diff --git a/config/BAM/bamClient/build.xml b/config/BAM/bamClient/build.xml new file mode 100644 index 0000000000..2da8620216 --- /dev/null +++ b/config/BAM/bamClient/build.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/BAM/bamClient/org.wso2.carbon.bam.client/pom.xml b/config/BAM/bamClient/org.wso2.carbon.bam.client/pom.xml new file mode 100644 index 0000000000..9ab40bf717 --- /dev/null +++ b/config/BAM/bamClient/org.wso2.carbon.bam.client/pom.xml @@ -0,0 +1,50 @@ + + 4.0.0 + + org.wso2.carbon.bam.client + sample + 1.0 + jar + + sample + http://maven.apache.org + + + UTF-8 + + + + + junit + junit + 3.8.1 + test + + + org.wso2.carbon + org.wso2.carbon.bam.analyzer.stub + 4.0.0 + + + org.wso2.carbon + org.wso2.carbon.bam.core.stub + 4.0.0 + + + org.wso2.carbon + org.wso2.carbon.bam.agent + 4.0.0 + + + org.wso2.carbon + org.wso2.carbon.bam2.service + 4.0.0 + + + org.wso2.carbon + org.wso2.carbon.authenticator.stub + 4.0.0 + + + diff --git a/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/java/org/wso2/carbon/bam/client/Client.java b/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/java/org/wso2/carbon/bam/client/Client.java new file mode 100644 index 0000000000..ee13533b3d --- /dev/null +++ b/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/java/org/wso2/carbon/bam/client/Client.java @@ -0,0 +1,90 @@ +package org.wso2.carbon.bam.client; + + +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; +import org.apache.axis2.context.ServiceContext; +import org.apache.axis2.transport.http.HTTPConstants; +import org.wso2.carbon.analytics.hive.stub.HiveScriptStoreServiceHiveScriptStoreException; +import org.wso2.carbon.analytics.hive.stub.HiveScriptStoreServiceStub; +import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub; +import org.wso2.carbon.authenticator.stub.LoginAuthenticationExceptionException; +import org.wso2.carbon.utils.FileUtil; + +import java.io.IOException; + +public class Client { + + private static String HIVE_SCRIPT_STORE_SERVICE = "HiveScriptStoreService"; + + private static HiveScriptStoreServiceStub hiveScriptStoreServiceStub; + + + public static void main(String[] args) + throws IOException, + LoginAuthenticationExceptionException { + + String trustStore = System.getProperty("carbon.home") + "/repository/resources/security"; + System.setProperty("javax.net.ssl.trustStore", trustStore + "/client-truststore.jks"); + System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon"); + + + String authenticationServiceURL = getProperty("bamUrl") + "AuthenticationAdmin"; + AuthenticationAdminStub authenticationAdminStub = new AuthenticationAdminStub(authenticationServiceURL); + ServiceClient client = authenticationAdminStub._getServiceClient(); + Options options = client.getOptions(); + options.setManageSession(true); + + authenticationAdminStub.login("admin", "admin", "localhost"); + + ServiceContext serviceContext = authenticationAdminStub. + _getServiceClient().getLastOperationContext().getServiceContext(); + String sessionCookie = (String) serviceContext.getProperty(HTTPConstants.COOKIE_STRING); + + String hiveScriptStoreServiceURL = getProperty("bamUrl") + HIVE_SCRIPT_STORE_SERVICE; + hiveScriptStoreServiceStub = new HiveScriptStoreServiceStub(hiveScriptStoreServiceURL); + + ServiceClient hiveScriptStoreServiceStubClient = hiveScriptStoreServiceStub._getServiceClient(); + Options hiveScriptStoreServiceStubOption = hiveScriptStoreServiceStubClient.getOptions(); + hiveScriptStoreServiceStubOption.setManageSession(true); + hiveScriptStoreServiceStubOption.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, sessionCookie); + + String apiVersionUsageSummaryContent = FileUtil.readFileToString(System.getProperty("configFilePath") + + "APIVersionUsageSummaryScript.hiveql"); + String apiVersionKeyUsageSummaryContent = FileUtil.readFileToString( System.getProperty("configFilePath") + + "APIVersionKeyUsageSummaryScript.hiveql"); + String apiVersionKeyLastAccessSummaryContent = FileUtil.readFileToString( System.getProperty("configFilePath") + + "APIVersionKeyLastAccessSummaryScript.hiveql"); + String apiVersionServiceTimeSummaryContent = FileUtil.readFileToString( System.getProperty("configFilePath") + + "APIVersionServiceTimeSummaryScript.hiveql"); + String keyUsageSummaryContent = FileUtil.readFileToString( System.getProperty("configFilePath") + + "KeyUsageSummaryScript.hiveql"); + + + + try { + + hiveScriptStoreServiceStub.saveHiveScript("APIVersionUsageSummaryScript",apiVersionUsageSummaryContent,"1 * * * * ? *"); + hiveScriptStoreServiceStub.saveHiveScript("APIVersionKeyUsageSummaryScript",apiVersionKeyUsageSummaryContent,"1 * * * * ? *"); + hiveScriptStoreServiceStub.saveHiveScript("APIVersionKeyLastAccessSummaryScript",apiVersionKeyLastAccessSummaryContent,"1 * * * * ? *"); + hiveScriptStoreServiceStub.saveHiveScript("APIVersionServiceTimeSummaryScript",apiVersionServiceTimeSummaryContent,"1 * * * * ? *"); + hiveScriptStoreServiceStub.saveHiveScript("KeyUsageSummaryScript",keyUsageSummaryContent,"1 * * * * ? *"); + System.out.println("BAM configured successfully for collecting API stats"); + return; + + } catch (HiveScriptStoreServiceHiveScriptStoreException e) { + e.printStackTrace(); + } + + + } + + private static String getProperty(String bamUrl) { + String defaultVal = "https://localhost:9443/services/"; + String result = System.getProperty(bamUrl); + if (result == null || result.length() == 0) { + result = defaultVal; + } + return result; + } +} diff --git a/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/APIVersionKeyLastAccessSummaryScript.hiveql b/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/APIVersionKeyLastAccessSummaryScript.hiveql new file mode 100644 index 0000000000..ae34bec21a --- /dev/null +++ b/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/APIVersionKeyLastAccessSummaryScript.hiveql @@ -0,0 +1,32 @@ +CREATE EXTERNAL TABLE IF NOT EXISTS APIVersionKeyLastAccess (key STRING, + api_version + STRING,consumerKey STRING,userId STRING, + context STRING,requestTime STRING) STORED BY + 'org.apache.hadoop.hive.cassandra.CassandraStorageHandler' WITH SERDEPROPERTIES ( "cassandra.host" = + "127.0.0.1", + "cassandra.port" = "9161","cassandra.ks.name" = "EVENT_KS", + "cassandra.ks.username" + = "admin","cassandra.ks.password" = "admin", + "cassandra.cf.name" = + "org_wso2_apimgt_statistics_request", + "cassandra.columns.mapping" = + ":key,payload_api_version, + payload_consumerKey,payload_userId,payload_context, + payload_requestTime" + ); +CREATE EXTERNAL TABLE IF NOT EXISTS APIVersionKeyLastAccessSummary (api_version STRING, + consumerKey STRING,userId STRING,context STRING, + requestTime DOUBLE) STORED BY + 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.table.create.query' = 'CREATE TABLE APIVersionKeyLastAccessSummary (api_version + VARCHAR(100), + consumerKey VARCHAR(100),userId VARCHAR(100), + context VARCHAR(100),requestTime + DOUBLE)' ); +insert overwrite table APIVersionKeyLastAccessSummary select api_version, + consumerKey,userId,context,max(cast(requestTime as DOUBLE)) from APIVersionKeyLastAccess group + by api_version, + consumerKey,userId,context; + + diff --git a/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/APIVersionKeyUsageSummaryScript.hiveql b/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/APIVersionKeyUsageSummaryScript.hiveql new file mode 100644 index 0000000000..ceeb0152e9 --- /dev/null +++ b/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/APIVersionKeyUsageSummaryScript.hiveql @@ -0,0 +1,30 @@ +CREATE EXTERNAL TABLE IF NOT EXISTS KeyUsage (key STRING, + context STRING,consumerKey + STRING,userId STRING, + version STRING,request STRING) STORED BY + 'org.apache.hadoop.hive.cassandra.CassandraStorageHandler' WITH SERDEPROPERTIES ( "cassandra.host" = + "127.0.0.1", + "cassandra.port" = "9161","cassandra.ks.name" = "EVENT_KS", + "cassandra.ks.username" + = "admin","cassandra.ks.password" = "admin", + "cassandra.cf.name" = + "org_wso2_apimgt_statistics_request", + "cassandra.columns.mapping" = + ":key,payload_context, + payload_consumerKey,payload_userId,payload_version, + payload_request" ); +CREATE EXTERNAL TABLE IF NOT EXISTS KeyUsageSummary (context STRING, + consumerKey STRING,userId + STRING,version STRING, + request INT) STORED BY + 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.table.create.query' = 'CREATE TABLE KeyUsageSummary (context + VARCHAR(100), + consumerKey VARCHAR(100),userId VARCHAR(100), + version VARCHAR(100),request INT)' ); +insert overwrite table KeyUsageSummary select context, + consumerKey,userId,version,sum(cast(request as INT)) from KeyUsage group by context, + consumerKey,userId,version; + + diff --git a/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/APIVersionServiceTimeSummaryScript.hiveql b/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/APIVersionServiceTimeSummaryScript.hiveql new file mode 100644 index 0000000000..8db843188f --- /dev/null +++ b/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/APIVersionServiceTimeSummaryScript.hiveql @@ -0,0 +1,28 @@ +CREATE EXTERNAL TABLE IF NOT EXISTS APIVersionServiceTime (key STRING, + api_version + STRING,context STRING,serviceTime STRING, + response STRING) STORED BY + 'org.apache.hadoop.hive.cassandra.CassandraStorageHandler' WITH SERDEPROPERTIES ( "cassandra.host" = + "127.0.0.1", + "cassandra.port" = "9161","cassandra.ks.name" = "EVENT_KS", + "cassandra.ks.username" + = "admin","cassandra.ks.password" = "admin", + "cassandra.cf.name" = + "org_wso2_apimgt_statistics_response", + "cassandra.columns.mapping" = + ":key,payload_api_version, + payload_context,payload_serviceTime,payload_response" ); +CREATE EXTERNAL TABLE IF NOT EXISTS APIVersionServiceTimeSummary (api_version STRING, + context + STRING,serviceTime INT,response INT) STORED BY + 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.table.create.query' = 'CREATE TABLE APIVersionServiceTimeSummary (api_version + VARCHAR(100), + context VARCHAR(100),serviceTime INT,response INT)' ); +insert overwrite table APIVersionServiceTimeSummary select api_version, + context,avg(cast(serviceTime as INT)),sum(cast(response as INT)) from APIVersionServiceTime + group by api_version, + context; + + diff --git a/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/APIVersionUsageSummaryScript.hiveql b/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/APIVersionUsageSummaryScript.hiveql new file mode 100644 index 0000000000..229164b9de --- /dev/null +++ b/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/APIVersionUsageSummaryScript.hiveql @@ -0,0 +1,29 @@ +CREATE EXTERNAL TABLE IF NOT EXISTS APIVersionUsage (key STRING, + api STRING,version + STRING,context STRING, + request STRING) STORED BY + 'org.apache.hadoop.hive.cassandra.CassandraStorageHandler' WITH SERDEPROPERTIES ( "cassandra.host" = + "127.0.0.1", + "cassandra.port" = "9161","cassandra.ks.name" = "EVENT_KS", + "cassandra.ks.username" + = "admin","cassandra.ks.password" = "admin", + "cassandra.cf.name" = + "org_wso2_apimgt_statistics_request", + "cassandra.columns.mapping" = + ":key,payload_api, + payload_version,payload_context,payload_request" ); +CREATE EXTERNAL TABLE IF NOT EXISTS APIVersionUsageSummary (api STRING, + version STRING,context + STRING,request INT) STORED BY 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES + ('wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.table.create.query' = 'CREATE TABLE APIVersionUsageSummary (api + VARCHAR(100), + version VARCHAR(100),context VARCHAR(100), + request INT)' ); +insert overwrite table APIVersionUsageSummary select api, + version,context,sum(cast(request as + INT)) from APIVersionUsage group by api, + version,context; + + diff --git a/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/KeyUsageSummaryScript.hiveql b/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/KeyUsageSummaryScript.hiveql new file mode 100644 index 0000000000..94c823b35b --- /dev/null +++ b/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/KeyUsageSummaryScript.hiveql @@ -0,0 +1,30 @@ +CREATE EXTERNAL TABLE IF NOT EXISTS APIVersionKeyUsage (key STRING, + api STRING,version + STRING,consumerKey STRING, + userId STRING,request STRING) STORED BY + 'org.apache.hadoop.hive.cassandra.CassandraStorageHandler' WITH SERDEPROPERTIES ( "cassandra.host" = + "127.0.0.1", + "cassandra.port" = "9161","cassandra.ks.name" = "EVENT_KS", + "cassandra.ks.username" + = "admin","cassandra.ks.password" = "admin", + "cassandra.cf.name" = + "org_wso2_apimgt_statistics_request", + "cassandra.columns.mapping" = + ":key,payload_api, + payload_version,payload_consumerKey,payload_userId, + payload_request" ); +CREATE EXTERNAL TABLE IF NOT EXISTS APIVersionKeyUsageSummary (api STRING, + version + STRING,consumerKey STRING,userId STRING, + request DOUBLE) STORED BY + 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.table.create.query' = 'CREATE TABLE APIVersionKeyUsageSummary (api + VARCHAR(100), + version VARCHAR(100),consumerKey VARCHAR(100), + userId VARCHAR(100),request DOUBLE)' ); +insert overwrite table APIVersionKeyUsageSummary select api, + version,consumerKey,userId,sum(cast(request as DOUBLE)) from APIVersionKeyUsage group by api, + version,consumerKey,userId; + + diff --git a/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/api-manager.xml b/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/api-manager.xml new file mode 100644 index 0000000000..eb6969085b --- /dev/null +++ b/config/BAM/bamClient/org.wso2.carbon.bam.client/src/main/resources/api-manager.xml @@ -0,0 +1,30 @@ + + + jdbc:h2:target/repository/database/WSO2AM_DB + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + 5 + + + false + 7612 + https://localhost:9444/ + admin + admin + repository/resources/security/client-truststore.jks + wso2carbon + + + https://localhost:9443/services/ + admin + admin + + + https://localhost:9443/services/ + admin + admin + + diff --git a/config/api-manager.xml b/config/api-manager.xml new file mode 100644 index 0000000000..35d81e3608 --- /dev/null +++ b/config/api-manager.xml @@ -0,0 +1,471 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}${carbon.context}/services/ + + admin + + admin + + + + + + X-JWT-Assertion + + + + + + + + + + + + + + + + + + + + + + + + + + + Production and Sandbox + + https://${carbon.local.ip}:${mgt.transport.https.port}${carbon.context}/services/ + + admin + + admin + + http://${carbon.local.ip}:${http.nio.port},https://${carbon.local.ip}:${https.nio.port} + + + + + true + + + true + + + referer + + + + + false + + + + + + false + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + 7612 + + + tcp://localhost:7612/ + + + admin + + + admin + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}${carbon.context}/services/ + + + admin + + + admin + + false + + + + false + + + + ThriftClient + 10397 + 10000 + 10397 + + true + + + + + + + + /oauth2/token + + + https://${carbon.local.ip}:${https.nio.port}/revoke + + + false + + + + + + + true + + + + + + true + + + subscriber + + + + + + true + false + https://${carbon.local.ip}:${mgt.transport.https.port}/store + + false + + false + + + true + + + true + + + + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/publisher + + + + + + + + + + + + + false + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + + diff --git a/config/rxts/api.rxt b/config/rxts/api.rxt new file mode 100644 index 0000000000..213c150bf9 --- /dev/null +++ b/config/rxts/api.rxt @@ -0,0 +1,238 @@ + + + /apimgt/applicationdata/provider/@{overview_provider}/@{overview_name}/@{overview_version}/api + overview_name + + + + + + + + + + + + + + + + + Provider + + + Name + + + Context + + + Version + + + Is Default Version + + false + true + + + + Transports + + + Redirect URL + + + Advertise Only + + + API Owner + + + Description + + + Endpoint Type + + Secured + Non Secured + + + + Endpoint URL + + + Implementation + + + Endpoint Config + + + Endpoint Username + + + Endpoint Password + + + Sandbox URL + + + InSequence + + + OutSequence + + + FaultSequence + + + WSDL + + + WADL + + + Thumbnail + + + Visibility + + + Visible Roles + + + Visible Tenants + + + Is Latest + + false + true + + + + Tier + + Gold + Silver + Other + + + + Status + + CREATED + PUBLISHED + PROTOTYPED + RETIRED + DEPRECATED + BLOCKED + + + + Technical Owner + + + Technical Owner Email + + + Business Owner + + + Business Owner Email + + + Subscription Availability + + + Tenants + + + Response Caching + + Enabled + Disabled + + + + Cache Timeout + + + Destination Stats Enabled + + Enabled + Disabled + + +
+ + + URL Pattern + HTTP Verb + Auth Type + Mediation Script + + + URL Pattern0 + + + HTTP Verb0 + + + Auth Type0 + + + Mediation Script0 + + + URL Pattern1 + + + HTTP Verb1 + + + Auth Type1 + + + Mediation Script1 + + + URL Pattern2 + + + HTTP Verb2 + + + Auth Type2 + + + Mediation Script2 + + + URL Pattern3 + + + HTTP Verb3 + + + Auth Type3 + + + Mediation Script3 + + + URL Pattern4 + + + HTTP Verb4 + + + Auth Type4 + + + Mediation Script4 + +
+
+ +
diff --git a/config/rxts/documentation.rxt b/config/rxts/documentation.rxt new file mode 100644 index 0000000000..1b6bc205d9 --- /dev/null +++ b/config/rxts/documentation.rxt @@ -0,0 +1,63 @@ + + + /apimgt/applicationdata/provider/@{overview_apiBasePath}/documentation/@{overview_name} + overview_name + + + + + + + + + + + Name + + + ApiBasePath + + + Summary + + + ApiBasePath + + + Type + + How To + Samples and SDK + Public Forum + Support Forum + API Message Formats + Other + + + + Source Type + + In Line + URL + File + + + + Visibility + + API_Level + Private + Shared + + + + Source URL + + + File Path + +
+
+ +
+ diff --git a/config/rxts/provider.rxt b/config/rxts/provider.rxt new file mode 100644 index 0000000000..e40a44fe9c --- /dev/null +++ b/config/rxts/provider.rxt @@ -0,0 +1,45 @@ + + + /providers/@{overview_version}/@{overview_name} + overview_name + + + + + + + + + + + Name + + + Version + + + Description + + + Endpoint URL + + + WSDL + + + Tags + + + + Tier Availability + + Gold + Silver + Other + + +
+
+ +
+ diff --git a/config/wso2server.bat b/config/wso2server.bat new file mode 100644 index 0000000000..3261136e2a --- /dev/null +++ b/config/wso2server.bat @@ -0,0 +1,173 @@ +@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 %* + +:checkJdk16 +"%JAVA_HOME%\bin\java" -version 2>&1 | findstr /r "1.[6|7]" >NUL +IF ERRORLEVEL 1 goto unknownJdk +goto jdk16 + +:unknownJdk +echo Starting WSO2 Carbon (in unsupported JDK) +echo [ERROR] CARBON is supported only on JDK 1.6 and 1.7 +goto jdk16 + +:jdk16 +goto runServer + +rem ----------------- Execute The Requested Command ---------------------------- + +:runServer +cd %CARBON_HOME% + +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=256m -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%" -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" -Dcarbon.logs.path="%CARBON_HOME%\repository\logs" -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.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 -DapplyPatches + +: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/config/wso2server.sh b/config/wso2server.sh new file mode 100644 index 0000000000..6aed64025e --- /dev/null +++ b/config/wso2server.sh @@ -0,0 +1,298 @@ +#!/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 ---------------------------------------------- +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" + 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 >&- ; then + echo "Process is already running" + exit 0 + fi + fi + export CARBON_HOME=$CARBON_HOME +# using nohup bash to avoid erros in solaris OS.TODO + nohup bash $CARBON_HOME/bin/wso2server.sh > /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 bash to avoid erros in solaris OS.TODO + nohup bash $CARBON_HOME/bin/wso2server.sh > /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_16=`$JAVA_HOME/bin/java -version 2>&1 | grep "1.[6|7]"` +if [ "$jdk_16" = "" ]; then + echo " Starting WSO2 Carbon (in unsupported JDK)" + echo " [ERROR] CARBON is supported only on JDK 1.6 and 1.7" +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" + +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=256m \ + -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" \ + -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager \ + -Djava.util.logging.config.file="$CARBON_HOME/repository/conf/etc/logging-bridge.properties" \ + -Dcarbon.config.dir.path="$CARBON_HOME/repository/conf" \ + -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.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 \ + -DapplyPatches \ + org.wso2.carbon.bootstrap.Bootstrap $* + status=$? +done diff --git a/design-docs/data-model/iteration1/1-entities-with-cardinality.jpg b/design-docs/data-model/iteration1/1-entities-with-cardinality.jpg new file mode 100644 index 0000000000..64afd725df Binary files /dev/null and b/design-docs/data-model/iteration1/1-entities-with-cardinality.jpg differ diff --git a/design-docs/data-model/iteration1/2-mapped-to-tree-hierarchy.jpg b/design-docs/data-model/iteration1/2-mapped-to-tree-hierarchy.jpg new file mode 100644 index 0000000000..0b53204dda Binary files /dev/null and b/design-docs/data-model/iteration1/2-mapped-to-tree-hierarchy.jpg differ diff --git a/design-docs/data-model/iteration1/3-consumers_and_APIs.jpg b/design-docs/data-model/iteration1/3-consumers_and_APIs.jpg new file mode 100644 index 0000000000..b23c3eba5a Binary files /dev/null and b/design-docs/data-model/iteration1/3-consumers_and_APIs.jpg differ diff --git a/design-docs/data-model/iteration1/4-storage-for-search-terms.jpg b/design-docs/data-model/iteration1/4-storage-for-search-terms.jpg new file mode 100644 index 0000000000..719de2cb2c Binary files /dev/null and b/design-docs/data-model/iteration1/4-storage-for-search-terms.jpg differ diff --git a/design-docs/data-model/iteration1/5-birds-eye.jpg b/design-docs/data-model/iteration1/5-birds-eye.jpg new file mode 100644 index 0000000000..16793b56b5 Binary files /dev/null and b/design-docs/data-model/iteration1/5-birds-eye.jpg differ diff --git a/design-docs/data-model/iteration1/compressed/1-entities-with-cardinality-21-02-2012.jpg b/design-docs/data-model/iteration1/compressed/1-entities-with-cardinality-21-02-2012.jpg new file mode 100644 index 0000000000..3b7438a13f Binary files /dev/null and b/design-docs/data-model/iteration1/compressed/1-entities-with-cardinality-21-02-2012.jpg differ diff --git a/design-docs/data-model/iteration1/compressed/2-mapped-to-tree-hierarchy-21-02-2012.jpg b/design-docs/data-model/iteration1/compressed/2-mapped-to-tree-hierarchy-21-02-2012.jpg new file mode 100644 index 0000000000..c6ff376de8 Binary files /dev/null and b/design-docs/data-model/iteration1/compressed/2-mapped-to-tree-hierarchy-21-02-2012.jpg differ diff --git a/design-docs/data-model/iteration1/compressed/3-consumers_and_APIs-21-02-2012.jpg b/design-docs/data-model/iteration1/compressed/3-consumers_and_APIs-21-02-2012.jpg new file mode 100644 index 0000000000..14a0a3cffb Binary files /dev/null and b/design-docs/data-model/iteration1/compressed/3-consumers_and_APIs-21-02-2012.jpg differ diff --git a/design-docs/data-model/iteration1/compressed/4-storage-for-search-terms-21-02-2012.jpg b/design-docs/data-model/iteration1/compressed/4-storage-for-search-terms-21-02-2012.jpg new file mode 100644 index 0000000000..af7bac3c38 Binary files /dev/null and b/design-docs/data-model/iteration1/compressed/4-storage-for-search-terms-21-02-2012.jpg differ diff --git a/design-docs/data-model/iteration1/compressed/5-birds-eye-21-02-2012.jpg b/design-docs/data-model/iteration1/compressed/5-birds-eye-21-02-2012.jpg new file mode 100644 index 0000000000..817e7279cb Binary files /dev/null and b/design-docs/data-model/iteration1/compressed/5-birds-eye-21-02-2012.jpg differ diff --git a/design-docs/data-model/iteration2/1-Tier-22-02-2012.jpg b/design-docs/data-model/iteration2/1-Tier-22-02-2012.jpg new file mode 100644 index 0000000000..e8b0093770 Binary files /dev/null and b/design-docs/data-model/iteration2/1-Tier-22-02-2012.jpg differ diff --git a/design-docs/data-model/iteration2/2-entities-with-cardinality-22-02-2012.jpg b/design-docs/data-model/iteration2/2-entities-with-cardinality-22-02-2012.jpg new file mode 100644 index 0000000000..a7d5f041ef Binary files /dev/null and b/design-docs/data-model/iteration2/2-entities-with-cardinality-22-02-2012.jpg differ diff --git a/design-docs/data-model/iteration2/3-mapped-to-tree-hierarchy-22-02-2012.jpg b/design-docs/data-model/iteration2/3-mapped-to-tree-hierarchy-22-02-2012.jpg new file mode 100644 index 0000000000..a8e97cb04e Binary files /dev/null and b/design-docs/data-model/iteration2/3-mapped-to-tree-hierarchy-22-02-2012.jpg differ diff --git a/design-docs/data-model/iteration2/4-Config-Data-Movedout-22-02-2012.jpg b/design-docs/data-model/iteration2/4-Config-Data-Movedout-22-02-2012.jpg new file mode 100644 index 0000000000..98321ad32d Binary files /dev/null and b/design-docs/data-model/iteration2/4-Config-Data-Movedout-22-02-2012.jpg differ diff --git a/design-docs/data-model/iteration2/5-birds-eye-22-02-2012.jpg b/design-docs/data-model/iteration2/5-birds-eye-22-02-2012.jpg new file mode 100644 index 0000000000..39e45b658f Binary files /dev/null and b/design-docs/data-model/iteration2/5-birds-eye-22-02-2012.jpg differ diff --git a/design-docs/data-model/iteration2/Property_for_Tier.jpg b/design-docs/data-model/iteration2/Property_for_Tier.jpg new file mode 100644 index 0000000000..26aea9d920 Binary files /dev/null and b/design-docs/data-model/iteration2/Property_for_Tier.jpg differ diff --git a/design-docs/data-model/iteration3/1-entities-with-cardinality.jpg b/design-docs/data-model/iteration3/1-entities-with-cardinality.jpg new file mode 100644 index 0000000000..71cc57faaa Binary files /dev/null and b/design-docs/data-model/iteration3/1-entities-with-cardinality.jpg differ diff --git a/design-docs/data-model/iteration3/22022012109.jpg b/design-docs/data-model/iteration3/22022012109.jpg new file mode 100644 index 0000000000..9488dda59b Binary files /dev/null and b/design-docs/data-model/iteration3/22022012109.jpg differ diff --git a/design-docs/data-model/iteration3/22022012111.jpg b/design-docs/data-model/iteration3/22022012111.jpg new file mode 100644 index 0000000000..34e1c76537 Binary files /dev/null and b/design-docs/data-model/iteration3/22022012111.jpg differ diff --git a/design-docs/data-model/iteration3/22022012113.jpg b/design-docs/data-model/iteration3/22022012113.jpg new file mode 100644 index 0000000000..c845598cf8 Binary files /dev/null and b/design-docs/data-model/iteration3/22022012113.jpg differ diff --git a/design-docs/data-model/iteration3/22022012114.jpg b/design-docs/data-model/iteration3/22022012114.jpg new file mode 100644 index 0000000000..136a3d0217 Binary files /dev/null and b/design-docs/data-model/iteration3/22022012114.jpg differ diff --git a/design-docs/data-model/iteration3/5-birds-eye.jpg b/design-docs/data-model/iteration3/5-birds-eye.jpg new file mode 100644 index 0000000000..1bed7aebcb Binary files /dev/null and b/design-docs/data-model/iteration3/5-birds-eye.jpg differ diff --git a/design-docs/data-model/iteration3/6-Classification-of-data.jpg b/design-docs/data-model/iteration3/6-Classification-of-data.jpg new file mode 100644 index 0000000000..6cbc39ca35 Binary files /dev/null and b/design-docs/data-model/iteration3/6-Classification-of-data.jpg differ diff --git a/design-docs/data-model/iteration4/rdbms_model.dia b/design-docs/data-model/iteration4/rdbms_model.dia new file mode 100644 index 0000000000..0d36e5b1a5 Binary files /dev/null and b/design-docs/data-model/iteration4/rdbms_model.dia differ diff --git a/design-docs/data-model/iteration4/rdbms_model.jpg b/design-docs/data-model/iteration4/rdbms_model.jpg new file mode 100644 index 0000000000..4c6981ca97 Binary files /dev/null and b/design-docs/data-model/iteration4/rdbms_model.jpg differ diff --git a/design-docs/mockscreens/HomePage.png b/design-docs/mockscreens/HomePage.png new file mode 100644 index 0000000000..7e0587cc8c Binary files /dev/null and b/design-docs/mockscreens/HomePage.png differ diff --git a/design-docs/mockscreens/HomePage.screen b/design-docs/mockscreens/HomePage.screen new file mode 100644 index 0000000000..9a2ac74552 --- /dev/null +++ b/design-docs/mockscreens/HomePage.screen @@ -0,0 +1,139 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/LoggedIn-Application-HomePage.png b/design-docs/mockscreens/LoggedIn-Application-HomePage.png new file mode 100644 index 0000000000..d2368c3ff0 Binary files /dev/null and b/design-docs/mockscreens/LoggedIn-Application-HomePage.png differ diff --git a/design-docs/mockscreens/LoggedIn-Application-HomePage.screen b/design-docs/mockscreens/LoggedIn-Application-HomePage.screen new file mode 100644 index 0000000000..11fbef760a --- /dev/null +++ b/design-docs/mockscreens/LoggedIn-Application-HomePage.screen @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/LoggedIn-Application-Services-HomePage.png b/design-docs/mockscreens/LoggedIn-Application-Services-HomePage.png new file mode 100644 index 0000000000..015a975c2b Binary files /dev/null and b/design-docs/mockscreens/LoggedIn-Application-Services-HomePage.png differ diff --git a/design-docs/mockscreens/LoggedIn-Application-Services-HomePage.screen b/design-docs/mockscreens/LoggedIn-Application-Services-HomePage.screen new file mode 100644 index 0000000000..b838ca7668 --- /dev/null +++ b/design-docs/mockscreens/LoggedIn-Application-Services-HomePage.screen @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/LoggedIn-Service-HomePage.png b/design-docs/mockscreens/LoggedIn-Service-HomePage.png new file mode 100644 index 0000000000..ab80f9722d Binary files /dev/null and b/design-docs/mockscreens/LoggedIn-Service-HomePage.png differ diff --git a/design-docs/mockscreens/LoggedIn-Service-HomePage.screen b/design-docs/mockscreens/LoggedIn-Service-HomePage.screen new file mode 100644 index 0000000000..5426b6f431 --- /dev/null +++ b/design-docs/mockscreens/LoggedIn-Service-HomePage.screen @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/ServiceDetails.png b/design-docs/mockscreens/ServiceDetails.png new file mode 100644 index 0000000000..a364472b74 Binary files /dev/null and b/design-docs/mockscreens/ServiceDetails.png differ diff --git a/design-docs/mockscreens/ServiceDetails.screen b/design-docs/mockscreens/ServiceDetails.screen new file mode 100644 index 0000000000..ad82013e34 --- /dev/null +++ b/design-docs/mockscreens/ServiceDetails.screen @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/ServiceListing b/design-docs/mockscreens/ServiceListing new file mode 100644 index 0000000000..bc2314b129 Binary files /dev/null and b/design-docs/mockscreens/ServiceListing differ diff --git a/design-docs/mockscreens/ServiceListing.screen b/design-docs/mockscreens/ServiceListing.screen new file mode 100644 index 0000000000..735ec28928 --- /dev/null +++ b/design-docs/mockscreens/ServiceListing.screen @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/0-login.screen b/design-docs/mockscreens/provider/0-login.screen new file mode 100644 index 0000000000..86ac6dbab8 --- /dev/null +++ b/design-docs/mockscreens/provider/0-login.screen @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/1.1-api-add.screen b/design-docs/mockscreens/provider/1.1-api-add.screen new file mode 100644 index 0000000000..8d47c96303 --- /dev/null +++ b/design-docs/mockscreens/provider/1.1-api-add.screen @@ -0,0 +1,121 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/1.2-api-add.screen b/design-docs/mockscreens/provider/1.2-api-add.screen new file mode 100644 index 0000000000..bcb9a13f8b --- /dev/null +++ b/design-docs/mockscreens/provider/1.2-api-add.screen @@ -0,0 +1,121 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/1.3-api-add.screen b/design-docs/mockscreens/provider/1.3-api-add.screen new file mode 100644 index 0000000000..a5e1ec7822 --- /dev/null +++ b/design-docs/mockscreens/provider/1.3-api-add.screen @@ -0,0 +1,130 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/2.1-api-listing.screen b/design-docs/mockscreens/provider/2.1-api-listing.screen new file mode 100644 index 0000000000..90b95a488a --- /dev/null +++ b/design-docs/mockscreens/provider/2.1-api-listing.screen @@ -0,0 +1,189 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/2.2-api-listing.screen b/design-docs/mockscreens/provider/2.2-api-listing.screen new file mode 100644 index 0000000000..09a278420b --- /dev/null +++ b/design-docs/mockscreens/provider/2.2-api-listing.screen @@ -0,0 +1,189 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/2.3-api-listing.screen b/design-docs/mockscreens/provider/2.3-api-listing.screen new file mode 100644 index 0000000000..88a0130ce6 --- /dev/null +++ b/design-docs/mockscreens/provider/2.3-api-listing.screen @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/3-api-details.screen b/design-docs/mockscreens/provider/3-api-details.screen new file mode 100644 index 0000000000..6d5440faa0 --- /dev/null +++ b/design-docs/mockscreens/provider/3-api-details.screen @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/4-api-versions.screen b/design-docs/mockscreens/provider/4-api-versions.screen new file mode 100644 index 0000000000..fd7211c5bd --- /dev/null +++ b/design-docs/mockscreens/provider/4-api-versions.screen @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/5-api-edit.screen b/design-docs/mockscreens/provider/5-api-edit.screen new file mode 100644 index 0000000000..63416e49ae --- /dev/null +++ b/design-docs/mockscreens/provider/5-api-edit.screen @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/6-api-users.screen b/design-docs/mockscreens/provider/6-api-users.screen new file mode 100644 index 0000000000..e61585b30e --- /dev/null +++ b/design-docs/mockscreens/provider/6-api-users.screen @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/7-api-docs.screen b/design-docs/mockscreens/provider/7-api-docs.screen new file mode 100644 index 0000000000..c136f81d8e --- /dev/null +++ b/design-docs/mockscreens/provider/7-api-docs.screen @@ -0,0 +1,116 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/APIDetails-SelectPackage.screen b/design-docs/mockscreens/provider/APIDetails-SelectPackage.screen new file mode 100644 index 0000000000..7194eb698b --- /dev/null +++ b/design-docs/mockscreens/provider/APIDetails-SelectPackage.screen @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/APIDetails.png b/design-docs/mockscreens/provider/APIDetails.png new file mode 100644 index 0000000000..a761699480 Binary files /dev/null and b/design-docs/mockscreens/provider/APIDetails.png differ diff --git a/design-docs/mockscreens/provider/APIDetails.screen b/design-docs/mockscreens/provider/APIDetails.screen new file mode 100644 index 0000000000..e3ed74a657 --- /dev/null +++ b/design-docs/mockscreens/provider/APIDetails.screen @@ -0,0 +1,137 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/APIDocumentation.screen b/design-docs/mockscreens/provider/APIDocumentation.screen new file mode 100644 index 0000000000..3d8d412a25 --- /dev/null +++ b/design-docs/mockscreens/provider/APIDocumentation.screen @@ -0,0 +1,114 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/APIs-published-by-a-provider.png b/design-docs/mockscreens/provider/APIs-published-by-a-provider.png new file mode 100644 index 0000000000..5d817aa423 Binary files /dev/null and b/design-docs/mockscreens/provider/APIs-published-by-a-provider.png differ diff --git a/design-docs/mockscreens/provider/AddNewAPI.screen b/design-docs/mockscreens/provider/AddNewAPI.screen new file mode 100644 index 0000000000..acdac9d44d --- /dev/null +++ b/design-docs/mockscreens/provider/AddNewAPI.screen @@ -0,0 +1,105 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/AllAPIProviders.png b/design-docs/mockscreens/provider/AllAPIProviders.png new file mode 100644 index 0000000000..19c2181204 Binary files /dev/null and b/design-docs/mockscreens/provider/AllAPIProviders.png differ diff --git a/design-docs/mockscreens/provider/CreateNewAPIVersion.screen b/design-docs/mockscreens/provider/CreateNewAPIVersion.screen new file mode 100644 index 0000000000..bb5f45524d --- /dev/null +++ b/design-docs/mockscreens/provider/CreateNewAPIVersion.screen @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/KeyMgt-for-API.png b/design-docs/mockscreens/provider/KeyMgt-for-API.png new file mode 100644 index 0000000000..114bfe2f57 Binary files /dev/null and b/design-docs/mockscreens/provider/KeyMgt-for-API.png differ diff --git a/design-docs/mockscreens/provider/ListOfProviders.screen b/design-docs/mockscreens/provider/ListOfProviders.screen new file mode 100644 index 0000000000..85b20be1d1 --- /dev/null +++ b/design-docs/mockscreens/provider/ListOfProviders.screen @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/MyPublishedAPIs-Keymanagement.screen b/design-docs/mockscreens/provider/MyPublishedAPIs-Keymanagement.screen new file mode 100644 index 0000000000..789fd0b25c --- /dev/null +++ b/design-docs/mockscreens/provider/MyPublishedAPIs-Keymanagement.screen @@ -0,0 +1,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/MyPublishedAPIs.screen b/design-docs/mockscreens/provider/MyPublishedAPIs.screen new file mode 100644 index 0000000000..12a313c234 --- /dev/null +++ b/design-docs/mockscreens/provider/MyPublishedAPIs.screen @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/RegisterEditProvider.screen b/design-docs/mockscreens/provider/RegisterEditProvider.screen new file mode 100644 index 0000000000..0ee2430c6d --- /dev/null +++ b/design-docs/mockscreens/provider/RegisterEditProvider.screen @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/UpdateAccessControl.screen b/design-docs/mockscreens/provider/UpdateAccessControl.screen new file mode 100644 index 0000000000..df9bfbf7de --- /dev/null +++ b/design-docs/mockscreens/provider/UpdateAccessControl.screen @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/design-docs/mockscreens/provider/screenshots/16-02-2012/API_Package_selection.png b/design-docs/mockscreens/provider/screenshots/16-02-2012/API_Package_selection.png new file mode 100644 index 0000000000..7fb3b9ee99 Binary files /dev/null and b/design-docs/mockscreens/provider/screenshots/16-02-2012/API_Package_selection.png differ diff --git a/design-docs/mockscreens/provider/screenshots/16-02-2012/APIs_published_by_provider.png b/design-docs/mockscreens/provider/screenshots/16-02-2012/APIs_published_by_provider.png new file mode 100644 index 0000000000..16e7daea67 Binary files /dev/null and b/design-docs/mockscreens/provider/screenshots/16-02-2012/APIs_published_by_provider.png differ diff --git a/design-docs/mockscreens/provider/screenshots/16-02-2012/AddNewAPI.png b/design-docs/mockscreens/provider/screenshots/16-02-2012/AddNewAPI.png new file mode 100644 index 0000000000..8493de3d0f Binary files /dev/null and b/design-docs/mockscreens/provider/screenshots/16-02-2012/AddNewAPI.png differ diff --git a/design-docs/mockscreens/provider/screenshots/16-02-2012/Add_API_Documentation.png b/design-docs/mockscreens/provider/screenshots/16-02-2012/Add_API_Documentation.png new file mode 100644 index 0000000000..55a276483f Binary files /dev/null and b/design-docs/mockscreens/provider/screenshots/16-02-2012/Add_API_Documentation.png differ diff --git a/design-docs/mockscreens/provider/screenshots/16-02-2012/All_API_Providers.png b/design-docs/mockscreens/provider/screenshots/16-02-2012/All_API_Providers.png new file mode 100644 index 0000000000..26b34edfc3 Binary files /dev/null and b/design-docs/mockscreens/provider/screenshots/16-02-2012/All_API_Providers.png differ diff --git a/design-docs/mockscreens/provider/screenshots/16-02-2012/Applications_using_an_API.png b/design-docs/mockscreens/provider/screenshots/16-02-2012/Applications_using_an_API.png new file mode 100644 index 0000000000..20a067d41f Binary files /dev/null and b/design-docs/mockscreens/provider/screenshots/16-02-2012/Applications_using_an_API.png differ diff --git a/design-docs/mockscreens/provider/screenshots/16-02-2012/EditAPI.png b/design-docs/mockscreens/provider/screenshots/16-02-2012/EditAPI.png new file mode 100644 index 0000000000..7adc00c488 Binary files /dev/null and b/design-docs/mockscreens/provider/screenshots/16-02-2012/EditAPI.png differ diff --git a/design-docs/mockscreens/provider/screenshots/16-02-2012/Manage_API_Versions.png b/design-docs/mockscreens/provider/screenshots/16-02-2012/Manage_API_Versions.png new file mode 100644 index 0000000000..a276b36508 Binary files /dev/null and b/design-docs/mockscreens/provider/screenshots/16-02-2012/Manage_API_Versions.png differ diff --git a/design-docs/mockscreens/provider/screenshots/16-02-2012/Policy_Template_Definition.png b/design-docs/mockscreens/provider/screenshots/16-02-2012/Policy_Template_Definition.png new file mode 100644 index 0000000000..ddd5487492 Binary files /dev/null and b/design-docs/mockscreens/provider/screenshots/16-02-2012/Policy_Template_Definition.png differ diff --git a/design-docs/mockscreens/provider/screenshots/16-02-2012/Signup.png b/design-docs/mockscreens/provider/screenshots/16-02-2012/Signup.png new file mode 100644 index 0000000000..45a71fbfdb Binary files /dev/null and b/design-docs/mockscreens/provider/screenshots/16-02-2012/Signup.png differ diff --git a/docs/resources/css/site.css b/docs/resources/css/site.css new file mode 100644 index 0000000000..12488c5097 --- /dev/null +++ b/docs/resources/css/site.css @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2005-2010, WSO2 Inc. (http://wso2.com) 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. + * + */ + +body { + color: #000; + font-size: 11px; + font-family: Verdana, Arial, Helvetica, sans-serif; + background-image: url( ../images/esb-docs-bg.gif ); + background-repeat: repeat-x; + background-attachment: scroll; + background-position: left top; + text-decoration: none; + text-align: left; + padding: 0px; + list-style-type: square; + list-style-position: outside; +} + +div#banner { + background-image: url(../images/esb-docs-header.gif); + background-repeat: no-repeat; + background-position: left top; + height: 38px; + padding-top: 30px; + padding-left: 265px; + border-bottom: 0px; +} + +div#banner span#bannerLeft { + font-size: 180%; + color: #542988; +} + +div#breadcrumbs { + background-color: transparent; + border-top: solid 0px; + border-bottom: solid 0px; + height: 23px; + padding-top: 5px; + padding-left: 20px; + padding-right: 20px; +} + +div#leftColumn { + margin-left: 0px; + margin-top: 0px; + border-top: 0px; + background-color: #F7F7F7; + border-left: solid 0px; + border-right: solid 1px #542988; + border-bottom: solid 1px #542988; +} + +div#leftColumn div#navcolumn { + padding-left: 20px; + padding-right: 20px; + padding-top: 15px; + background-color: #F7F7F7; +} + + +div#contentBox { + margin-top: 10px; + margin-bottom: 15px; + font-size: 12px; +} + +div#navcolumn h5 { + margin-bottom: 2px; + padding-bottom: 2px; + border-bottom: solid 1px #542988; + font-size: 110%; +} + +#navcolumn li { + padding-top: 2px; + padding-bottom: 2px; +} + +p { +} + +td { + background-color: #f8f8f8; + padding: 3px 5px; + outline-color: gray; + outline-width: 0; +} + +a:link { + color: #36c; +} + +a:visited { +} + +a:hover { + color: #7f7f7f; +} + +a:active { +} + +body, td, select, input, li { + line-height: 18px; +} + +h1 { + color: #333; + font-size: 18px; + font-weight: bold; + font-style: normal; + line-height: normal; + background-image: none; + background-repeat: no-repeat; + background-attachment: scroll; + background-position: left top; + text-decoration: none; + height: 30px; + padding-bottom: 2px; + border-bottom: 1px solid #663399; +} + +h2 { + color: black; + font-size: 15px; + font-weight: bold; + line-height: 24px; + border-bottom: 0px; + border-left: solid 1px #ccc; + border-right: solid 1px #ccc; + border-top: 0px; + background-color: #B5B5B5; + padding-left: 5px; + padding-top: 0px; + padding-bottom: 0px; + color: #fff; +} + +h3 { + color: #3a3a3a; + font-size: 12px; + font-weight: bold; + padding-top: 10px; + padding-bottom: 4px; + padding-left: 10px; + border-left: 0px; + border-right: 0px; + border-top: 0px; + border-bottom: 1px solid #ccc; + background-image: url(../images/table-header.gif); + background-position: left bottom; + background-repeat: repeat-x; + background-color: transparent; +} + +table { + background-color: #cbcbcb; + margin: 0; + padding: 1px; + border-style: solid; + border-width: 0; +} + +th { + padding-left: 5px; +} + +img { + background-color: gray; + padding: 1px; +} +div#footer { + background-color: #ccc; + padding-right: 20px; +} \ No newline at end of file diff --git a/docs/resources/images/add-user.png b/docs/resources/images/add-user.png new file mode 100644 index 0000000000..fc72b127e2 Binary files /dev/null and b/docs/resources/images/add-user.png differ diff --git a/docs/resources/images/add.gif b/docs/resources/images/add.gif new file mode 100644 index 0000000000..4bfdd7983e Binary files /dev/null and b/docs/resources/images/add.gif differ diff --git a/docs/resources/images/browse-registry.png b/docs/resources/images/browse-registry.png new file mode 100644 index 0000000000..7671f3c21b Binary files /dev/null and b/docs/resources/images/browse-registry.png differ diff --git a/docs/resources/images/delete.gif b/docs/resources/images/delete.gif new file mode 100644 index 0000000000..471f55c15f Binary files /dev/null and b/docs/resources/images/delete.gif differ diff --git a/docs/resources/images/dep-tracking.png b/docs/resources/images/dep-tracking.png new file mode 100644 index 0000000000..35d2238d21 Binary files /dev/null and b/docs/resources/images/dep-tracking.png differ diff --git a/docs/resources/images/edit.gif b/docs/resources/images/edit.gif new file mode 100644 index 0000000000..f44da7badd Binary files /dev/null and b/docs/resources/images/edit.gif differ diff --git a/docs/resources/images/editing-registry-entry.png b/docs/resources/images/editing-registry-entry.png new file mode 100644 index 0000000000..519dedec85 Binary files /dev/null and b/docs/resources/images/editing-registry-entry.png differ diff --git a/docs/resources/images/endpoint-info.png b/docs/resources/images/endpoint-info.png new file mode 100644 index 0000000000..f4d395cf06 Binary files /dev/null and b/docs/resources/images/endpoint-info.png differ diff --git a/docs/resources/images/endpoint-mbean.png b/docs/resources/images/endpoint-mbean.png new file mode 100644 index 0000000000..3c66dd3820 Binary files /dev/null and b/docs/resources/images/endpoint-mbean.png differ diff --git a/docs/resources/images/endpoint-off.png b/docs/resources/images/endpoint-off.png new file mode 100644 index 0000000000..298bf32dc2 Binary files /dev/null and b/docs/resources/images/endpoint-off.png differ diff --git a/docs/resources/images/endpoint-state.png b/docs/resources/images/endpoint-state.png new file mode 100644 index 0000000000..51b1e88d60 Binary files /dev/null and b/docs/resources/images/endpoint-state.png differ diff --git a/docs/resources/images/endpoint-turn-off.png b/docs/resources/images/endpoint-turn-off.png new file mode 100644 index 0000000000..cadf740568 Binary files /dev/null and b/docs/resources/images/endpoint-turn-off.png differ diff --git a/docs/resources/images/esb-architecture.png b/docs/resources/images/esb-architecture.png new file mode 100644 index 0000000000..79344f5fb0 Binary files /dev/null and b/docs/resources/images/esb-architecture.png differ diff --git a/docs/resources/images/esb-docs-bg.gif b/docs/resources/images/esb-docs-bg.gif new file mode 100644 index 0000000000..858ed6744a Binary files /dev/null and b/docs/resources/images/esb-docs-bg.gif differ diff --git a/docs/resources/images/esb-docs-header.gif b/docs/resources/images/esb-docs-header.gif new file mode 100644 index 0000000000..2ef5db6e7b Binary files /dev/null and b/docs/resources/images/esb-docs-header.gif differ diff --git a/docs/resources/images/help.gif b/docs/resources/images/help.gif new file mode 100644 index 0000000000..368068d09d Binary files /dev/null and b/docs/resources/images/help.gif differ diff --git a/docs/resources/images/installed-features.png b/docs/resources/images/installed-features.png new file mode 100644 index 0000000000..6e97fa2bd8 Binary files /dev/null and b/docs/resources/images/installed-features.png differ diff --git a/docs/resources/images/jconsole-mbean.png b/docs/resources/images/jconsole-mbean.png new file mode 100644 index 0000000000..1b4f0f87d2 Binary files /dev/null and b/docs/resources/images/jconsole-mbean.png differ diff --git a/docs/resources/images/log_mediator_conf.png b/docs/resources/images/log_mediator_conf.png new file mode 100644 index 0000000000..7be137b1a9 Binary files /dev/null and b/docs/resources/images/log_mediator_conf.png differ diff --git a/docs/resources/images/login.png b/docs/resources/images/login.png new file mode 100644 index 0000000000..ce9c384fd3 Binary files /dev/null and b/docs/resources/images/login.png differ diff --git a/docs/resources/images/logs.png b/docs/resources/images/logs.png new file mode 100644 index 0000000000..685554427c Binary files /dev/null and b/docs/resources/images/logs.png differ diff --git a/docs/resources/images/main_seq.png b/docs/resources/images/main_seq.png new file mode 100644 index 0000000000..6f1b35b9ae Binary files /dev/null and b/docs/resources/images/main_seq.png differ diff --git a/docs/resources/images/monitoring_jconsole_login.png b/docs/resources/images/monitoring_jconsole_login.png new file mode 100644 index 0000000000..ed49ae3605 Binary files /dev/null and b/docs/resources/images/monitoring_jconsole_login.png differ diff --git a/docs/resources/images/monitoring_jconsole_mbeans.png b/docs/resources/images/monitoring_jconsole_mbeans.png new file mode 100644 index 0000000000..a6c85483a2 Binary files /dev/null and b/docs/resources/images/monitoring_jconsole_mbeans.png differ diff --git a/docs/resources/images/monitoring_seq.png b/docs/resources/images/monitoring_seq.png new file mode 100644 index 0000000000..44d4acf9a7 Binary files /dev/null and b/docs/resources/images/monitoring_seq.png differ diff --git a/docs/resources/images/monitoring_view.png b/docs/resources/images/monitoring_view.png new file mode 100644 index 0000000000..f31fd8640c Binary files /dev/null and b/docs/resources/images/monitoring_view.png differ diff --git a/docs/resources/images/monitoring_view_ps.png b/docs/resources/images/monitoring_view_ps.png new file mode 100644 index 0000000000..6c7a6e1ef3 Binary files /dev/null and b/docs/resources/images/monitoring_view_ps.png differ diff --git a/docs/resources/images/monitoring_view_ps_single.png b/docs/resources/images/monitoring_view_ps_single.png new file mode 100644 index 0000000000..e89feb7149 Binary files /dev/null and b/docs/resources/images/monitoring_view_ps_single.png differ diff --git a/docs/resources/images/ns-add.png b/docs/resources/images/ns-add.png new file mode 100644 index 0000000000..142b4c2b20 Binary files /dev/null and b/docs/resources/images/ns-add.png differ diff --git a/docs/resources/images/nseditor-icon.gif b/docs/resources/images/nseditor-icon.gif new file mode 100644 index 0000000000..5b4ab69396 Binary files /dev/null and b/docs/resources/images/nseditor-icon.gif differ diff --git a/docs/resources/images/ot-header-esb-bg.gif b/docs/resources/images/ot-header-esb-bg.gif new file mode 100644 index 0000000000..a9fe470434 Binary files /dev/null and b/docs/resources/images/ot-header-esb-bg.gif differ diff --git a/docs/resources/images/perm-tree.png b/docs/resources/images/perm-tree.png new file mode 100644 index 0000000000..8920240871 Binary files /dev/null and b/docs/resources/images/perm-tree.png differ diff --git a/docs/resources/images/proxy-service.gif b/docs/resources/images/proxy-service.gif new file mode 100644 index 0000000000..ffdb8750b5 Binary files /dev/null and b/docs/resources/images/proxy-service.gif differ diff --git a/docs/resources/images/proxy.png b/docs/resources/images/proxy.png new file mode 100644 index 0000000000..ff0e5ae937 Binary files /dev/null and b/docs/resources/images/proxy.png differ diff --git a/docs/resources/images/proxy_service_step1.png b/docs/resources/images/proxy_service_step1.png new file mode 100644 index 0000000000..85b3aa9c43 Binary files /dev/null and b/docs/resources/images/proxy_service_step1.png differ diff --git a/docs/resources/images/proxy_templates.png b/docs/resources/images/proxy_templates.png new file mode 100644 index 0000000000..fa9cdfb848 Binary files /dev/null and b/docs/resources/images/proxy_templates.png differ diff --git a/docs/resources/images/qs_address.png b/docs/resources/images/qs_address.png new file mode 100644 index 0000000000..49d33f1dc4 Binary files /dev/null and b/docs/resources/images/qs_address.png differ diff --git a/docs/resources/images/qs_endpoint_main.png b/docs/resources/images/qs_endpoint_main.png new file mode 100644 index 0000000000..83325b11f8 Binary files /dev/null and b/docs/resources/images/qs_endpoint_main.png differ diff --git a/docs/resources/images/qs_out_sequence.png b/docs/resources/images/qs_out_sequence.png new file mode 100644 index 0000000000..7ca39ea7d7 Binary files /dev/null and b/docs/resources/images/qs_out_sequence.png differ diff --git a/docs/resources/images/qs_proxy_dashbord.png b/docs/resources/images/qs_proxy_dashbord.png new file mode 100644 index 0000000000..7719672c7c Binary files /dev/null and b/docs/resources/images/qs_proxy_dashbord.png differ diff --git a/docs/resources/images/qs_proxy_dashbord_in.png b/docs/resources/images/qs_proxy_dashbord_in.png new file mode 100644 index 0000000000..c93b153e6d Binary files /dev/null and b/docs/resources/images/qs_proxy_dashbord_in.png differ diff --git a/docs/resources/images/qs_proxy_service.png b/docs/resources/images/qs_proxy_service.png new file mode 100644 index 0000000000..06476e8c29 Binary files /dev/null and b/docs/resources/images/qs_proxy_service.png differ diff --git a/docs/resources/images/qs_proxy_service2.png b/docs/resources/images/qs_proxy_service2.png new file mode 100644 index 0000000000..ca4a8b700f Binary files /dev/null and b/docs/resources/images/qs_proxy_service2.png differ diff --git a/docs/resources/images/qs_proxy_wizard3.png b/docs/resources/images/qs_proxy_wizard3.png new file mode 100644 index 0000000000..e6cd9f351d Binary files /dev/null and b/docs/resources/images/qs_proxy_wizard3.png differ diff --git a/docs/resources/images/qs_ps_overall_stats.png b/docs/resources/images/qs_ps_overall_stats.png new file mode 100644 index 0000000000..8cc9f5eb03 Binary files /dev/null and b/docs/resources/images/qs_ps_overall_stats.png differ diff --git a/docs/resources/images/qs_ps_stats.png b/docs/resources/images/qs_ps_stats.png new file mode 100644 index 0000000000..1bd917fa1d Binary files /dev/null and b/docs/resources/images/qs_ps_stats.png differ diff --git a/docs/resources/images/registry-entry-types.png b/docs/resources/images/registry-entry-types.png new file mode 100644 index 0000000000..d5124c1617 Binary files /dev/null and b/docs/resources/images/registry-entry-types.png differ diff --git a/docs/resources/images/registry_picker.gif b/docs/resources/images/registry_picker.gif new file mode 100644 index 0000000000..de78940aa4 Binary files /dev/null and b/docs/resources/images/registry_picker.gif differ diff --git a/docs/resources/images/registrybrowser.png b/docs/resources/images/registrybrowser.png new file mode 100644 index 0000000000..46fbe4fd2e Binary files /dev/null and b/docs/resources/images/registrybrowser.png differ diff --git a/docs/resources/images/sequence_statistics.png b/docs/resources/images/sequence_statistics.png new file mode 100644 index 0000000000..f253c634c9 Binary files /dev/null and b/docs/resources/images/sequence_statistics.png differ diff --git a/docs/resources/images/sequences.png b/docs/resources/images/sequences.png new file mode 100644 index 0000000000..de3f901bfb Binary files /dev/null and b/docs/resources/images/sequences.png differ diff --git a/docs/resources/images/set-java-home.jpg b/docs/resources/images/set-java-home.jpg new file mode 100644 index 0000000000..d23d544990 Binary files /dev/null and b/docs/resources/images/set-java-home.jpg differ diff --git a/docs/resources/images/simple_address_endpoint.png b/docs/resources/images/simple_address_endpoint.png new file mode 100644 index 0000000000..0f57ec58db Binary files /dev/null and b/docs/resources/images/simple_address_endpoint.png differ diff --git a/docs/resources/images/stat-icon-disabled.gif b/docs/resources/images/stat-icon-disabled.gif new file mode 100644 index 0000000000..ec24847903 Binary files /dev/null and b/docs/resources/images/stat-icon-disabled.gif differ diff --git a/docs/resources/images/stat-icon.gif b/docs/resources/images/stat-icon.gif new file mode 100644 index 0000000000..3f7d61f79d Binary files /dev/null and b/docs/resources/images/stat-icon.gif differ diff --git a/docs/resources/images/statistics.png b/docs/resources/images/statistics.png new file mode 100644 index 0000000000..2836f266e2 Binary files /dev/null and b/docs/resources/images/statistics.png differ diff --git a/docs/resources/images/synapse-PBX.jpg b/docs/resources/images/synapse-PBX.jpg new file mode 100644 index 0000000000..53592541dd Binary files /dev/null and b/docs/resources/images/synapse-PBX.jpg differ diff --git a/docs/resources/images/synapse-flow.png b/docs/resources/images/synapse-flow.png new file mode 100644 index 0000000000..f5b6a0352f Binary files /dev/null and b/docs/resources/images/synapse-flow.png differ diff --git a/docs/resources/images/synapse-logo-web2.png b/docs/resources/images/synapse-logo-web2.png new file mode 100644 index 0000000000..0b4fc12f64 Binary files /dev/null and b/docs/resources/images/synapse-logo-web2.png differ diff --git a/docs/resources/images/table-header.gif b/docs/resources/images/table-header.gif new file mode 100644 index 0000000000..92283f0911 Binary files /dev/null and b/docs/resources/images/table-header.gif differ diff --git a/docs/resources/images/templates_call-template-parameters.png b/docs/resources/images/templates_call-template-parameters.png new file mode 100644 index 0000000000..add4bb3dfb Binary files /dev/null and b/docs/resources/images/templates_call-template-parameters.png differ diff --git a/docs/resources/images/templates_endpoint_templ_design.png b/docs/resources/images/templates_endpoint_templ_design.png new file mode 100644 index 0000000000..8036a73576 Binary files /dev/null and b/docs/resources/images/templates_endpoint_templ_design.png differ diff --git a/docs/resources/images/templates_sequence_params.png b/docs/resources/images/templates_sequence_params.png new file mode 100644 index 0000000000..f75e038dd0 Binary files /dev/null and b/docs/resources/images/templates_sequence_params.png differ diff --git a/docs/resources/images/templates_template_endpoint.png b/docs/resources/images/templates_template_endpoint.png new file mode 100644 index 0000000000..78a61ec564 Binary files /dev/null and b/docs/resources/images/templates_template_endpoint.png differ diff --git a/docs/resources/images/trace.png b/docs/resources/images/trace.png new file mode 100644 index 0000000000..7731046aa4 Binary files /dev/null and b/docs/resources/images/trace.png differ diff --git a/docs/resources/images/tracer-icon-disabled.gif b/docs/resources/images/tracer-icon-disabled.gif new file mode 100644 index 0000000000..ddcd94c2d9 Binary files /dev/null and b/docs/resources/images/tracer-icon-disabled.gif differ diff --git a/docs/resources/images/tracer-icon.gif b/docs/resources/images/tracer-icon.gif new file mode 100644 index 0000000000..02d399e648 Binary files /dev/null and b/docs/resources/images/tracer-icon.gif differ diff --git a/docs/resources/images/user-mgt.png b/docs/resources/images/user-mgt.png new file mode 100644 index 0000000000..813207dddb Binary files /dev/null and b/docs/resources/images/user-mgt.png differ diff --git a/docs/site.xml b/docs/site.xml new file mode 100644 index 0000000000..0d0fdfbf4f --- /dev/null +++ b/docs/site.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + org.apache.maven.skins + maven-default-skin + 1.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/xdoc/admin_guide.xml b/docs/xdoc/admin_guide.xml new file mode 100644 index 0000000000..e879cd06e7 --- /dev/null +++ b/docs/xdoc/admin_guide.xml @@ -0,0 +1,1032 @@ + + + + + + + WSO2 ESB - System Administration Guide + + + + + + + [ Documentation Index ] +

+ WSO2 Enterprise Service Bus [ESB] System Administration Guide +

+

+This is a manual on how to maintain and administrate a WSO2 ESB instance. It explains how various +features of the ESB can be configured using the ESB management console and by modifying the ESB +configuration files. Descriptions are provided on advanced features like Remote/Embedded +registry configuration, adding external libraries, managing key stores and user management. It +also explains how to performance tune the ESB runtime for extreme throughput. +

+

Contents

+

+

+

+ +

+ Introduction +

+

+WSO2 ESB is a production grade open source ESB solution based on the lightweight Apache Synapse ESB. +WSO2 ESB supports service mediation, message mediation, load balancing, clustering and many more +enterprise integration techniques out of the box. It also supports a range of application and transport +level protocols such as HTTP, JMS, Mail, VFS, FIX and a variety of industrial messaging standards such as +Hessian. +

+

+Starting from version 2.0, WSO2 ESB is based on the revolutionary WSO2 Carbon framework. WSO2 Carbon +is an OSGi based middleware framework for SOA. Currently all WSO2 Java products are based on WSO2 +Carbon including WSO2 Governance Registry and WSO2 AS. Since ESB is OSGi based some knowledge in +OSGi would be helpful in administrating the WSO2 ESB. +

+

+This document explains how to get WSO2 ESB and install it on a server. The latter sections of the +document illustrates how to setup and configure various features of the WSO2 ESB and how to performance +tune various aspects of the product. +

+ +

Document Conventions

+
    +
  • 'ESB_HOME' refers to the directory in the file system where WSO2 ESB is installed
  • +
  • 'ESB_SRC_HOME' refers to the directory in the file system where WSO2 ESB source distribution is installed
  • +
  • All file paths follow Unix/Linux conventions but they resemble Windows file paths as well
  • +
+ +

Getting WSO2 ESB

+

+Binary distributions and source distributions of WSO2 ESB can be downloaded free from the +WSO2 ESB home page in the WSO2 Oxygen Tank. Before proceeding to the +downloads page you will be asked to register on the WSO2 Oxygen Tank. Registration is free and optional +however it is recommended that you sign up for an account right away since registered Oxygen Tank users +get exclusive access to our support forums and tons of valuable content related to SOA and Web Services. +

+

+Once you are on the downloads page click on the relevant links to download a binary distribution or a +source distribution of the latest stable release of the WSO2 ESB. If you are interested in an older +version of the ESB, scroll down in the downloads page to locate the links to previous releases. You will +also find links to download developer releases and nightly builds of the WSO2 ESB on the same page. We +recommend that you always download the latest stable release. If you want to try out a feature that was +added very recently you can try out a nightly build. +

+

+If you downloaded a source distribution of the ESB you need to build the source to get the executable +binary. WSO2 ESB uses an Apache Maven2 based build system and +therefore you need to first download and install Apache Maven2. Please refer Maven2 documentation on +installing and configuring Apache Maven2. Also note that Apache Maven2 requires Java to run. +Once Maven2 is properly configured extract the downloaded source distribution and change your working +directory to the directory that is created. Then execute the command 'mvn clean install' to run the builder. +Once the build process is complete you can find the binary distribution archive in ESB_SRC_HOME/modules/distribution/target +directory. +

+ +

Installing and Running WSO2 ESB

+

+To install the WSO2 ESB simply extract the downloaded binary distribution archive. If you built WSO2 ESB +from source extract the archive created by the builder. We recommend installing WSO2 ESB on a Unix/Linux +system since that will enable you to get the maximum out of the ESB. In order to be able to start WSO2 ESB +you first need Java 5 or higher. Having installed Java on your system please set the JAVA_HOME environment +variable to point to the directory in which Java is installed. +

+

Running WSO2 ESB in Standalone Mode

+

+Now you are all set to start WSO2 ESB in the standalone mode. Go to ESB_HOME/bin directory and if you are +on Unix/Linux execute the wso2server.sh shell script or if you are on Windows execute the wso2server.bat +batch file. This will start the ESB and you can see the progress of the startup procedure on the console. +Please note that server startup may take some time depending on the hardware configuration of your system. +The very first startup of the ESB can take up a few additional seconds since some first time configuration +procedure is run by the ESB. If the server started up cleanly you should get an output similar to the following +on the console. +

+
+  [2010-03-23 10:34:17,594]  INFO - Main Initializing system...
+  [2010-03-23 10:34:25,176]  INFO - CarbonCoreActivator Starting WSO2 Carbon...
+  [2010-03-23 10:34:25,178]  INFO - CarbonCoreActivator Operating System : Linux 2.6.28-16-generic, amd64
+  [2010-03-23 10:34:25,178]  INFO - CarbonCoreActivator Java Home        : /opt/jdk1.6.0_16/jre
+  [2010-03-23 10:34:25,178]  INFO - CarbonCoreActivator Java Version     : 1.6.0_16
+  [2010-03-23 10:34:25,178]  INFO - CarbonCoreActivator Java VM          : Java HotSpot(TM) 64-Bit Server VM 14.2-b01,Sun Microsystems Inc.
+  [2010-03-23 10:34:25,178]  INFO - CarbonCoreActivator Carbon Home      : /home/user/wso2esb-3.0.1
+  [2010-03-23 10:34:25,179]  INFO - CarbonCoreActivator Java Temp Dir    : /home/user/wso2esb-3.0.1/tmp
+  [2010-03-23 10:34:25,179]  INFO - CarbonCoreActivator User             : user, en-US, Asia/Colombo
+  [2010-03-23 10:34:29,715]  INFO - RegistryCoreServiceComponent Registry Mode    : READ-WRITE
+  [2010-03-23 10:34:32,349]  INFO - CarbonServerManager Starting Carbon initialization...
+  [2010-03-23 10:34:32,561]  INFO - ClusterBuilder Clustering has been disabled
+  [2010-03-23 10:34:32,742]  INFO - DeploymentInterceptor Deploying Axis2 module : relay-3.0
+  [2010-03-23 10:34:32,799]  INFO - DeploymentInterceptor Deploying Axis2 module : wso2mex-3.0
+  [2010-03-23 10:34:32,818]  INFO - DeploymentInterceptor Deploying Axis2 module : rampart-SNAPSHOT
+  [2010-03-23 10:34:32,862]  INFO - DeploymentInterceptor Deploying Axis2 module : sandesha2-3.0
+  [2010-03-23 10:34:32,916]  INFO - DeploymentInterceptor Deploying Axis2 module : wso2caching-3.0
+  [2010-03-23 10:34:32,989]  INFO - DeploymentInterceptor Deploying Axis2 module : wso2xfer-3.0
+  [2010-03-23 10:34:33,001]  INFO - DeploymentInterceptor Deploying Axis2 module : rahas-SNAPSHOT
+  [2010-03-23 10:34:33,019]  INFO - DeploymentInterceptor Deploying Axis2 module : savan-SNAPSHOT
+  [2010-03-23 10:34:33,034]  INFO - DeploymentInterceptor Deploying Axis2 module : wso2throttle-3.0
+  [2010-03-23 10:34:33,125]  INFO - DeploymentInterceptor Deploying Axis2 module : addressing-1.6-wso2v1
+  [2010-03-23 10:34:33,202]  INFO - HttpCoreNIOSSLSender Loading Identity Keystore from : resources/security/wso2carbon.jks
+  [2010-03-23 10:34:33,228]  INFO - HttpCoreNIOSSLSender Loading Trust Keystore from : resources/security/client-truststore.jks
+  [2010-03-23 10:34:33,256]  INFO - HttpCoreNIOSender HTTPS Sender starting
+  [2010-03-23 10:34:33,269]  INFO - HttpCoreNIOSender HTTP Sender starting
+  [2010-03-23 10:34:33,370]  INFO - DeploymentInterceptor Deploying Axis2 service : echo
+  [2010-03-23 10:34:33,899]  INFO - DeploymentInterceptor Deploying Axis2 service : version
+  [2010-03-23 10:34:37,698]  INFO - DeploymentInterceptor Deploying Axis2 service : wso2carbon-sts
+  [2010-03-23 10:34:38,273]  INFO - DeploymentInterceptor Deploying Axis2 service : XKMS
+  [2010-03-23 10:34:38,480]  INFO - CarbonServerManager Repository       : /home/user/wso2esb-3.0.1/repository/deployment/server/
+  [2010-03-23 10:34:38,506]  INFO - EmbeddedRegistryBasedSubscriptionManager Connection established with the registry
+  [2010-03-23 10:34:38,530]  INFO - ServiceBusInitializer Starting ESB...
+  [2010-03-23 10:34:38,573]  INFO - ServiceBusInitializer Initializing Apache Synapse...
+  [2010-03-23 10:34:38,580]  INFO - SynapseControllerFactory Using Synapse home : /home/user/wso2esb-3.0.1/.
+  [2010-03-23 10:34:38,580]  INFO - SynapseControllerFactory Using synapse.xml location : /home/user/wso2esb-3.0.1/./repository/conf/synapse-config
+  [2010-03-23 10:34:38,580]  INFO - SynapseControllerFactory Using server name : localhost
+  [2010-03-23 10:34:38,584]  INFO - SynapseControllerFactory The timeout handler will run every : 15s
+  [2010-03-23 10:34:38,634]  INFO - Axis2SynapseController Initializing Synapse at : Tue Mar 23 10:34:38 IST 2010
+  [2010-03-23 10:34:38,636]  INFO - Axis2SynapseController Loading mediator extensions...
+  [2010-03-23 10:34:38,642]  INFO - CarbonSynapseController Loading the mediation configuration from the file system
+  [2010-03-23 10:34:38,645]  INFO - MultiXMLConfigurationBuilder Building synapse configuration from the synapse artifact repository at : ./repository/conf/synapse-config
+  [2010-03-23 10:34:38,646]  INFO - XMLConfigurationBuilder Generating the Synapse configuration model by parsing the XML configuration
+  [2010-03-23 10:34:39,077]  INFO - SynapseConfigurationBuilder Loaded Synapse configuration from the artifact repository at : ./repository/conf/synapse-config
+  [2010-03-23 10:34:39,208]  INFO - Axis2SynapseController Deploying the Synapse service...
+  [2010-03-23 10:34:39,212]  INFO - Axis2SynapseController Deploying Proxy services...
+  [2010-03-23 10:34:39,212]  INFO - Axis2SynapseController Deploying EventSources...
+  [2010-03-23 10:34:39,217]  INFO - ServerManager Server ready for processing...
+  [2010-03-23 10:34:40,219]  INFO - HttpCoreNIOSSLListener Loading Identity Keystore from : resources/security/wso2carbon.jks
+  [2010-03-23 10:34:40,221]  INFO - HttpCoreNIOSSLListener Loading Trust Keystore from : resources/security/client-truststore.jks
+  [2010-03-23 10:34:40,237]  INFO - HttpCoreNIOListener HTTPS Listener started on port : 8243
+  [2010-03-23 10:34:40,239]  INFO - HttpCoreNIOListener HTTP Listener started on port : 8280
+  [2010-03-23 10:34:40,798]  INFO - RegistryEventingServiceComponent Successfully Initialized Eventing on Registry
+  [2010-03-23 10:34:43,926]  INFO - CarbonUIServiceComponent Mgt Console URL  : https://10.100.1.209:9443/carbon/
+  [2010-03-23 10:34:43,940]  INFO - StartupFinalizerServiceComponent Started Transport Listener Manager
+  [2010-03-23 10:34:43,940]  INFO - StartupFinalizerServiceComponent Server           :  WSO2 ESB-3.0.1
+  [2010-03-23 10:34:43,940]  INFO - StartupFinalizerServiceComponent WSO2 Carbon started in 25 sec
+
+

+To verify that the ESB is up and running fire off your Web browser and go to https://localhost:9443/carbon. +This will take you to the WSO2 ESB on-line management console. +

+ +

+You can login to the console using the default user credentials given below. +

+
    +
  • Username: admin
  • +
  • Password: admin
  • +
+

+If you can get that far then the ESB is properly installed and running. +

+

+WSO2 ESB startup scripts stated above accept a few useful arguments. +

+

+--cleanRegistry
+This argument will remove the settings stored in the registry and replace them with factory settings. +It removes the /_system/config/repository collection and the /_system/local/repository collection in the +registry which are used to store resources and configurations managed by the ESB and the underlying +Carbon framework. Therefore the ESB will be forced to start fresh with factory settings. Starting from +WSO2 ESB 3.0 the mediation configuration (sequences, proxies etc) is read from the file system by default. +In that case this argument does not have any effect on the mediation configuration used by the ESB. +

+

+--debug <port>
+Enables remote debugging on the ESB through the specified port. +

+

+In addition to the above mentioned arguments the ESB startup scripts accept the following VM arguments. +

+

+-DosgiConsole
+Starts the OSGi console from which you can directly interact with the underlying OSGi framework. +

+

+-DloadFromRegistry
+This argument was first introduced in ESB 3.0. When set to 'true' it will force the ESB to load the mediation +configuration from the registry, instead of loading it from the file system. Please note that for this +argument to work the registry must contain a valid mediation configuration stored in it. Therefore one +cannot pass this argument to a fresh ESB instance which is starting from a clean registry. However after the +first startup the registry will contain a mediation configuration and hence subsequent startups can proceed +with this VM parameter. +

+

+-DwriteToFile
+Newly added to WSO2 ESB 3.0, this argument takes effect only when the mediation configuration is loaded +from the registry. When set to 'true' this parameter will force the ESB to save the configuration loaded +from the registry to the local file system at startup. +

+ +

Running ESB Samples

+

+WSO2 ESB ships with a large number of sample configurations which enables you to get familiar with the +product quickly and easily. Please refer the WSO2 ESB samples guide for sample configuration and details +on how to run them. You may start WSO2 ESB using those sample configuration by executing the +ESB_HOME/bin/wso2esb-sample.sh (for Unix/Linux) or ESB_HOME/bin/wso2esb-sample.bat (for Windows). +These launcher scripts take a mandatory argument -sn. Use this argument to specify the sample number. +

+

+eg: ./wso2esb-sample.sh -sn 250 (This will launch the ESB using the Sample 250 configuration) +

+

+The sample configuration files can be found in the ESB_HOME/repository/samples directory. +

+

+When launching the ESB using the wso2esb-sample.sh/wso2esb-sample.bat scripts a new registry context root +will be created for storing data and configurations related to that sample. Also note that these launcher +scripts accept the same set of arguments accepted by the wso2server.sh and wso2server.bat. +

+ +

WSO2 ESB Directory Hierarchy

+

+When you extract a WSO2 ESB binary distribution archive you will find the following directories in the +top level directory that is created. +

+ +

+bin -
+ Contains all the necessary scripts to interact with the WSO2 ESB instance. There are shell scripts + (with .sh extension) for Unix/Linux users and batch files (with .bat extension) for Windows users. + In general you will find the following scripts in this directory.
+
+

    +
  • + wso2server.sh/wso2server.bat - Launches WSO2 ESB +
  • +
  • + wso2esb-samples.sh/wso2esb-samples.bat - Launches WSO2 ESB using one of the sample configurations +
  • +
  • + wsdl2java.sh/wsdl2java.bat - Launches the Java stub generation tool for Web Services +
  • +
  • + java2wsdl.sh/java2wsdl.bat - Launches the WSDL generation tool for Java Web Services +
  • +
  • + tcpmon.sh/tcpmon.bat - Launches TCPMon, the TCP connection monitor +
  • +
  • + chpasswd.sh/chpasswd.bat -Use this script to change the administrator password without signing in to the server
    +
  • +
  • + ciphertool.sh/ciphertool.bat -<TODO: Indika>
    +
  • +
  • + daemon.sh -Start WSO2 ESB as a daemon on Unix/Linux systems
    +
  • +
  • + install.bat - Install WSO2 ESB as a background service on Windows
    +
  • +
  • + repowriter.sh/repowriter.bat +
  • +
  • + carbondump.sh/carbondump.bat - Create a dump file containing runtime information related to the ESB (Dump file is useful in debugging issues) +
  • +
+
+ In addition to the above mentioned scripts you will find a subdirectory named 'native' in the bin + directory.
+

+

+dbscripts -
+Contains a collection of database scripts required to create the Carbon database on a variety of database +management systems.
+

+

+lib -
+The lib directory houses all the jar files and OSGi bundles required by the embedded Tomcat instance. +The log4j.properties file used by the ESB is also stored here. In addition to that, the Carbon webapp +can be found in the lib/core directory. The lib/core/WEB-INF/classes directory houses some of +important configuration files of the ESB such as nhttp.properties, synapse.properties and datasources.properties. +

+

+repository -
+This directory houses all the OSGi bundles, service artifacts, modules, configurations and related resources +used by the WSO2 ESB instance. The repository/components/plugin directory will contain all the necessary OSGi bundles +at server runtime. In the components subdirectory you can also find a set of child directories such as lib, +mediators and extensions which can be used to deploy custom mediators and third party dependencies into the ESB. +The repository/conf subdirectory contains all the crucial configuration files such as axis2.xml and carbon.xml. The +mediation configuration is loaded from the repository/deployment/server/synapse-config directory. Also starting from ESB 3.0 +server logs are stored in the repository/logs directory. +

+

+resources -
+Contains additional resources required by WSO2 ESB. This includes security related resources such as +keystores. +

+

+samples -
+The samples directory contains the sample Axis2 server, sample Axis2 client, source code of the sample +services and clients and the ANT scripts required to build and run them. +

+

+tmp -
+The temporary files directory used by the ESB +

+ +

Using the WSO2 ESB Management Console

+

+WSO2 ESB management console is a Web based control panel powered by JSP and AJAX which enables system administrators +to interact with a running ESB instance, without having to touch any underlying configuration files. The +management console allows the users to command and control proxy services, sequences, transports, local +entries, registry, modules, endpoints and much more. ESB management console is a great way to try things +out without having to edit the actual configuration files or without having to restart the ESB for +changes to take effect. +

+

+We recommend using Mozilla Firefox 3 or Internet Explorer 7 to access the WSO2 ESB management console. +Please note that your browser must be JavaScript enabled to take the full advantage of the management console. +To access the ESB management console fire off you Web browser and navigate to +https://<Server Host>:<Server Port>/<Context>. If you are running the Web browser on +the same machine as the ESB you may use 'localhost' as the server host. The default port and the context +for the ESB management console are '9443' and 'carbon' respectively. If you entered the URL correctly you +will be taken to the management console's login page. +

+

+On the login page enter 'admin' as the username and the password to login to the system. You can change +user credentials and even add new users once you login. Controls and wizards in the ESB management console +are pretty much self explanatory. However if you are having trouble finding your way in the management +console, click on the 'Help' link at the top right corner of any page to access context sensitive help. +

+

+Please note that the ESB management console makes use of the default HTTPS servlet transport which is +configured in the ESB_HOME/repository/conf/mgt-transports.xml file. It is important that this transport +is always properly configured in the mentioned file. Otherwise the management console might be inaccessible +to the users. +

+ +

User Management

+

+To access the WSO2 ESB user management features, first sign in to the ESB management console and click on +'User and Roles' under the 'Configure' menu in the left navigation bar. This will take you to the User +Management home page which contains the controls illustrated below. +

+ +

+From here you can manage users and roles. A user is associated with one or more roles (generally specified at +user creation time) and each role is associated with zero or more permissions (generally specified at +role creation time). Therefore the set of permissions owned by a user is determined by the roles assigned to +that user. A user owns the union of all the permissions associated with the roles assigned to that user. By +default ESB comes with only two roles, the 'admin' role and the 'everyone' role. There is also a third role +named 'system' which is not visible in the management console. Every user will be assigned the +'everyone' role. This role does not have any permissions by default. Users with the 'admin' role have full +access to all the features and controls in the ESB (all permissions). By default the user 'admin' is assigned the +'admin' role along with the 'everyone' role. Also note that the ESB UI does not allow configuing the permissions +assigned to the 'admin' role. +

+

+The permission model of WSO2 ESB is hierarchical. Therefore permissions +can be assigned in a fine grained manner or a coarse grained manner. For an example one could assign the 'Configure' +admin permission to a role. The role will be able to configure event sources, scheduled tasks and many other things. +This is a coarse grained permission allocation. On the other hand one may assign the specific +'Transport Management', 'Configure Tasks' or 'Configure Data Sources' permission to a role which is a fine grained +permission allocation. The full ESB permission tree looks as follows. +

+ +

+Use the 'User Management' page in the UI to add new users, add new roles, assign and withdraw permissions from +roles and change login credentials of users. To add a new role to the system click on 'Roles' in the User +Management home page and on the page that appears click the 'Add New Role' link. This will start the 'Add +Role' wizard. The wizard will guide you though the process of creating a role by specifying a unique name +for the role and adding the relevant permissions to the new role. Similarly to create a new user, click on +'Users' in the User Management home page. Then from the next page that appears select 'Create New User' link. +This will launch the 'Add User' wizard which will enable you to create a new user account with login credentials +and associate the account with one or more existing roles. The ESB management console also enables you to +search for and modify existing users and roles. +

+

Using External User Stores (LDAP/AD)

+

+You can also connect an external user store (database) with WSO2 ESB. Such external stores are configured through +the user-mgt.xml file which can be found in the repository/conf directory. Settings required to connect an LDAP +based user store or an Active Directory based user store are provided in the default user-mgt.xml file. Simply +uncomment the relevant entries in the file and update the required parameters. Also note that the ESB can have +only one user store at any given moment. Hence when you want to connect to a different user store you also need +to comment out the default user store settings (LDAP user store manager) in the user-mgt.xml file. Configuration +settings for the LDAP based user store looks as follows. +

+
+<UserStoreManager class="org.wso2.carbon.user.core.ldap.ApacheDSUserStoreManager">
+    <Property name="ReadOnly">false</Property>
+    <Property name="ConnectionURL">ldap://localhost:${Ports.EmbeddedLDAP.LDAPServerPort}</Property>
+    <Property name="ConnectionName">uid=admin,ou=system</Property>
+    <Property name="ConnectionPassword">admin</Property>
+    <Property name="passwordHashMethod">SHA</Property>
+    <Property name="UserNameListFilter">(objectClass=person)</Property>
+    <Property name="UserEntryObjectClass">wso2Person</Property>
+    <Property name="UserSearchBase">ou=Users,dc=wso2,dc=org</Property>
+    <Property name="UserNameSearchFilter">(&(objectClass=person)(uid=?))</Property>
+    <Property name="UserNameAttribute">uid</Property>
+    <Property name="PasswordJavaScriptRegEx">[\\S]{5,30}</Property>
+    <Property name="UsernameJavaScriptRegEx">[\\S]{3,30}</Property>
+    <Property name="UsernameJavaRegEx">^[^~!@#$;%^*+={}\\|\\\\<>]{3,30}$</Property>
+    <Property name="RolenameJavaScriptRegEx">[\\S]{3,30}</Property>
+    <Property name="RolenameJavaRegEx">^[^~!@#$;%^*+={}\\|\\\\<>]{3,30}$</Property>
+    <Property name="ReadLDAPGroups">true</Property>
+    <Property name="WriteLDAPGroups">true</Property>
+    <Property name="EmptyRolesAllowed">true</Property>
+    <Property name="GroupSearchBase">ou=Groups,dc=wso2,dc=org</Property>
+    <Property name="GroupNameListFilter">(objectClass=groupOfNames)</Property>
+    <Property name="GroupEntryObjectClass">groupOfNames</Property>
+    <Property name="GroupNameSearchFilter">(&(objectClass=groupOfNames)(cn=?))</Property>
+    <Property name="GroupNameAttribute">cn</Property>
+    <Property name="MembershipAttribute">member</Property>
+</UserStoreManager>
+
+

+For more information on using external user stores please refer User Core Admin +Guide. +

+ +

Setting Up Logging

+

+Logging is one of the most important aspects of a production grade server. A properly configured logging system +is vital in identifying errors, security threats and usage patterns. WSO2 ESB uses a log4j based logging mechanism +through Apache Commons Logging facade library. The log4j.properties file which governs how logging is performed by +the server can be found in ESB_HOME/lib directory. However it is recommended not to make any alterations to the +default log4j.properties file. The recommended way of setting up logging is by using the ESB management console. +Simply login to the management console and click on 'Logging' under the 'Configure' menu in the left navigation bar. +From here you can setup various appenders and configure log levels for various loggers. Any changes to the logging +configuration you make from the management console will get priority over what is defined in the actual +log4j.properties file. +

+

+By default WSO2 ESB comes with the following log appenders configured. +

+
    +
  • + CARBON_CONSOLE (Logs to the console when the server is running) +
  • +
  • + CARBON_LOGFILE (Writes the logs to ESB_HOME/repository/logs/wso2-esb.log) +
  • +
  • + CARBON_MEMORY +
  • +
  • + CARBON_SYS_LOG +
  • +
  • + SERVICE_APPENDER (Writes mediation time audit messages to ESB_HOME/repository/logs/wso2-esb-service.log) +
  • +
  • + TRACE_APPENDER (Writes mediation time tracing/debug messages to the ESB_HOME/repository/logs/wso2-esb-trace.log for tracing enabled services) +
  • +
  • + TRACE_MEMORYAPPENDER +
  • +
+

+Tracing can be enabled for individual mediation sequences and proxy services from the 'Mediation Sequences' +home page and the 'Service Dashboard' page respectively. Click on the 'Sequences' link under 'Mediation' in +the 'Manage' menu of the left navigation bar to access the 'Mediation Sequences' page. This page lists all +the deployed sequences. Each sequence gives you the options to enable/disable tracing. To access the service +dashboard for a proxy service go to the Services List page and click on the proxy service that you are +interested in. Once a sequence or a proxy service is tracing enabled you can view the generated log messages +by visiting the 'Mediation Tracer' page under the 'Monitor' menu. The 'Monitor' menu also gives you access +to the system logs and the SOAP tracer logs all through the Web interface itself. +

+ + +

Configuring the Underlying Axis2 Engine

+

+WSO2 ESB is based on Apache Synapse lightweight ESB which in turns uses the Apache Axis2 SOAP engine. Every +WSO2 ESB administrator is expected to have at least a basic understanding of Axis2 and Axis2 configuration model. +The global configuration of the Axis2 engine is specified in a file named axis2.xml. This configuration file can +be found in the ESB_HOME/repository/conf directory. Any settings configured in the axis2.xml file are directly +applied to the server at startup time. Generally, one can configure the following settings in the axis2.xml file. +

+
    +
  • + Global system parameters (eg: hotdeployment, hotupdate, servicepath etc) +
  • +
  • + Global Axis2 listeners (Axis2 observer implementations which are notified of Axis2 events) +
  • +
  • + Deployers +
  • +
  • + Message receivers, formatters and builders +
  • +
  • + Transport receivers and senders +
  • +
  • + Globally engaged modules (eg: addressing) +
  • +
  • + Clustering +
  • +
  • + Axis2 phases +
  • +
+

+The axis2.xml file which comes with WSO2 ESB contains examples and descriptions illustrating how the above +can be configured and setup for common deployment scenarios. +

+ +

Mediation Configuration

+

+Mediation configuration is the most important part of the WSO2 ESB as far as the functionality of the service +bus is concerned. The mediation configuration consists of following items. +

+
    +
  • Endpoints
  • +
  • Sequences
  • +
  • Proxy services
  • +
  • Scheduled tasks
  • +
  • Event sources
  • +
  • Local entries
  • +
  • Priority executors (new in ESB 3.0)
  • +
+

+Each of the above items can be configured through the management console. New instances of above items +can be added to the ESB, existing items can be modified or removed. The 'Synapse' entry in the 'Configure' +menu provides a single unified view of the entire mediation configuration and allows the user to make +modifications to it using the Synapse configuration language. +

+ +

Persistence

+

+By default the mediation configuration is stored in the file system as well as in the registry. In the file +system, configuration is saved under the ESB_HOME/repository/conf/synapse-config directory. There are separate +subdirectories to store different types of configuration items. When you add a new item using the management +console it will be saved to a new file under the synapse-config directory. For an example, if you add a new +endpoint named 'foo' from the UI, it will be saved to a file named foo.xml in ESB_HOME/repository/conf/synapse-config/endpoints +directory. Any further modifications to the endpoint foo will be saved back to the same file. However if you +add a new item from the Synapse configuration editor in the UI (in Configure menu) it will be saved to +ESB_HOME/repository/conf/synapse-config/synapse.xml file. +

+

+You can customize the behavior of mediation configuration persistence by editing the carbon.xml file. You may +add the following entry to the carbon.xml and tune up the parameter values as appropriate. +

+
+<MediationConfig>
+    <LoadFromRegistry>false</LoadFromRegistry>
+    <SaveToFile>false</SaveToFile>
+    <Persistence>enabled</Persistence>
+    <RegistryPersistence>enabled</RegistryPersistence>
+</MediationConfig>
+
+

+Set the LoadFromRegistry to 'true' if you want to load the mediation configuration from the registry instead of the file +system. SaveToFile option takes effect only when LoadFromRegistry is set to 'true'. If both values are set to 'true' +the mediation configuration will be loaded from the registry and will also be saved to the local file system at +startup. If you want to prevent the ESB from saving the mediation configuration to the registry set RegistryPersistence +to 'disabled'. By default this is enabled. You can turn off all persistence activies by setting Persistence to +'disabled'. In that case mediation configuration will not be saved to the file system nor the registry. The configuration +in the disk/registry is effectively frozen. But the changes made from the UI will still take effect in the runtime. But +such changes will not survive a restart since they are not saved to persistence store. +

+ +

Dependency Tracking

+

+WSO2 ESB keeps track of the dependencies among various mediation configuration elements. In a typical mediation +configuration there are often dependencies among sequences, endpoints, proxy services and local entires. A +sequence can make references to other sequences, local entries and endpoints. A proxy service may also make references to +sequences and endpoints. The ESB runtime by default keeps track of such dependencies and warns the user, if he +attempts to remove a particular item from the configuration which is a dependency for another item. +

+ +

+The dependency tacking process takes up a few CPU cycles and memory to compute and keep track of the +dependencies at runtime. Therefore it is recommended to turn this feature off in production environments. +To turn off dependency tracking open up the synapse.properties file which can be found in the +ESB_HOME/webapps/ROOT/WEB-INF/classes directory and comment out the following line: +

+
synapse.observers=org.wso2.carbon.mediation.dependency.mgt.DependencyTracker
+

+You also need to restart the ESB for the change to take effect. Commenting out the above entry will disengage +the dependency tracker and hence the ESB will stop computing and keeping track of dependencies among +different configuration items in the mediation configuration. +

+ +

Hot Deployment of Mediation Artifacts

+

+WSO2 ESB 3.0 introduces the hot deployment feature for mediation artifacts. With this feature you can hot +deploy artifacts like endpoints, sequences and proxy services into the ESB_HOME/repository/conf/synapse-config +directory. Simply save the artifact configuration to an XML file and drop it into the relevant subdirectory in +the synapse-config parent directory. ESB will pick up the newly added file and get it deployed in the server +runtime. Once deployed you will be able to view it through the management console and make further changes if +necessary. Similarly you can make changes to an existing file which contains a mediation configuration item +and the ESB will pick the changes up through the hot update feature. +

+

+In a production system it is recommended to turn off hot deployment and update for smooth operation of the ESB. +To turn off hot deployment and hot update open up the axis2.xml file in repository/conf directory and set the +following two parameter values to 'false'. (These are by default set to 'true') +

+
+    <parameter name="hotdeployment" locked="false">false</parameter>
+
+    <parameter name="hotupdate" locked="false">false</parameter>
+
+ +

Installing and Managing Features

+

+New features can be easily installed into the ESB by using the 'WSO2 Carbon Component Manager' that comes +with the ESB. Component manager is powered by Equinox P2 and allows you to connect to a remote or local P2 +repository and get any feature installed into the ESB runtime. You can also uninstall existing features of +the ESB and come up with a customized version of WSO2 ESB tailored to meet your requirements. +

+

+To use the component manager, login to the management console and click on 'Features' under the +'Configure' menu. Go to the 'Settings' tab and click on 'Manage Repositories'. Click 'Add New Repository' +and specify the P2 repository to which you wish to connect to. The official WSO2 P2 repository is available +over http://dist.wso2.org/p2. +

+

+Once the repository is configured go to the 'Available Features' tab to browse through the features and get them +installed to the ESB. The installation of a feature can take a while depending on the network bandwidth and +hardware configuration available. Once a feature has been successfully installed you will be prompted to logout +and restart the ESB. +

+

+If you wish to uninstall an existing feature go to the 'Installed Features' tab, select the features to be +uninstalled and click on 'Uninstall' at the bottom of the page. +

+ + +

Adding External Dependencies to the System

+

+You would want to deploy external dependency jars into the WSO2 ESB server in many scenarios. Generally one +would want to add external dependencies in following situations. +

+
    +
  • + Enabling and configuring a new transport (Many transport implementations such as JMS and FIX require + adding a set of external dependencies to the server) +
  • +
  • + Adding a custom mediator +
  • +
  • + Adding a custom handler or a module +
  • +
+

+To add an external dependency to the WSO2 ESB you simply need to copy the necessary jar file(s) to +ESB_HOME/repository/components/lib or ESB_HOME/repository/components/extensions. Jars copied to these +directories will be automatically converted into OSGi bundles on ESB startup. Jars copied to +ESB_HOME/repository/components/extensions will be converted into OSGi bundles which are fragments of the +main system bundle. WSO2 ESB also provides the ESB_HOME/repository/components/mediators directory to deploy +custom mediators into the ESB. +

+

+Currently WSO2 ESB does not support deploying external dependencies at runtime. Therefore after copying +the external dependency jars to the relevant locations the server must be restarted for the server to be +able to pick them up. +

+ +

Registry Integration

+

+WSO2 ESB makes use of a WSO2 Governance Registry instance to store various configurations and artifacts +such as proxy services, sequences and endpoints. Simply put a registry is a content store and a metadata +repository. Various SOA artifacts such as services, WSDLs and configuration files can be stored in a +registry keyed by unique paths. A path is similar to a Unix file path. In WSO2 ESB all configurations +pertaining to modules, logging, security, data sources and other service groups are stored in the registry +by default. Starting from WSO2 Carbon 2.0 all the transport configurations are also stored in the registry. +WSO2 ESB 2.1 introduced a feature to directly store endpoints and sequences to the registry with a user +specified key value. +

+

+WSO2 ESB accesses the registry in two ways. In many cases it accesses the registry by directly calling the +registry API from Carbon components. In some special situations it gains access to the registry through the +underlying Apache Synapse configuration. It is important that Synapse configuration should always include a +registry definition. That is, the ESB configuration should include the following registry definition. +

+ +
+<registry provider="org.wso2.carbon.mediation.registry.WSO2Registry">
+	<parameter name="cachableDuration">15000</parameter>
+</registry>
+
+ +

+Starting from ESB 3.0 the registry that comes with WSO2 ESB is actually a combination of 3 registries. +

+
    +
  • Local repository (Used to store settings/metadata specific to the ESB node - This registry cannot be shared)
  • +
  • Configuration registry (Used to store settings/metadata that is shared across a cluster of ESB instances)
  • +
  • Governance registry (Used to store user specified metadata and resources and can be shared across an organization)
  • +
+

+The above registry instances are mounted to a single top level registry to provide a single unified view. Mount points of +the three registries are /_system/local, /_system/config and /_system/governance respectively. One could browse +the contents of the registry used by the ESB from the WSO2 ESB management console. To browse the registry, first +login to the ESB management console and click on 'Registry Browser' link under the 'Registry' menu. +

+ + +

Using the Embedded Registry

+

+WSO2 ESB comes with an embedded WSO2 Governance Registry (WSO2 G-Reg) which is used by the ESB to store configurations +and other deployment artifacts. The embedded registry instance makes use of the embedded ESB database. This is an H2 +database and the data files are by default stored in the directory named ESB_HOME/repository/database. If you are running +the ESB in the embedded registry mode you should be careful not to manually alter any files stored in this directory as +that might lead to database corruption or data loss. +

+

+The embedded registry instance is configured by the registry.xml file which can be found in the ESB_HOME/repository/conf directory. +In this configuration you could point the embedded registry to a database other than the default embedded H2 database. +To change the database used by the registry or change the location of the database files edit the following section of the +registry.xml. +

+
+<dbconfig name="wso2registry">
+	<url>jdbc:h2:database/WSO2CARBON_DB</url>
+	<userName>wso2carbon</userName>
+	<password>wso2carbon</password>
+	<driverName>org.h2.Driver</driverName>
+	<maxActive>50</maxActive>
+	<maxWait>60000</maxWait>
+	<minIdle>5</minIdle>
+</dbconfig>
+
+

+WSO2 Governance Registry can be run in two operational modes, namely the ReadWrite mode and the ReadOnly mode. By default +it operates in the ReadWrite mode. This mode is set by the following element in the registry.xml file. +

+
+<readOnly>false</readOnly>    
+
+

+When the registry ReadOnly mode is set to true the ESB will not be able to store resources or write values +to the registry. It will be capable of reading the existing resources only. If you want to make sure that +the ESB or any of the ESB administrators do not alter the resources already stored in the registry this +value should be set to true. Also in a clustered deployment it is recommended that only one ESB instance +accesses the registry in the ReadWrite mode. All other ESB nodes should be accessing the registry in the +ReadOnly mode to prevent different ESB servers from modifying the same resources at the same time. Any +configuration updates should be done via the ESB instancce in ReadWrite mode. +

+

+In addition to configuring the database instance you can configure media type handlers for various media types +and setup various registry related system parameters by modifying the registry.xml file. The default +configuration defines the following parameters. +

+
+<staticConfiguration>
+	<versioningProperties>true</versioningProperties>
+	<versioningComments>true</versioningComments>
+	<versioningTags>true</versioningTags>
+	<versioningRatings>true</versioningRatings>
+</staticConfiguration>    
+
+

+Please refer WSO2 G-Reg documentation for further information on setting up media type handlers and other +global parameters. +

+ +

Using the Remote Registry

+

+You can configure the ESB to use a remotely hosted WSO2 Governance Registry instance as the metadata and +configuration store, instead of using the embedded registry instance. For that you need to edit the +ESB_HOME/repository/conf/registry.xml file and modify the database configuration to point to the same +database as the remote registry instance. Edit the dbconfig element in the registry.xml and make sure that +the ESB is pointed to the same database as your WSO2 Governance Registry instance. +

+ +

Setting Up Keystores

+

+WSO2 ESB uses several keystores to power the HTTPS transport and encrypt other confidential information +such as administrator passwords. The keystore of the HTTPS transport is configured in the axis2.xml file +under the HTTPS transport receiver and HTTPS transport sender configurations. +

+ +
+<parameter name="keystore" locked="false">
+	<KeyStore>
+		<Location>repository/resources/security/wso2carbon.jks</Location>
+		<Type>JKS</Type>
+		<Password>wso2carbon</Password>
+		<KeyPassword>wso2carbon</KeyPassword>
+	</KeyStore>
+</parameter>
+<parameter name="truststore" locked="false">
+	<TrustStore>
+		<Location>repository/resources/security/client-truststore.jks</Location>
+		<Type>JKS</Type>
+		<Password>wso2carbon</Password>
+	</TrustStore>
+</parameter>
+
+ +

+The default keystores can be found in ESB_HOME/repository/resources/security directory. To change the keystores used +by the HTTPS transport update the HTTPS transport receiver and sender configurations by specifying the paths +to keystore files and other attributes of the files such as the keystore passwords. Under the <KeyStore> +element two password values must be specified. The <Password> element should indicate the password of +the keystore file. The <KeyPassword> elemenet should point to the password required to access the private key. +

+

+The keystore used to encrypt administrator passwords and other confidential information in Carbon is configured in +ESB_HOME/repository/conf/carbon.xml file. This keystore configuration can be found under the <security> +element of the carbon.xml file. By default this is also used by the security management component when it +comes to securing deployed Web Services with WS-Security. +

+ +
+<KeyStore>
+	<Location>${carbon.home}/resources/security/wso2carbon.jks</Location>
+	<Type>JKS</Type>
+	<Password>wso2carbon</Password>
+	<KeyAlias>wso2carbon</KeyAlias>
+	<KeyPassword>wso2carbon</KeyPassword>
+</KeyStore>
+
+ +

Setting Up Host Names and Ports

+

+The bind address values and HTTP/HTTPS ports used by the ESB server should be configured in the +ESB_HOME/repository/conf/axis2.xml file. To configure the bind address for the server, define the following +parameter under the HTTP and HTTPS transport receiver configurations in the axis2.xml file. +

+ +
+<parameter name="bind-address" locked="false">hostname or IP address</parameter>
+
+ +

+Similarly the HTTP and HTTPS ports used by the ESB HTTP-NIO transport should be configured by specifying the +following parameter in the HTTP/HTTPS transport receiver configurations in the axis2.xml file. +

+ +
+<parameter name="port" locked="false">8280</parameter>
+
+ +

+The following sample HTTP configuration shows how to listen on HTTP port 8280 bound to the hostname my.test.server.com +

+ +
+<transportReceiver name="http" class="org.apache.synapse.transport.nhttp.HttpCoreNIOListener">
+	<parameter name="port" locked="false">8280</parameter>
+	<parameter name="non-blocking" locked="false">true</parameter>
+	<parameter name="bind-address" locked="false">my.test.server.com</parameter>
+</transportReceiver>
+
+ +

+To change the ports used by the ESB management console you must modify the ESB_HOME/repository/conf/mgt-transports.xml. +By default the management console would accept HTTPS requests on port 9443. Change the following parameter +to set the HTTPS port used by the console. +

+ +
+<parameter name="port">9443</parameter>
+
+ +

+In situations where a bind address is specifically defined in the axis2.xml it is recommended to define a +WSDL prefix for the HTTP and HTTPS transports. The WSDL prefix value will be added to all the HTTP/HTTPS +endpoints defined in the auto generated and user published WSDLs. To setup a WSDL prefix define the following +parameter under the HTTP and HTTPS receiver configurations in the axis2.xml file. +

+ +
+<parameter name="WSDLEPRPrefix" locked="false">https://apachehost:port/somepath</parameter>
+
+ +

+WSO2 ESB also allows you to setup a HTTP proxy port to deploy the ESB behind a proxy server using Apache mod_proxy. +In such deployments you need to specify the HTTP proxy port in the axis2.xml file's HTTP/HTTPS receiver +configurations using the following parameter. +

+ +
+<parameter name="proxyPort">80</parameter>
+
+ +

+Please refer the WSO2 Carbon Transports Catalog for more information on setting up HTTP and HTTPS NIO transports +and the servlet HTTPS transport for various deployments. +

+ +

Performance Tuning WSO2 ESB

+

+We recommend that you install WSO2 ESB on Unix/Linux systems for production deployments. This section, for +the most part, assumes that you have setup the ESB on a server running Unix/Linux. Also keep in mind that +you should not take performance tuning steps described here lightly. Performance tuning requires you to modify +some important system files which would effect all the programs running on the server. Hence care must be +applied and please refer Unix/Linux documentation for more details on the configuration files described here. +

+

+To optimize the network performance and OS performance for the ESB you will have to modify the /etc/sysctl.conf +file. We recommend specifying the following entries in this file. +

+ +
+net.ipv4.tcp_fin_timeout = 30
+fs.file-max = 2097152
+net.ipv4.tcp_tw_recycle = 1
+net.ipv4.tcp_tw_reuse = 1
+net.core.rmem_default = 524288
+net.core.wmem_default = 524288
+net.core.rmem_max = 67108864
+net.core.wmem_max = 67108864
+net.ipv4.tcp_rmem = 4096 87380 16777216
+net.ipv4.tcp_wmem = 4096 65536 16777216
+
+ +

+These settings specify a larger port range, a more effective TCP connection timeout value and a number of +other important parameters at the system level. +

+

+Also you may specify the following entries in the /etc/security/limits.conf file to alter the number of allowed +open files for system users. +

+ +
+* soft nofile 4096
+* hard nofile 65535
+
+ +

+You can tune up the HTTP-NIO transport performance by creating a nhhtp.properties file for the ESB. This +configuration file should be placed in the ESB_HOME/lib/core/WEB-INF/classes directory. You can change the +socket timeout values, connection timeout values and HTTP receiver thread pool parameters by specifying them +in the nhttp.properties file. A sample set of values that can be included in the nhttp.properties file is +specified below. +

+ +
+http.socket.timeout=60000
+http.socket.buffer-size=8192
+http.tcp.nodelay=1
+http.connection.stalecheck=0
+
+# 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
+
+ +

+When the nhttp.properties file is not provided a set of default values will be used to initialize the +thread pool of the HTTP-NIO transports. However the default values (mentioned in the above example) are +suitable for most deployments and it is recommended to leave them unchanged without overriding the values +using a nhttp.properties configuration file. +

+ + diff --git a/docs/xdoc/admin_guide.xml~ b/docs/xdoc/admin_guide.xml~ new file mode 100644 index 0000000000..580b98241b --- /dev/null +++ b/docs/xdoc/admin_guide.xml~ @@ -0,0 +1,1032 @@ + + + + + + + WSO2 ESB - System Administration Guide + + + + + + + [ Documentation Index ] +

+ WSO2 Enterprise Service Bus -ESB System Administration Guide +

+

+This is a manual on how to maintain and administrate a WSO2 ESB instance. It explains how various +features of the ESB can be configured using the ESB management console and by modifying the ESB +configuration files. Descriptions are provided on advanced features like Remote/Embedded +registry configuration, adding external libraries, managing key stores and user management. It +also explains how to performance tune the ESB runtime for extreme throughput. +

+

Contents

+

+

+

+ +

+ Introduction +

+

+WSO2 ESB is a production grade open source ESB solution based on the lightweight Apache Synapse ESB. +WSO2 ESB supports service mediation, message mediation, load balancing, clustering and many more +enterprise integration techniques out of the box. It also supports a range of application and transport +level protocols such as HTTP, JMS, Mail, VFS, FIX and a variety of industrial messaging standards such as +Hessian. +

+

+Starting from version 2.0, WSO2 ESB is based on the revolutionary WSO2 Carbon framework. WSO2 Carbon +is an OSGi based middleware framework for SOA. Currently all WSO2 Java products are based on WSO2 +Carbon including WSO2 Governance Registry and WSO2 AS. Since ESB is OSGi based some knowledge in +OSGi would be helpful in administrating the WSO2 ESB. +

+

+This document explains how to get WSO2 ESB and install it on a server. The latter sections of the +document illustrates how to setup and configure various features of the WSO2 ESB and how to performance +tune various aspects of the product. +

+ +

Document Conventions

+
    +
  • 'ESB_HOME' refers to the directory in the file system where WSO2 ESB is installed
  • +
  • 'ESB_SRC_HOME' refers to the directory in the file system where WSO2 ESB source distribution is installed
  • +
  • All file paths follow Unix/Linux conventions but they resemble Windows file paths as well
  • +
+ +

Getting WSO2 ESB

+

+Binary distributions and source distributions of WSO2 ESB can be downloaded free from the +WSO2 ESB home page in the WSO2 Oxygen Tank. Before proceeding to the +downloads page you will be asked to register on the WSO2 Oxygen Tank. Registration is free and optional +however it is recommended that you sign up for an account right away since registered Oxygen Tank users +get exclusive access to our support forums and tons of valuable content related to SOA and Web Services. +

+

+Once you are on the downloads page click on the relevant links to download a binary distribution or a +source distribution of the latest stable release of the WSO2 ESB. If you are interested in an older +version of the ESB, scroll down in the downloads page to locate the links to previous releases. You will +also find links to download developer releases and nightly builds of the WSO2 ESB on the same page. We +recommend that you always download the latest stable release. If you want to try out a feature that was +added very recently you can try out a nightly build. +

+

+If you downloaded a source distribution of the ESB you need to build the source to get the executable +binary. WSO2 ESB uses an Apache Maven2 based build system and +therefore you need to first download and install Apache Maven2. Please refer Maven2 documentation on +installing and configuring Apache Maven2. Also note that Apache Maven2 requires Java to run. +Once Maven2 is properly configured extract the downloaded source distribution and change your working +directory to the directory that is created. Then execute the command 'mvn clean install' to run the builder. +Once the build process is complete you can find the binary distribution archive in ESB_SRC_HOME/modules/distribution/target +directory. +

+ +

Installing and Running WSO2 ESB

+

+To install the WSO2 ESB simply extract the downloaded binary distribution archive. If you built WSO2 ESB +from source extract the archive created by the builder. We recommend installing WSO2 ESB on a Unix/Linux +system since that will enable you to get the maximum out of the ESB. In order to be able to start WSO2 ESB +you first need Java 5 or higher. Having installed Java on your system please set the JAVA_HOME environment +variable to point to the directory in which Java is installed. +

+

Running WSO2 ESB in Standalone Mode

+

+Now you are all set to start WSO2 ESB in the standalone mode. Go to ESB_HOME/bin directory and if you are +on Unix/Linux execute the wso2server.sh shell script or if you are on Windows execute the wso2server.bat +batch file. This will start the ESB and you can see the progress of the startup procedure on the console. +Please note that server startup may take some time depending on the hardware configuration of your system. +The very first startup of the ESB can take up a few additional seconds since some first time configuration +procedure is run by the ESB. If the server started up cleanly you should get an output similar to the following +on the console. +

+
+  [2010-03-23 10:34:17,594]  INFO - Main Initializing system...
+  [2010-03-23 10:34:25,176]  INFO - CarbonCoreActivator Starting WSO2 Carbon...
+  [2010-03-23 10:34:25,178]  INFO - CarbonCoreActivator Operating System : Linux 2.6.28-16-generic, amd64
+  [2010-03-23 10:34:25,178]  INFO - CarbonCoreActivator Java Home        : /opt/jdk1.6.0_16/jre
+  [2010-03-23 10:34:25,178]  INFO - CarbonCoreActivator Java Version     : 1.6.0_16
+  [2010-03-23 10:34:25,178]  INFO - CarbonCoreActivator Java VM          : Java HotSpot(TM) 64-Bit Server VM 14.2-b01,Sun Microsystems Inc.
+  [2010-03-23 10:34:25,178]  INFO - CarbonCoreActivator Carbon Home      : /home/user/wso2esb-3.0.1
+  [2010-03-23 10:34:25,179]  INFO - CarbonCoreActivator Java Temp Dir    : /home/user/wso2esb-3.0.1/tmp
+  [2010-03-23 10:34:25,179]  INFO - CarbonCoreActivator User             : user, en-US, Asia/Colombo
+  [2010-03-23 10:34:29,715]  INFO - RegistryCoreServiceComponent Registry Mode    : READ-WRITE
+  [2010-03-23 10:34:32,349]  INFO - CarbonServerManager Starting Carbon initialization...
+  [2010-03-23 10:34:32,561]  INFO - ClusterBuilder Clustering has been disabled
+  [2010-03-23 10:34:32,742]  INFO - DeploymentInterceptor Deploying Axis2 module : relay-3.0
+  [2010-03-23 10:34:32,799]  INFO - DeploymentInterceptor Deploying Axis2 module : wso2mex-3.0
+  [2010-03-23 10:34:32,818]  INFO - DeploymentInterceptor Deploying Axis2 module : rampart-SNAPSHOT
+  [2010-03-23 10:34:32,862]  INFO - DeploymentInterceptor Deploying Axis2 module : sandesha2-3.0
+  [2010-03-23 10:34:32,916]  INFO - DeploymentInterceptor Deploying Axis2 module : wso2caching-3.0
+  [2010-03-23 10:34:32,989]  INFO - DeploymentInterceptor Deploying Axis2 module : wso2xfer-3.0
+  [2010-03-23 10:34:33,001]  INFO - DeploymentInterceptor Deploying Axis2 module : rahas-SNAPSHOT
+  [2010-03-23 10:34:33,019]  INFO - DeploymentInterceptor Deploying Axis2 module : savan-SNAPSHOT
+  [2010-03-23 10:34:33,034]  INFO - DeploymentInterceptor Deploying Axis2 module : wso2throttle-3.0
+  [2010-03-23 10:34:33,125]  INFO - DeploymentInterceptor Deploying Axis2 module : addressing-1.6-wso2v1
+  [2010-03-23 10:34:33,202]  INFO - HttpCoreNIOSSLSender Loading Identity Keystore from : resources/security/wso2carbon.jks
+  [2010-03-23 10:34:33,228]  INFO - HttpCoreNIOSSLSender Loading Trust Keystore from : resources/security/client-truststore.jks
+  [2010-03-23 10:34:33,256]  INFO - HttpCoreNIOSender HTTPS Sender starting
+  [2010-03-23 10:34:33,269]  INFO - HttpCoreNIOSender HTTP Sender starting
+  [2010-03-23 10:34:33,370]  INFO - DeploymentInterceptor Deploying Axis2 service : echo
+  [2010-03-23 10:34:33,899]  INFO - DeploymentInterceptor Deploying Axis2 service : version
+  [2010-03-23 10:34:37,698]  INFO - DeploymentInterceptor Deploying Axis2 service : wso2carbon-sts
+  [2010-03-23 10:34:38,273]  INFO - DeploymentInterceptor Deploying Axis2 service : XKMS
+  [2010-03-23 10:34:38,480]  INFO - CarbonServerManager Repository       : /home/user/wso2esb-3.0.1/repository/deployment/server/
+  [2010-03-23 10:34:38,506]  INFO - EmbeddedRegistryBasedSubscriptionManager Connection established with the registry
+  [2010-03-23 10:34:38,530]  INFO - ServiceBusInitializer Starting ESB...
+  [2010-03-23 10:34:38,573]  INFO - ServiceBusInitializer Initializing Apache Synapse...
+  [2010-03-23 10:34:38,580]  INFO - SynapseControllerFactory Using Synapse home : /home/user/wso2esb-3.0.1/.
+  [2010-03-23 10:34:38,580]  INFO - SynapseControllerFactory Using synapse.xml location : /home/user/wso2esb-3.0.1/./repository/conf/synapse-config
+  [2010-03-23 10:34:38,580]  INFO - SynapseControllerFactory Using server name : localhost
+  [2010-03-23 10:34:38,584]  INFO - SynapseControllerFactory The timeout handler will run every : 15s
+  [2010-03-23 10:34:38,634]  INFO - Axis2SynapseController Initializing Synapse at : Tue Mar 23 10:34:38 IST 2010
+  [2010-03-23 10:34:38,636]  INFO - Axis2SynapseController Loading mediator extensions...
+  [2010-03-23 10:34:38,642]  INFO - CarbonSynapseController Loading the mediation configuration from the file system
+  [2010-03-23 10:34:38,645]  INFO - MultiXMLConfigurationBuilder Building synapse configuration from the synapse artifact repository at : ./repository/conf/synapse-config
+  [2010-03-23 10:34:38,646]  INFO - XMLConfigurationBuilder Generating the Synapse configuration model by parsing the XML configuration
+  [2010-03-23 10:34:39,077]  INFO - SynapseConfigurationBuilder Loaded Synapse configuration from the artifact repository at : ./repository/conf/synapse-config
+  [2010-03-23 10:34:39,208]  INFO - Axis2SynapseController Deploying the Synapse service...
+  [2010-03-23 10:34:39,212]  INFO - Axis2SynapseController Deploying Proxy services...
+  [2010-03-23 10:34:39,212]  INFO - Axis2SynapseController Deploying EventSources...
+  [2010-03-23 10:34:39,217]  INFO - ServerManager Server ready for processing...
+  [2010-03-23 10:34:40,219]  INFO - HttpCoreNIOSSLListener Loading Identity Keystore from : resources/security/wso2carbon.jks
+  [2010-03-23 10:34:40,221]  INFO - HttpCoreNIOSSLListener Loading Trust Keystore from : resources/security/client-truststore.jks
+  [2010-03-23 10:34:40,237]  INFO - HttpCoreNIOListener HTTPS Listener started on port : 8243
+  [2010-03-23 10:34:40,239]  INFO - HttpCoreNIOListener HTTP Listener started on port : 8280
+  [2010-03-23 10:34:40,798]  INFO - RegistryEventingServiceComponent Successfully Initialized Eventing on Registry
+  [2010-03-23 10:34:43,926]  INFO - CarbonUIServiceComponent Mgt Console URL  : https://10.100.1.209:9443/carbon/
+  [2010-03-23 10:34:43,940]  INFO - StartupFinalizerServiceComponent Started Transport Listener Manager
+  [2010-03-23 10:34:43,940]  INFO - StartupFinalizerServiceComponent Server           :  WSO2 ESB-3.0.1
+  [2010-03-23 10:34:43,940]  INFO - StartupFinalizerServiceComponent WSO2 Carbon started in 25 sec
+
+

+To verify that the ESB is up and running fire off your Web browser and go to https://localhost:9443/carbon. +This will take you to the WSO2 ESB on-line management console. +

+ +

+You can login to the console using the default user credentials given below. +

+
    +
  • Username: admin
  • +
  • Password: admin
  • +
+

+If you can get that far then the ESB is properly installed and running. +

+

+WSO2 ESB startup scripts stated above accept a few useful arguments. +

+

+--cleanRegistry
+This argument will remove the settings stored in the registry and replace them with factory settings. +It removes the /_system/config/repository collection and the /_system/local/repository collection in the +registry which are used to store resources and configurations managed by the ESB and the underlying +Carbon framework. Therefore the ESB will be forced to start fresh with factory settings. Starting from +WSO2 ESB 3.0 the mediation configuration (sequences, proxies etc) is read from the file system by default. +In that case this argument does not have any effect on the mediation configuration used by the ESB. +

+

+--debug <port>
+Enables remote debugging on the ESB through the specified port. +

+

+In addition to the above mentioned arguments the ESB startup scripts accept the following VM arguments. +

+

+-DosgiConsole
+Starts the OSGi console from which you can directly interact with the underlying OSGi framework. +

+

+-DloadFromRegistry
+This argument was first introduced in ESB 3.0. When set to 'true' it will force the ESB to load the mediation +configuration from the registry, instead of loading it from the file system. Please note that for this +argument to work the registry must contain a valid mediation configuration stored in it. Therefore one +cannot pass this argument to a fresh ESB instance which is starting from a clean registry. However after the +first startup the registry will contain a mediation configuration and hence subsequent startups can proceed +with this VM parameter. +

+

+-DwriteToFile
+Newly added to WSO2 ESB 3.0, this argument takes effect only when the mediation configuration is loaded +from the registry. When set to 'true' this parameter will force the ESB to save the configuration loaded +from the registry to the local file system at startup. +

+ +

Running ESB Samples

+

+WSO2 ESB ships with a large number of sample configurations which enables you to get familiar with the +product quickly and easily. Please refer the WSO2 ESB samples guide for sample configuration and details +on how to run them. You may start WSO2 ESB using those sample configuration by executing the +ESB_HOME/bin/wso2esb-sample.sh (for Unix/Linux) or ESB_HOME/bin/wso2esb-sample.bat (for Windows). +These launcher scripts take a mandatory argument -sn. Use this argument to specify the sample number. +

+

+eg: ./wso2esb-sample.sh -sn 250 (This will launch the ESB using the Sample 250 configuration) +

+

+The sample configuration files can be found in the ESB_HOME/repository/samples directory. +

+

+When launching the ESB using the wso2esb-sample.sh/wso2esb-sample.bat scripts a new registry context root +will be created for storing data and configurations related to that sample. Also note that these launcher +scripts accept the same set of arguments accepted by the wso2server.sh and wso2server.bat. +

+ +

WSO2 ESB Directory Hierarchy

+

+When you extract a WSO2 ESB binary distribution archive you will find the following directories in the +top level directory that is created. +

+ +

+bin -
+ Contains all the necessary scripts to interact with the WSO2 ESB instance. There are shell scripts + (with .sh extension) for Unix/Linux users and batch files (with .bat extension) for Windows users. + In general you will find the following scripts in this directory.
+
+

    +
  • + wso2server.sh/wso2server.bat - Launches WSO2 ESB +
  • +
  • + wso2esb-samples.sh/wso2esb-samples.bat - Launches WSO2 ESB using one of the sample configurations +
  • +
  • + wsdl2java.sh/wsdl2java.bat - Launches the Java stub generation tool for Web Services +
  • +
  • + java2wsdl.sh/java2wsdl.bat - Launches the WSDL generation tool for Java Web Services +
  • +
  • + tcpmon.sh/tcpmon.bat - Launches TCPMon, the TCP connection monitor +
  • +
  • + chpasswd.sh/chpasswd.bat -Use this script to change the administrator password without signing in to the server
    +
  • +
  • + ciphertool.sh/ciphertool.bat -<TODO: Indika>
    +
  • +
  • + daemon.sh -Start WSO2 ESB as a daemon on Unix/Linux systems
    +
  • +
  • + install.bat - Install WSO2 ESB as a background service on Windows
    +
  • +
  • + repowriter.sh/repowriter.bat +
  • +
  • + carbondump.sh/carbondump.bat - Create a dump file containing runtime information related to the ESB (Dump file is useful in debugging issues) +
  • +
+
+ In addition to the above mentioned scripts you will find a subdirectory named 'native' in the bin + directory.
+

+

+dbscripts -
+Contains a collection of database scripts required to create the Carbon database on a variety of database +management systems.
+

+

+lib -
+The lib directory houses all the jar files and OSGi bundles required by the embedded Tomcat instance. +The log4j.properties file used by the ESB is also stored here. In addition to that, the Carbon webapp +can be found in the lib/core directory. The lib/core/WEB-INF/classes directory houses some of +important configuration files of the ESB such as nhttp.properties, synapse.properties and datasources.properties. +

+

+repository -
+This directory houses all the OSGi bundles, service artifacts, modules, configurations and related resources +used by the WSO2 ESB instance. The repository/components/plugin directory will contain all the necessary OSGi bundles +at server runtime. In the components subdirectory you can also find a set of child directories such as lib, +mediators and extensions which can be used to deploy custom mediators and third party dependencies into the ESB. +The repository/conf subdirectory contains all the crucial configuration files such as axis2.xml and carbon.xml. The +mediation configuration is loaded from the repository/deployment/server/synapse-config directory. Also starting from ESB 3.0 +server logs are stored in the repository/logs directory. +

+

+resources -
+Contains additional resources required by WSO2 ESB. This includes security related resources such as +keystores. +

+

+samples -
+The samples directory contains the sample Axis2 server, sample Axis2 client, source code of the sample +services and clients and the ANT scripts required to build and run them. +

+

+tmp -
+The temporary files directory used by the ESB +

+ +

Using the WSO2 ESB Management Console

+

+WSO2 ESB management console is a Web based control panel powered by JSP and AJAX which enables system administrators +to interact with a running ESB instance, without having to touch any underlying configuration files. The +management console allows the users to command and control proxy services, sequences, transports, local +entries, registry, modules, endpoints and much more. ESB management console is a great way to try things +out without having to edit the actual configuration files or without having to restart the ESB for +changes to take effect. +

+

+We recommend using Mozilla Firefox 3 or Internet Explorer 7 to access the WSO2 ESB management console. +Please note that your browser must be JavaScript enabled to take the full advantage of the management console. +To access the ESB management console fire off you Web browser and navigate to +https://<Server Host>:<Server Port>/<Context>. If you are running the Web browser on +the same machine as the ESB you may use 'localhost' as the server host. The default port and the context +for the ESB management console are '9443' and 'carbon' respectively. If you entered the URL correctly you +will be taken to the management console's login page. +

+

+On the login page enter 'admin' as the username and the password to login to the system. You can change +user credentials and even add new users once you login. Controls and wizards in the ESB management console +are pretty much self explanatory. However if you are having trouble finding your way in the management +console, click on the 'Help' link at the top right corner of any page to access context sensitive help. +

+

+Please note that the ESB management console makes use of the default HTTPS servlet transport which is +configured in the ESB_HOME/repository/conf/mgt-transports.xml file. It is important that this transport +is always properly configured in the mentioned file. Otherwise the management console might be inaccessible +to the users. +

+ +

User Management

+

+To access the WSO2 ESB user management features, first sign in to the ESB management console and click on +'User and Roles' under the 'Configure' menu in the left navigation bar. This will take you to the User +Management home page which contains the controls illustrated below. +

+ +

+From here you can manage users and roles. A user is associated with one or more roles (generally specified at +user creation time) and each role is associated with zero or more permissions (generally specified at +role creation time). Therefore the set of permissions owned by a user is determined by the roles assigned to +that user. A user owns the union of all the permissions associated with the roles assigned to that user. By +default ESB comes with only two roles, the 'admin' role and the 'everyone' role. There is also a third role +named 'system' which is not visible in the management console. Every user will be assigned the +'everyone' role. This role does not have any permissions by default. Users with the 'admin' role have full +access to all the features and controls in the ESB (all permissions). By default the user 'admin' is assigned the +'admin' role along with the 'everyone' role. Also note that the ESB UI does not allow configuing the permissions +assigned to the 'admin' role. +

+

+The permission model of WSO2 ESB is hierarchical. Therefore permissions +can be assigned in a fine grained manner or a coarse grained manner. For an example one could assign the 'Configure' +admin permission to a role. The role will be able to configure event sources, scheduled tasks and many other things. +This is a coarse grained permission allocation. On the other hand one may assign the specific +'Transport Management', 'Configure Tasks' or 'Configure Data Sources' permission to a role which is a fine grained +permission allocation. The full ESB permission tree looks as follows. +

+ +

+Use the 'User Management' page in the UI to add new users, add new roles, assign and withdraw permissions from +roles and change login credentials of users. To add a new role to the system click on 'Roles' in the User +Management home page and on the page that appears click the 'Add New Role' link. This will start the 'Add +Role' wizard. The wizard will guide you though the process of creating a role by specifying a unique name +for the role and adding the relevant permissions to the new role. Similarly to create a new user, click on +'Users' in the User Management home page. Then from the next page that appears select 'Create New User' link. +This will launch the 'Add User' wizard which will enable you to create a new user account with login credentials +and associate the account with one or more existing roles. The ESB management console also enables you to +search for and modify existing users and roles. +

+

Using External User Stores (LDAP/AD)

+

+You can also connect an external user store (database) with WSO2 ESB. Such external stores are configured through +the user-mgt.xml file which can be found in the repository/conf directory. Settings required to connect an LDAP +based user store or an Active Directory based user store are provided in the default user-mgt.xml file. Simply +uncomment the relevant entries in the file and update the required parameters. Also note that the ESB can have +only one user store at any given moment. Hence when you want to connect to a different user store you also need +to comment out the default user store settings (LDAP user store manager) in the user-mgt.xml file. Configuration +settings for the LDAP based user store looks as follows. +

+
+<UserStoreManager class="org.wso2.carbon.user.core.ldap.ApacheDSUserStoreManager">
+    <Property name="ReadOnly">false</Property>
+    <Property name="ConnectionURL">ldap://localhost:${Ports.EmbeddedLDAP.LDAPServerPort}</Property>
+    <Property name="ConnectionName">uid=admin,ou=system</Property>
+    <Property name="ConnectionPassword">admin</Property>
+    <Property name="passwordHashMethod">SHA</Property>
+    <Property name="UserNameListFilter">(objectClass=person)</Property>
+    <Property name="UserEntryObjectClass">wso2Person</Property>
+    <Property name="UserSearchBase">ou=Users,dc=wso2,dc=org</Property>
+    <Property name="UserNameSearchFilter">(&(objectClass=person)(uid=?))</Property>
+    <Property name="UserNameAttribute">uid</Property>
+    <Property name="PasswordJavaScriptRegEx">[\\S]{5,30}</Property>
+    <Property name="UsernameJavaScriptRegEx">[\\S]{3,30}</Property>
+    <Property name="UsernameJavaRegEx">^[^~!@#$;%^*+={}\\|\\\\<>]{3,30}$</Property>
+    <Property name="RolenameJavaScriptRegEx">[\\S]{3,30}</Property>
+    <Property name="RolenameJavaRegEx">^[^~!@#$;%^*+={}\\|\\\\<>]{3,30}$</Property>
+    <Property name="ReadLDAPGroups">true</Property>
+    <Property name="WriteLDAPGroups">true</Property>
+    <Property name="EmptyRolesAllowed">true</Property>
+    <Property name="GroupSearchBase">ou=Groups,dc=wso2,dc=org</Property>
+    <Property name="GroupNameListFilter">(objectClass=groupOfNames)</Property>
+    <Property name="GroupEntryObjectClass">groupOfNames</Property>
+    <Property name="GroupNameSearchFilter">(&(objectClass=groupOfNames)(cn=?))</Property>
+    <Property name="GroupNameAttribute">cn</Property>
+    <Property name="MembershipAttribute">member</Property>
+</UserStoreManager>
+
+

+For more information on using external user stores please refer User Core Admin +Guide. +

+ +

Setting Up Logging

+

+Logging is one of the most important aspects of a production grade server. A properly configured logging system +is vital in identifying errors, security threats and usage patterns. WSO2 ESB uses a log4j based logging mechanism +through Apache Commons Logging facade library. The log4j.properties file which governs how logging is performed by +the server can be found in ESB_HOME/lib directory. However it is recommended not to make any alterations to the +default log4j.properties file. The recommended way of setting up logging is by using the ESB management console. +Simply login to the management console and click on 'Logging' under the 'Configure' menu in the left navigation bar. +From here you can setup various appenders and configure log levels for various loggers. Any changes to the logging +configuration you make from the management console will get priority over what is defined in the actual +log4j.properties file. +

+

+By default WSO2 ESB comes with the following log appenders configured. +

+
    +
  • + CARBON_CONSOLE (Logs to the console when the server is running) +
  • +
  • + CARBON_LOGFILE (Writes the logs to ESB_HOME/repository/logs/wso2-esb.log) +
  • +
  • + CARBON_MEMORY +
  • +
  • + CARBON_SYS_LOG +
  • +
  • + SERVICE_APPENDER (Writes mediation time audit messages to ESB_HOME/repository/logs/wso2-esb-service.log) +
  • +
  • + TRACE_APPENDER (Writes mediation time tracing/debug messages to the ESB_HOME/repository/logs/wso2-esb-trace.log for tracing enabled services) +
  • +
  • + TRACE_MEMORYAPPENDER +
  • +
+

+Tracing can be enabled for individual mediation sequences and proxy services from the 'Mediation Sequences' +home page and the 'Service Dashboard' page respectively. Click on the 'Sequences' link under 'Mediation' in +the 'Manage' menu of the left navigation bar to access the 'Mediation Sequences' page. This page lists all +the deployed sequences. Each sequence gives you the options to enable/disable tracing. To access the service +dashboard for a proxy service go to the Services List page and click on the proxy service that you are +interested in. Once a sequence or a proxy service is tracing enabled you can view the generated log messages +by visiting the 'Mediation Tracer' page under the 'Monitor' menu. The 'Monitor' menu also gives you access +to the system logs and the SOAP tracer logs all through the Web interface itself. +

+ + +

Configuring the Underlying Axis2 Engine

+

+WSO2 ESB is based on Apache Synapse lightweight ESB which in turns uses the Apache Axis2 SOAP engine. Every +WSO2 ESB administrator is expected to have at least a basic understanding of Axis2 and Axis2 configuration model. +The global configuration of the Axis2 engine is specified in a file named axis2.xml. This configuration file can +be found in the ESB_HOME/repository/conf directory. Any settings configured in the axis2.xml file are directly +applied to the server at startup time. Generally, one can configure the following settings in the axis2.xml file. +

+
    +
  • + Global system parameters (eg: hotdeployment, hotupdate, servicepath etc) +
  • +
  • + Global Axis2 listeners (Axis2 observer implementations which are notified of Axis2 events) +
  • +
  • + Deployers +
  • +
  • + Message receivers, formatters and builders +
  • +
  • + Transport receivers and senders +
  • +
  • + Globally engaged modules (eg: addressing) +
  • +
  • + Clustering +
  • +
  • + Axis2 phases +
  • +
+

+The axis2.xml file which comes with WSO2 ESB contains examples and descriptions illustrating how the above +can be configured and setup for common deployment scenarios. +

+ +

Mediation Configuration

+

+Mediation configuration is the most important part of the WSO2 ESB as far as the functionality of the service +bus is concerned. The mediation configuration consists of following items. +

+
    +
  • Endpoints
  • +
  • Sequences
  • +
  • Proxy services
  • +
  • Scheduled tasks
  • +
  • Event sources
  • +
  • Local entries
  • +
  • Priority executors (new in ESB 3.0)
  • +
+

+Each of the above items can be configured through the management console. New instances of above items +can be added to the ESB, existing items can be modified or removed. The 'Synapse' entry in the 'Configure' +menu provides a single unified view of the entire mediation configuration and allows the user to make +modifications to it using the Synapse configuration language. +

+ +

Persistence

+

+By default the mediation configuration is stored in the file system as well as in the registry. In the file +system, configuration is saved under the ESB_HOME/repository/conf/synapse-config directory. There are separate +subdirectories to store different types of configuration items. When you add a new item using the management +console it will be saved to a new file under the synapse-config directory. For an example, if you add a new +endpoint named 'foo' from the UI, it will be saved to a file named foo.xml in ESB_HOME/repository/conf/synapse-config/endpoints +directory. Any further modifications to the endpoint foo will be saved back to the same file. However if you +add a new item from the Synapse configuration editor in the UI (in Configure menu) it will be saved to +ESB_HOME/repository/conf/synapse-config/synapse.xml file. +

+

+You can customize the behavior of mediation configuration persistence by editing the carbon.xml file. You may +add the following entry to the carbon.xml and tune up the parameter values as appropriate. +

+
+<MediationConfig>
+    <LoadFromRegistry>false</LoadFromRegistry>
+    <SaveToFile>false</SaveToFile>
+    <Persistence>enabled</Persistence>
+    <RegistryPersistence>enabled</RegistryPersistence>
+</MediationConfig>
+
+

+Set the LoadFromRegistry to 'true' if you want to load the mediation configuration from the registry instead of the file +system. SaveToFile option takes effect only when LoadFromRegistry is set to 'true'. If both values are set to 'true' +the mediation configuration will be loaded from the registry and will also be saved to the local file system at +startup. If you want to prevent the ESB from saving the mediation configuration to the registry set RegistryPersistence +to 'disabled'. By default this is enabled. You can turn off all persistence activies by setting Persistence to +'disabled'. In that case mediation configuration will not be saved to the file system nor the registry. The configuration +in the disk/registry is effectively frozen. But the changes made from the UI will still take effect in the runtime. But +such changes will not survive a restart since they are not saved to persistence store. +

+ +

Dependency Tracking

+

+WSO2 ESB keeps track of the dependencies among various mediation configuration elements. In a typical mediation +configuration there are often dependencies among sequences, endpoints, proxy services and local entires. A +sequence can make references to other sequences, local entries and endpoints. A proxy service may also make references to +sequences and endpoints. The ESB runtime by default keeps track of such dependencies and warns the user, if he +attempts to remove a particular item from the configuration which is a dependency for another item. +

+ +

+The dependency tacking process takes up a few CPU cycles and memory to compute and keep track of the +dependencies at runtime. Therefore it is recommended to turn this feature off in production environments. +To turn off dependency tracking open up the synapse.properties file which can be found in the +ESB_HOME/webapps/ROOT/WEB-INF/classes directory and comment out the following line: +

+
synapse.observers=org.wso2.carbon.mediation.dependency.mgt.DependencyTracker
+

+You also need to restart the ESB for the change to take effect. Commenting out the above entry will disengage +the dependency tracker and hence the ESB will stop computing and keeping track of dependencies among +different configuration items in the mediation configuration. +

+ +

Hot Deployment of Mediation Artifacts

+

+WSO2 ESB 3.0 introduces the hot deployment feature for mediation artifacts. With this feature you can hot +deploy artifacts like endpoints, sequences and proxy services into the ESB_HOME/repository/conf/synapse-config +directory. Simply save the artifact configuration to an XML file and drop it into the relevant subdirectory in +the synapse-config parent directory. ESB will pick up the newly added file and get it deployed in the server +runtime. Once deployed you will be able to view it through the management console and make further changes if +necessary. Similarly you can make changes to an existing file which contains a mediation configuration item +and the ESB will pick the changes up through the hot update feature. +

+

+In a production system it is recommended to turn off hot deployment and update for smooth operation of the ESB. +To turn off hot deployment and hot update open up the axis2.xml file in repository/conf directory and set the +following two parameter values to 'false'. (These are by default set to 'true') +

+
+    <parameter name="hotdeployment" locked="false">false</parameter>
+
+    <parameter name="hotupdate" locked="false">false</parameter>
+
+ +

Installing and Managing Features

+

+New features can be easily installed into the ESB by using the 'WSO2 Carbon Component Manager' that comes +with the ESB. Component manager is powered by Equinox P2 and allows you to connect to a remote or local P2 +repository and get any feature installed into the ESB runtime. You can also uninstall existing features of +the ESB and come up with a customized version of WSO2 ESB tailored to meet your requirements. +

+

+To use the component manager, login to the management console and click on 'Features' under the +'Configure' menu. Go to the 'Settings' tab and click on 'Manage Repositories'. Click 'Add New Repository' +and specify the P2 repository to which you wish to connect to. The official WSO2 P2 repository is available +over http://dist.wso2.org/p2. +

+

+Once the repository is configured go to the 'Available Features' tab to browse through the features and get them +installed to the ESB. The installation of a feature can take a while depending on the network bandwidth and +hardware configuration available. Once a feature has been successfully installed you will be prompted to logout +and restart the ESB. +

+

+If you wish to uninstall an existing feature go to the 'Installed Features' tab, select the features to be +uninstalled and click on 'Uninstall' at the bottom of the page. +

+ + +

Adding External Dependencies to the System

+

+You would want to deploy external dependency jars into the WSO2 ESB server in many scenarios. Generally one +would want to add external dependencies in following situations. +

+
    +
  • + Enabling and configuring a new transport (Many transport implementations such as JMS and FIX require + adding a set of external dependencies to the server) +
  • +
  • + Adding a custom mediator +
  • +
  • + Adding a custom handler or a module +
  • +
+

+To add an external dependency to the WSO2 ESB you simply need to copy the necessary jar file(s) to +ESB_HOME/repository/components/lib or ESB_HOME/repository/components/extensions. Jars copied to these +directories will be automatically converted into OSGi bundles on ESB startup. Jars copied to +ESB_HOME/repository/components/extensions will be converted into OSGi bundles which are fragments of the +main system bundle. WSO2 ESB also provides the ESB_HOME/repository/components/mediators directory to deploy +custom mediators into the ESB. +

+

+Currently WSO2 ESB does not support deploying external dependencies at runtime. Therefore after copying +the external dependency jars to the relevant locations the server must be restarted for the server to be +able to pick them up. +

+ +

Registry Integration

+

+WSO2 ESB makes use of a WSO2 Governance Registry instance to store various configurations and artifacts +such as proxy services, sequences and endpoints. Simply put a registry is a content store and a metadata +repository. Various SOA artifacts such as services, WSDLs and configuration files can be stored in a +registry keyed by unique paths. A path is similar to a Unix file path. In WSO2 ESB all configurations +pertaining to modules, logging, security, data sources and other service groups are stored in the registry +by default. Starting from WSO2 Carbon 2.0 all the transport configurations are also stored in the registry. +WSO2 ESB 2.1 introduced a feature to directly store endpoints and sequences to the registry with a user +specified key value. +

+

+WSO2 ESB accesses the registry in two ways. In many cases it accesses the registry by directly calling the +registry API from Carbon components. In some special situations it gains access to the registry through the +underlying Apache Synapse configuration. It is important that Synapse configuration should always include a +registry definition. That is, the ESB configuration should include the following registry definition. +

+ +
+<registry provider="org.wso2.carbon.mediation.registry.WSO2Registry">
+	<parameter name="cachableDuration">15000</parameter>
+</registry>
+
+ +

+Starting from ESB 3.0 the registry that comes with WSO2 ESB is actually a combination of 3 registries. +

+
    +
  • Local repository (Used to store settings/metadata specific to the ESB node - This registry cannot be shared)
  • +
  • Configuration registry (Used to store settings/metadata that is shared across a cluster of ESB instances)
  • +
  • Governance registry (Used to store user specified metadata and resources and can be shared across an organization)
  • +
+

+The above registry instances are mounted to a single top level registry to provide a single unified view. Mount points of +the three registries are /_system/local, /_system/config and /_system/governance respectively. One could browse +the contents of the registry used by the ESB from the WSO2 ESB management console. To browse the registry, first +login to the ESB management console and click on 'Registry Browser' link under the 'Registry' menu. +

+ + +

Using the Embedded Registry

+

+WSO2 ESB comes with an embedded WSO2 Governance Registry (WSO2 G-Reg) which is used by the ESB to store configurations +and other deployment artifacts. The embedded registry instance makes use of the embedded ESB database. This is an H2 +database and the data files are by default stored in the directory named ESB_HOME/repository/database. If you are running +the ESB in the embedded registry mode you should be careful not to manually alter any files stored in this directory as +that might lead to database corruption or data loss. +

+

+The embedded registry instance is configured by the registry.xml file which can be found in the ESB_HOME/repository/conf directory. +In this configuration you could point the embedded registry to a database other than the default embedded H2 database. +To change the database used by the registry or change the location of the database files edit the following section of the +registry.xml. +

+
+<dbconfig name="wso2registry">
+	<url>jdbc:h2:database/WSO2CARBON_DB</url>
+	<userName>wso2carbon</userName>
+	<password>wso2carbon</password>
+	<driverName>org.h2.Driver</driverName>
+	<maxActive>50</maxActive>
+	<maxWait>60000</maxWait>
+	<minIdle>5</minIdle>
+</dbconfig>
+
+

+WSO2 Governance Registry can be run in two operational modes, namely the ReadWrite mode and the ReadOnly mode. By default +it operates in the ReadWrite mode. This mode is set by the following element in the registry.xml file. +

+
+<readOnly>false</readOnly>    
+
+

+When the registry ReadOnly mode is set to true the ESB will not be able to store resources or write values +to the registry. It will be capable of reading the existing resources only. If you want to make sure that +the ESB or any of the ESB administrators do not alter the resources already stored in the registry this +value should be set to true. Also in a clustered deployment it is recommended that only one ESB instance +accesses the registry in the ReadWrite mode. All other ESB nodes should be accessing the registry in the +ReadOnly mode to prevent different ESB servers from modifying the same resources at the same time. Any +configuration updates should be done via the ESB instancce in ReadWrite mode. +

+

+In addition to configuring the database instance you can configure media type handlers for various media types +and setup various registry related system parameters by modifying the registry.xml file. The default +configuration defines the following parameters. +

+
+<staticConfiguration>
+	<versioningProperties>true</versioningProperties>
+	<versioningComments>true</versioningComments>
+	<versioningTags>true</versioningTags>
+	<versioningRatings>true</versioningRatings>
+</staticConfiguration>    
+
+

+Please refer WSO2 G-Reg documentation for further information on setting up media type handlers and other +global parameters. +

+ +

Using the Remote Registry

+

+You can configure the ESB to use a remotely hosted WSO2 Governance Registry instance as the metadata and +configuration store, instead of using the embedded registry instance. For that you need to edit the +ESB_HOME/repository/conf/registry.xml file and modify the database configuration to point to the same +database as the remote registry instance. Edit the dbconfig element in the registry.xml and make sure that +the ESB is pointed to the same database as your WSO2 Governance Registry instance. +

+ +

Setting Up Keystores

+

+WSO2 ESB uses several keystores to power the HTTPS transport and encrypt other confidential information +such as administrator passwords. The keystore of the HTTPS transport is configured in the axis2.xml file +under the HTTPS transport receiver and HTTPS transport sender configurations. +

+ +
+<parameter name="keystore" locked="false">
+	<KeyStore>
+		<Location>repository/resources/security/wso2carbon.jks</Location>
+		<Type>JKS</Type>
+		<Password>wso2carbon</Password>
+		<KeyPassword>wso2carbon</KeyPassword>
+	</KeyStore>
+</parameter>
+<parameter name="truststore" locked="false">
+	<TrustStore>
+		<Location>repository/resources/security/client-truststore.jks</Location>
+		<Type>JKS</Type>
+		<Password>wso2carbon</Password>
+	</TrustStore>
+</parameter>
+
+ +

+The default keystores can be found in ESB_HOME/repository/resources/security directory. To change the keystores used +by the HTTPS transport update the HTTPS transport receiver and sender configurations by specifying the paths +to keystore files and other attributes of the files such as the keystore passwords. Under the <KeyStore> +element two password values must be specified. The <Password> element should indicate the password of +the keystore file. The <KeyPassword> elemenet should point to the password required to access the private key. +

+

+The keystore used to encrypt administrator passwords and other confidential information in Carbon is configured in +ESB_HOME/repository/conf/carbon.xml file. This keystore configuration can be found under the <security> +element of the carbon.xml file. By default this is also used by the security management component when it +comes to securing deployed Web Services with WS-Security. +

+ +
+<KeyStore>
+	<Location>${carbon.home}/resources/security/wso2carbon.jks</Location>
+	<Type>JKS</Type>
+	<Password>wso2carbon</Password>
+	<KeyAlias>wso2carbon</KeyAlias>
+	<KeyPassword>wso2carbon</KeyPassword>
+</KeyStore>
+
+ +

Setting Up Host Names and Ports

+

+The bind address values and HTTP/HTTPS ports used by the ESB server should be configured in the +ESB_HOME/repository/conf/axis2.xml file. To configure the bind address for the server, define the following +parameter under the HTTP and HTTPS transport receiver configurations in the axis2.xml file. +

+ +
+<parameter name="bind-address" locked="false">hostname or IP address</parameter>
+
+ +

+Similarly the HTTP and HTTPS ports used by the ESB HTTP-NIO transport should be configured by specifying the +following parameter in the HTTP/HTTPS transport receiver configurations in the axis2.xml file. +

+ +
+<parameter name="port" locked="false">8280</parameter>
+
+ +

+The following sample HTTP configuration shows how to listen on HTTP port 8280 bound to the hostname my.test.server.com +

+ +
+<transportReceiver name="http" class="org.apache.synapse.transport.nhttp.HttpCoreNIOListener">
+	<parameter name="port" locked="false">8280</parameter>
+	<parameter name="non-blocking" locked="false">true</parameter>
+	<parameter name="bind-address" locked="false">my.test.server.com</parameter>
+</transportReceiver>
+
+ +

+To change the ports used by the ESB management console you must modify the ESB_HOME/repository/conf/mgt-transports.xml. +By default the management console would accept HTTPS requests on port 9443. Change the following parameter +to set the HTTPS port used by the console. +

+ +
+<parameter name="port">9443</parameter>
+
+ +

+In situations where a bind address is specifically defined in the axis2.xml it is recommended to define a +WSDL prefix for the HTTP and HTTPS transports. The WSDL prefix value will be added to all the HTTP/HTTPS +endpoints defined in the auto generated and user published WSDLs. To setup a WSDL prefix define the following +parameter under the HTTP and HTTPS receiver configurations in the axis2.xml file. +

+ +
+<parameter name="WSDLEPRPrefix" locked="false">https://apachehost:port/somepath</parameter>
+
+ +

+WSO2 ESB also allows you to setup a HTTP proxy port to deploy the ESB behind a proxy server using Apache mod_proxy. +In such deployments you need to specify the HTTP proxy port in the axis2.xml file's HTTP/HTTPS receiver +configurations using the following parameter. +

+ +
+<parameter name="proxyPort">80</parameter>
+
+ +

+Please refer the WSO2 Carbon Transports Catalog for more information on setting up HTTP and HTTPS NIO transports +and the servlet HTTPS transport for various deployments. +

+ +

Performance Tuning WSO2 ESB

+

+We recommend that you install WSO2 ESB on Unix/Linux systems for production deployments. This section, for +the most part, assumes that you have setup the ESB on a server running Unix/Linux. Also keep in mind that +you should not take performance tuning steps described here lightly. Performance tuning requires you to modify +some important system files which would effect all the programs running on the server. Hence care must be +applied and please refer Unix/Linux documentation for more details on the configuration files described here. +

+

+To optimize the network performance and OS performance for the ESB you will have to modify the /etc/sysctl.conf +file. We recommend specifying the following entries in this file. +

+ +
+net.ipv4.tcp_fin_timeout = 30
+fs.file-max = 2097152
+net.ipv4.tcp_tw_recycle = 1
+net.ipv4.tcp_tw_reuse = 1
+net.core.rmem_default = 524288
+net.core.wmem_default = 524288
+net.core.rmem_max = 67108864
+net.core.wmem_max = 67108864
+net.ipv4.tcp_rmem = 4096 87380 16777216
+net.ipv4.tcp_wmem = 4096 65536 16777216
+
+ +

+These settings specify a larger port range, a more effective TCP connection timeout value and a number of +other important parameters at the system level. +

+

+Also you may specify the following entries in the /etc/security/limits.conf file to alter the number of allowed +open files for system users. +

+ +
+* soft nofile 4096
+* hard nofile 65535
+
+ +

+You can tune up the HTTP-NIO transport performance by creating a nhhtp.properties file for the ESB. This +configuration file should be placed in the ESB_HOME/lib/core/WEB-INF/classes directory. You can change the +socket timeout values, connection timeout values and HTTP receiver thread pool parameters by specifying them +in the nhttp.properties file. A sample set of values that can be included in the nhttp.properties file is +specified below. +

+ +
+http.socket.timeout=60000
+http.socket.buffer-size=8192
+http.tcp.nodelay=1
+http.connection.stalecheck=0
+
+# 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
+
+ +

+When the nhttp.properties file is not provided a set of default values will be used to initialize the +thread pool of the HTTP-NIO transports. However the default values (mentioned in the above example) are +suitable for most deployments and it is recommended to leave them unchanged without overriding the values +using a nhttp.properties configuration file. +

+ + diff --git a/docs/xdoc/configuration_language.xml b/docs/xdoc/configuration_language.xml new file mode 100644 index 0000000000..27f56f3a5e --- /dev/null +++ b/docs/xdoc/configuration_language.xml @@ -0,0 +1,1987 @@ + + + + + + + WSO2 ESB - Configuration Language + + + + + + + [ Documentation Index ] +

+ WSO2 Enterprise Service Bus (ESB) Configuration +

+

Contents

+

+

+

+ + +

Overview

+

The mediation engine of WSO2 ESB is driven off a set of XML configuration files. +This allows the mediation configuration to be easily +hand edited, backed up from the file system, or even included into version +control for easier management and administration (e.g. moving a configuration from +development, through QA, staging and into production). The configuration files +that drives the mediation engine are stored in the ESB_HOME/repository/conf/synapse-config +directory. These configuration files are written using the Synapse configuration language +which is a simple and easy to learn domain specific language based on XML.

+ +

It is always recommended to use the graphical wizards and tools provided in the +WSO2 ESB management console to setup the mediation configuration, thus avoiding having to +write XML configurations manually. The ESB management console offers a rich set of tools +that allows you to build mediation configurations easily without writing a single line of XML. +However it is helpful to have a basic understanding +on the Synapse configuration language as well as on how the mediation configuration is +physically stored on the disk. A decent knowledge on the Synapse configuration language +will enable you to develop efficient and concise mediation configurations. Understanding +how the files are stored will allow you to use third party tools and scripts for configuration +management activities.

+ +

This guide walks you through the Synapse configuration language and how various +configuration files are stored under the synapse-config directory of the ESB. It starts +off with a breif introduction to the high level concepts associated with mediation and then +explores into how such concepts can be implemented using the Synapse configuration +language in WSO2 ESB.

+ +

The Mediation Engine and Modes of Operation

+

As the diagram below depicts, the mediation engine consists of Proxy +services, Endpoints, Sequences and Startup jobs managed by the ESB. It +also contains the interface to the Registry/Repository being used by the mediation engine. +Items like sequences, endpoints and proxy services could be made to +reference different configuration elements that +are served through the Registry. When using the Registry to hold +pieces of the configuration, certain elements such as endpoint definitions, +sequences and local entries could be updated dynamically while the ESB +is executing, and the Registry could trigger a re-load as configured.

+ +

Synapse message flow

+ +

Typically the ESB is deployed between the actual client and a backend +service implementation to mediate the message flow in between. Thus WSO2 +ESB can accept a message on behalf of the actual service, perform +authentication, validation, transformation, logging, routing based on the +content etc. and then decide the destination target endpoint for the message +and direct it to an actual service implementation. The ESB can also +detect timeouts, transport failures during communication or introduce load +balancing, throttling or caching where necessary. For fault scenarios such as +authentication failure, or schema validation failure, the WSO2 ESB can be +configured to return a custom message or a SOAP fault to the requesting client +without forwarding the request to the actual service.

+ +

WSO2 ESB can operate in four modes of operation:

+ +

Service mediation (Proxy services)

+ +

In Service mediation, the ESB exposes a service endpoint on the ESB, +that accepts messages from clients. Typically these services acts as proxies +for existing (external) services, and the role of the ESB would be to "mediate" +these messages before they are proxied to the actual service. In this mode, +WSO2 ESB could expose a service already available in one transport, over a +different transport; or expose a service that uses one schema or WSDL as a +service that uses a different schema or WSDL etc. A Proxy service could define +the transports over which the service is exposed, and point to the mediation +sequences that should be used to process request and response messages through +the proxy service. A proxy service maybe a SOAP or REST/POX service over http/s +or SOAP, POX, Plain Text or Binary / Legacy service for other transports such +as JMS and VFS file systems - e.g. CSV content being the payload

+ +

Message mediation (Sequences)

+ +

In Message mediation, WSO2 ESB can act as a transparent proxy for clients - +if they are directed to point to WSO2 ESB as a http proxy. This way, +WSO2 ESB could be configured to filter all messages on a network for logging, +access control etc, and could "mediate" messages without the explicit knowledge +of the original client. If the ESB receives a message that is not accepted by +any proxy service, this message is handled through message mediation as well. +Message mediation always processes messages according to the mediation sequence +defined as "main".

+ +

Task Scheduling (Startup jobs)

+

With the task scheduling capabilities of WSO2 ESB, one or more tasks can be +configured to execute in a periodic manner in the ESB runtime. Tasks are +custom developed Java code which are deployed into the ESB by the user. Tasks +could be written to inject messages into the service bus periodically, poll +databases and message queues, cleanup the environment and ping backend services +to check availability.

+ +

Eventing (Event Sources)

+

With event sources and the event publisher mediator, WSO2 ESB can act as an +event broker. It can receive and manage subscription requests from client applications +and then dispatch events to the subscribers based on a pre configured criteria. +Also if required events can be mediated through sequences before delivering them +to the subscribers. The subscription manager implementation is pluggable and WSO2 +ESB ships with a registry based subscription manager and an in memory subscription +manager.

+ +

Concepts and Configuration Elements

+

The following section explaing the high level concepts associated with the WSO2 +ESB mediation engine and how they map to various configuration elements in the ESB +configuration. It is very important to understand these high level concepts regardless +of how you are planning to develop mediation configuration. Even if you are using +the graphical tools to develop configuration it is still necessary to understand these +concepts.

+ +

Mediators and Mediation +Sequences

+ +

WSO2 ESB defines a 'mediator' as a component that performs some +mediation action on a message during the process flow. Thus a mediator gets +full access to a message at the point where it is defined to gain control, and +could inspect the message, modify it or take an external action depending on +some attributes or values of the current message. A mediation sequence, +commonly called a 'sequence' is a list of such mediators. A sequence may be +named for re-use, or defined in-line or anonymously within a configuration. +Sequences may be defined within the synapse.xml configuration or within the +Registry. Writing a custom mediator in Java is easy and the supplementary +documentation provides more details on this. The 'Class' and 'POJO (command)" +mediators allows one to plugin a Java class easily into the mediation engine with +minimal effort. In addition, the Script mediator allows one to provide an +Apache BSF script (e.g. Javascript, Ruby, Groovy etc) for mediation.

+ +

A mediation configuration holds two special sequences named "main" and +"fault". These may be defined within the synapse.xml, or externally via the +Registry. If either is not found, a suitable default is generated at runtime by +the ESB. The default "main" sequence will simply send a message without +mediation, while the default "fault" sequence would log the message including +the payload and any error/exception encountered and stop further processing. +The 'fault' sequence executes whenever WSO2 ESB itself encounters an error while +processing a message - or when a fault handler has not been defined to handle +exceptions. A sequence can assign another named sequence as its "fault" handler +sequence, and control branches to the fault handler if an error is encountered +during the execution of the initial sequence.

+ +

Endpoints

+ +

An Endpoint definition within the mediation configuration defines an external service endpoint +and any attributes or semantics that should be followed when communicating with +that endpoint. An endpoint definition can be named for re-use, or defined +in-line or anonymously within a configuration. Typically an endpoint would be +based on a service Address or a WSDL. Additionally WSO2 ESB supports +Failover and Load-balance endpoints - which are defined over a group of +endpoints. Endpoints may be defined within the synapse-config configuration or +within the Registry.

+ +

Proxy Services

+ +

A proxy service is a virtual services hosted in the ESB runtime. For a service client it +appears to be a real Web Service which accepts service requests. The proxy service mediates +any accepted requests and forwards them to a specified endpoint, most of the time to an +actual Web Service. The responses coming back from the target endpoint are mediated back to +the client which sent the original service request. Proxy services often make references to +sequences, endpoints and local entries. A proxy service can enforce various QoS requirements +on a request and can be exposed over a user specified transport. Therefore they are often used +to expose existing Web Services over a different transport or a QoS configuration. For an +example a proxy service can be used to expose an HTTP service over JMS or it can be used to +expose an unsecured service in a secured manner using WS-Security standards.

+ +

Unlike sequences and endpoints which can be stored and loaded from the registry, proxy +services cannot be loaded from the registry. However a proxy service can make references +to sequences and endpoints stored in the registry.

+ +

Tasks

+ +

A Task is a custom Java class that implements the +org.apache.synapse.startup.Task interface that defines a single "public void +execute()" method. Such a task can be scheduled and managed via the +ESB. The scheduling information for a task can be specified in the cron format +or a simple format by the user. A task may also be specified as a one-time task +where required, and can be used to trigger a callout or inject a message into +the ESB.

+ +

Remote Registry and Local Registry (Local Entries)

+ +

A mediation configuration can refer to an external Registry / Repository for +resources used such as WSDL's, Schemas, Scripts, XSLT or XQuery transformations +etc. One or more remote registries may be hidden or merged behind a local +Registry interface defined to a Synapse configuration. Resources from an +external registry are looked up using "keys" - which are known to the external +registry. WSO2 ESB ships with a simple URL based registry implementation +that uses the file system for storage of resources, and URL's or fragments as +"keys".

+ +

A Registry may define a duration for which a resource served may be cached +by the ESB runtime. If such a duration is specified, WSO2 ESB is +capable of refreshing the resource after cache expiry to support dynamic +re-loading of resource at runtime. Optionally, a configuration could define +certain "keys" to map to locally defined entities. These entities may refer to +a source URL or file, or defined as in-line XML or text within the +configuration itself. If a Registry contains a resource whose "key" matches the +key of a locally defined entry, the local entry shadows the resource available +in the Registry. Thus it is possible to override Registry resources locally +from within a configuration. To integrate WSO2 ESB with a custom / new Registry +or repository, one needs to implement the org.apache.synapse.registry.Registry +interface to suit the actual Registry being used.

+ +

Event Sources

+

An event source is used to define the event source and the subscription manager +configuration used in the eventing implementation of WSO2 ESB. An event source provides +a service URL that can be used to the send subscriptions and events (events that are +not required to go through a mediation flow). +

+ +

Priority Executors

+

Prioriy executors can be used to execute sequences with a given priority. Priority executors are + used in high load scenarios where user wants to execute differrent sequences with different + priorities. This allows user to control the resources allocated to executing sequences and + prevent high priority messages from getting delayed and dropped. A priority has a valid meaning + comparing to other priorities specified. For example if we have two priorities with value 10 + and 1, message with priority 10 will get 10 times more resources than messages with priority 1. +

+ +

The Contents of the synapse-config Directory

+ +

The synapse-config directory which houses the mediation configuration (Synapse configuration) +of WSO2 ESB contains several files and subdirectories. Usually the following set of child +directories are available in the synapse-config directory.

+ +
    +
  • endpoints
  • +
  • event-sources
  • +
  • local-entries
  • +
  • priority-executors
  • +
  • proxy-services
  • +
  • sequences
  • +
  • tasks
  • +
+ +

Each of the above subdirectories can house multiple XML configuration files that define +specific configuration elements of the Synapse configuration. For an example the 'endpoints' +subdirectory can house zero or more XML files that contain endpoint configurations.

+ +

Inaddition to the above mentioned subdirectories, there can be files named synapse.xml and +registry.xml at the top level of the synapse-config directory. The registry.xml contains +the registry definition for the ESB. The synapse.xml can contain any type of configuration +elements wrapped in a top level <definitions> element. This file is mainly there for backward +compatibility reasons. Older versions of WSO2 ESB had only a single flat XML file named synapse.xml +to load the entire Synapse configuration from. The synapse.xml file in the synapse-config directory +resembles this flat configuration file so that a user could easily port an old configuration +to a new ESB distribution. Basically a user can get the content of the old synapse.xml file and +put it in the synapse-config/synapse.xml file.

+ +

A Synapse configuration looks like the following at the top level synapse.xml file:

+
 <definitions>
+   <registry provider="string">...</registry>?
+   <localEntry key="string">...</localEntry>?
+   <sequence name="string">...</sequence>?
+   <endpoint name="string">...</endpoint>?
+   <proxy name="string" ...>...</proxy>?
+   <task name="string" ...>...</task>?
+   <eventSource name="string" ...>...</eventSource>?
+   <priorityExecutor name="string" ...>...</priorityExecutor>? 
+   mediator*
+ </definitions>
+ +

The <definitions> elements in the synapse.xml holds the ESB +configuration. While the <registry>, <sequence>, <endpoint>, +<proxy>, <task> and <localEntry> elements refer to those +discussed above, the built-in mediator elements names are already registered +with the Synapse engine. Custom mediators written by a user may be included +into the library directory, and would be dynamically picked up in a Sun JDK +environment. A list of mediators found directly as children under the +<definitions> element would be treated as the "main" sequence, if a named +sequence with the name "main" cannot be found.

+ +

Registry

+ +

The <registry> element is used to define the remote registry used by +the configuration. The registry provider specifies an implementation class for +the registry implementation used, and optionally a number of configuration +parameters as may be required for the configuration of the connection to the +registry.

+
 <registry provider="string"/>
+   <parameter name="string">text | xml</parameter>*
+ </registry>
+ +

Registry entries loaded from a remote registry may be cached as dictated by +the registry, and reloaded after the cache periods expires if a newer version +is found. Hence it is possible to define configuration elements such as +(dynamic) sequences and endpoints, as well as resources such as XSLT's, Scripts +or XSDs off the registry, and update the configuration as these are allowed to +dynamically change over time.

+ +

WSO2 ESB ships with a built-in file system based registry implementation called the +"FileSystemRegistry" and this can be configured as follows:

+
e.g.
+<registry provider="org.wso2.carbon.mediation.registry.ESBRegistry">
+  <parameter name="root">file:./repository/samples/resources/</parameter>
+  <parameter name="cachableDuration">15000</parameter>
+</registry>
+ +

The "root" parameter specifies the root directory of the Registry for loaded +resources. The FileSystemBasedRegistry keys are path fragments, that when combined +with the root prefix would form the full URL for the referenced resource. The +"cachableDuration" parameter specifies the number of milliseconds for which +resources loaded from the Registry should be cached. More advanced registry +implementations allows different cachable durations to be specified for +different resources, or mark some resources as never expires. By default WSO2 ESB +uses the WSO2 Governance Registry for storing resources. It is configured as +follows:

+
e.g.
+<registry provider="org.wso2.carbon.mediation.registry.WSO2Registry">
+  <parameter name="cachableDuration">15000</parameter>
+</registry>
+ +

By default you will find the above bit of configuration in the top level +registry.xml file in the synapse-config directory.

+ +

Local Registry / Local Entries

+ +

The <localEntry> element is used to declare registry entries that are +local to the ESB instance, as shown below

+
  <localEntry key="string" [src="url"]>text | xml</localEntry>
+ +

These entries are top level entries which are globally visible within the +entire system. Values of these entries can be retrieved via the extension XPath +function "synapse:get-property(prop-name)" and the keys of these entries could +be specified wherever a registry key is expected within the configuration.

+ +

An entry can be static text specified as inline text or static XML specified +as an inline XML fragment or specified as a URL (using the src attribute). A +local entry shadows any entry with the same name from a remote Registry.

+
e.g.
+<localEntry key="version">0.1</localEntry>
+<localEntry key="validate_schema">
+        <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+         ...
+        </xs:schema>
+    </localEntry>
+<localEntry key="xslt-key-req" src="file:repository/samples/resources/transform/transform.xslt"/>
+ +

Local entries can be defined in the top level synapse.xml file or in the +synapse-config/local-entries directory.

+ +

Sequences

+ +

A <sequence> element is used to define a sequence of mediators that +can be invoked later by name. The sequences named "main" and "fault" has +special significance in a Synapse configuration. The "main" sequence handles +any message that is accepted for 'Message +Mediation', and the "fault" sequence is invoked if Synapse encounters a +fault, and a custom fault handler is not specified for the sequence via its +"onError" attribute. If the "main" or "fault" sequences are not defined locally +or not found in the Registry, the Synapse ESB defines suitable defaults at +initialization.

+ +

A Dynamic Sequence may be defined by specifying a key reference to a +registry entry. As the remote registry entry changes, the sequence will +dynamically be updated according to the specified cache duration and +expiration. If tracing is enabled on a sequence, all messages being processed +through the sequence would write tracing information through each mediation +step to the trace.log file configured via the log4j.properties configuration. +Setting the trace log level to TRACE would additionally dump the message and +detailed trace information at each mediation step. A tracing enabled sequence +propagates this setting to invoked sub-sequences.

+
 <sequence name="string" [onError="string"] [key="string"] [trace="enable"]>
+   mediator*
+ </sequence>
+
e.g.
+<sequence name="main" onError="errorHandler">
+  .. <!-- a 'main' sequence that invokes the sequence named 'errorHandler' on a fault --> ..
+</sequence>
+
<sequence key="sequence/dynamic_seq_1.xml"/>
+where "sequence/dynamic_seq_1.xml" refers to the following sequence definition from the registry:
+
+<sequence name="dynamic_sequence" xmlns="http://ws.apache.org/ns/synapse">
+  ..
+</sequence>
+ +

Sequences can be defined in the top level synapse.xml file or in the +synapse-config/sequences directory. The default main sequence and the fault +sequence that ships with WSO2 ESB can be found in the sequences directory +in two files named main.xml and fault.xml respectively.

+ +

Endpoints

+ +

Endpoints can be defined in the top level synapse.xml file or in the +synapse-config/endpoints directory.

+ +

An <endpoint> element defines a destination for an outgoing message. +An endpoint may be specified as an address endpoint, WSDL based endpoint, a +load balancing endpoint or a fail-over endpoint as follows:

+
<endpoint [name="string"] [key="string"] [key-expression="string"]>
+  address-endpoint | default-endpoint | wsdl-endpoint | load-balanced-endpoint | fail-over-endpoint
+</endpoint> 
+ +

All above endpoint types can have a name attribute, and such named endpoints +can be reffered by other endpoints, through the key attribute. For example if +there is an endpoint named as "foo", the following endpoint can be used in any +place, where "foo" has to be used.

+
<endpoint key="foo"/>
+ +

The "trace" attribute turns on detailed trace information for messages being +sent to the endpoint. These are available in the trace.log configured via the +log4j.properties file. Setting the trace log level to TRACE will dump detailed +trace information including message payloads.

+ +

Address Endpoint

+ +

Address endpoint is an endpoint defined by specifying the EPR and other +attributes of the endpoint directly in the configuration. The 'uri' attribute +of the address element contains the EPR of the target endpoint. Message format +for the endpoint and the method to optimize attachments can be specified in the +format and optimize attributes respectively. Reliable messaging and security +policies for the endpoint can be specified in the policy attribute of the +enableRM and enableSec elements respectively. WS-Addressing can be engaged for +the messaging going to the endpoint by the enableAddressing element. +suspendDurationOnFailure attribute specifies the time duration in seconds to +suspend this endpoint, if it is detected as failed. If this attribute is not +specified, endpoint will never be recovered after a failure.

+ +

Address endpoints can timeout if responses fail to arrive at Synapse by a +predefined timeout-duration specified in seconds. The timeout action specifies +whether to discard responses that arrives late, or to trigger a fault. Synapse +has a periodic timeout handler that triggers itself at each 15 second interval. +Thus endpoint timeouts will have a +/- error on actual trigger time. Though +this can be minimized by setting a System property +"synapse.timeout_handler_interval" to a millisecond duration below the desired +endpoint timeout, care must be taken as a lesser value may have a higher +overhead on the system.

+ +

An endpoint that fails may be suspended for a specified duration after such +a failure, during which new messages will not be processed through the +endpoint. The 'suspendDurationOnFailure' could specify an optional value in +seconds for which this endpoint should be suspended.

+ +

QoS aspects such as WS-RM and WS-Security and WS-Addressing may be enabled +on messages sent to an endpoint using the enableRM, enableSec and +enableAddressing elements. Optionally, the WS-RM and WS-Security policies could +be specified using the 'policy' attributes.

+
<address uri="endpoint address" [format="soap11|soap12|pox|get"] [optimize="mtom|swa"]
+         [encoding="charset encoding"]
+         [statistics="enable|disable"] [trace="enable|disable"]>
+  <enableRM [policy="key"]/>?
+  <enableSec [policy="key"]/>?
+  <enableAddressing [version="final|submission"] [separateListener="true|false"]/>?
+
+  <timeout>
+    <duration>timeout duration in milliseconds</duration>
+    <action>discard|fault</action>
+  </timeout>?
+
+  <suspendDurationOnFailure>
+    suspend duration in seconds
+  </suspendDurationOnFailure>?
+
+  <markForSuspension>
+    [<errorCodes>xxx,yyy</errorCodes>]
+    <retriesBeforeSuspension>m</retriesBeforeSuspension>
+    <retryDelay>d</retryDelay>
+  </markForSuspension>
+
+  <suspendOnFailure>
+    [<errorCodes>xxx,yyy</errorCodes>]
+    <initialDuration>n</initialDuration>
+    <progressionFactor>r</progressionFactor>
+    <maximumDuration>l</maximumDuration>
+  </suspendOnFailure>
+
+</address>
+ +

Following are some sample address URI definitions.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TransportSample address
HTTPhttp://localhost:9000/soap/SimpleStockQuoteService
JMSjms:/SimpleStockQuoteService?
+    transport.jms.ConnectionFactoryJNDIName=QueueConnectionFactory&
+    java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&
+    java.naming.provider.url=tcp://localhost:61616&
+    transport.jms.DestinationType=topic
Mailmailto:guest@host
VFSvfs:file:///home/user/directory
vfs:file:///home/user/file
vfs:ftp://guest:guest@localhost/directory?vfs.passive=true
FIXfix://localhost:9876?BeginString=4.4&SenderCompID=SYNAPSE&TargetCompID=EXEC
+ +

Default Endpoint

+ +

Default endpoint is an endpoint defined for adding QoS and other +configurations to the endpoint which is resolved from the 'To' address of the +message context. All the configurations such as message format for the +endpoint, the method to optimize attachments, reliable messaging, security +policies for the endpoint can be specified as in the Address Endpoint. This +endpoint differs from the address endpoint only in the uri attribute which will +not be present in this endpoint. Following section describes the configuration +of a default endpoint

+
<default [format="soap11|soap12|pox|get"] [optimize="mtom|swa"]
+         [encoding="charset encoding"]
+         [statistics="enable|disable"] [trace="enable|disable"]>
+  <enableRM [policy="key"]/>?
+  <enableSec [policy="key"]/>?
+  <enableAddressing [version="final|submission"] [separateListener="true|false"]/>?
+
+  <timeout>
+    <duration>timeout duration in milliseconds</duration>
+    <action>discard|fault</action>
+  </timeout>?
+
+  <suspendDurationOnFailure>
+    suspend duration in seconds
+  </suspendDurationOnFailure>?
+</default>
+ +

WSDL Endpoint

+ +

WSDL endpoint is an endpoint definition based on a specified WSDL document. +The WSDL document can be specified either as a URI or as an inlined definition +within the configuration. The service and port name containing the target EPR +has to be specified with the 'service' and 'port' (or 'endpoint') attributes +respectively. enableRM, enableSec, enableAddressing, suspendDurationOnFailure +and timeout elements are same as for an Address endpoint.

+
<wsdl [uri="wsdl-uri"] service="qname" port/endpoint="qname">
+  <wsdl:definition>...</wsdl:definition>?
+  <wsdl20:description>...</wsdl20:description>?
+  <enableRM [policy="key"]/>?
+  <enableSec [policy="key"]/>?
+  <enableAddressing/>?
+  <suspendDurationOnFailure>suspend-duration</suspendDurationOnFailure>?
+
+  <markForSuspension>
+    [<errorCodes>xxx,yyy</errorCodes>]
+    <retriesBeforeSuspension>m</retriesBeforeSuspension>
+    <retryDelay>d</retryDelay>
+  </markForSuspension>
+
+  <suspendOnFailure>
+    [<errorCodes>xxx,yyy</errorCodes>]
+    <initialDuration>n</initialDuration>
+    <progressionFactor>r</progressionFactor>
+    <maximumDuration>l</maximumDuration>
+  </suspendOnFailure>
+
+  <timeout>
+    <duration>timeout-duration</duration>
+    <action>discard|fault</action>
+  </timeout>?
+</wsdl>
+ +

Load balanced Endpoint

+ +

A Load balanced endpoint distributes the messages (load) arriving at it +among a set of listed endpoints by evaluating the load balancing policy and any +other relevant parameters. Policy attribute of the load balance element +specifies the load balance policy (algorithm) to be used for selecting the +target endpoint. Currently only the roundRobin policy is supported. failover +attribute determines if the next endpoint should be selected once the currently +selected endpoint has failed, and defaults to true. The set of endpoints among +which the load is distributed can be listed under the 'loadBalance' element. +Those endpoints can belong to any endpoint type mentioned in this document. For +example, failover endpoints can be listed inside the load balance endpoint to +load balance between failover groups etc.

+ +

The optional 'session' element makes the endpoint a session affinity based +load balancing endpoint. If it is specified, sessions are bound to endpoints in +the first message and all successive messages for those sessions are directed +to their associated endpoints. Currently there are two types of sessions +supported in SAL endpoints. Namely HTTP transport based session which +identifies the sessions based on http cookies and the client session which +identifies the session by looking at a SOAP header sent by the client with the +QName '{http://ws.apache.org/ns/synapse}ClientID'. The 'failover' attribute +mentioned above is not applicable for session affinity based endpoints and it +is always considered as set to false. If it is required to have failover +behavior in session affinity based load balance endpoints, list failover +endpoints as the target endpoints.

+
<session type="http|simpleClientSession"/>?
+<loadBalance [policy="roundRobin"] [failover="true|false"]>
+  <endpoint .../>+
+</loadBalance>
+ +

Failover Endpoint

+ +

Failover endpoints send messages to the listed endpoints with the following +failover behavior. At the start, the first listed endpoint is selected as the +primary and all other endpoints are treated as backups. Incoming messages are +always sent only to the primary endpoint. If the primary endpoint fails, next +active endpoint is selected as the primary and failed endpoint is marked as +inactive. Thus it sends messages successfully as long as there is at least one +active endpoint among the listed endpoints.

+
<failover>
+  <endpoint .../>+
+</failover>
+ +

Indirect Endpoint

+

Indirect Endpoint refers an actual endpoint by a key. This endpoint fetches + the actual endpoint at runtime. Then it delegates the message sending to + the actual endpoint. When Endpoints are stored in the registry and referred, + this endpoint can be used. The key is a static value for this endpoint.

+
<endpoint key="" name="" />
+ +

Resolving Endpoint

+

Resolving Endpoint refers an actual endpoint using a dynamickey. The key is a XPath expression. + The XPath is evaluated against the current message and key is calculated at run time. Then resolving endpoint fetches + the actual endpoint using the calculated key. Then it delegates the message sending to + the actual endpoint. When Endpoints are stored in the registry and referred, + this endpoint can be used.

+
<endpoint name="" key-expression="" />
+ +

Proxy Services

+ +

A <proxy> element is used to define a Synapse Proxy service.

+
 <proxy name="string" [transports="(http |https |jms |.. )+|all"] [pinnedServers="(serverName )+"]>
+   <description>...</description>?
+   <target [inSequence="name"] [outSequence="name"] [faultSequence="name"] [endpoint="name"]>
+      <inSequence>...</inSequence>?
+      <outSequence>...</outSequence>?
+      <faultSequence>...</faultSequence>?
+      <endpoint>...</endpoint>?
+   </target>?
+   <publishWSDL key="string" uri="string">
+      ( <wsdl:definition>...</wsdl:definition> | <wsdl20:description>...</wsdl20:description> )?
+      <resource location="..." key="..."/>*
+   </publishWSDL>?
+   <parameter name="string">                 // optional service parameters such as (e.g. transport.jms.ConnectionFactory)
+      string | xml
+   </parameter>
+ </proxy>
+ +

A proxy service is created and exposed on the specified transports through +the underlying Axis2 engine, exposing service EPR's as per the standard Axis2 +conventions - based on the service name. (Note: that currently Axis2 does not +allow custom URI's to be set for services on some transports such as http/s) +The Proxy service could be exposed over all enabled Axis2 transports such as +http, https, JMS, Mail and File etc. or on a subset of these as specified with +the optional 'transports' attribute.

+ +

You can give a list of Synapse server names where this proxy service should +be deployed using 'pinnedServers' attribute. It takes the server names +separated by comma or space character. If there is no pinned server list then +proxy service will be started in all server instances. If a pinned server names +list is given it will only start in the given named Synapse server instances. +The Synapse server name is picked up either from the system property +'SynapseServerName' or through the axis2.xml parameter 'SynapseConfig.ServerName', +failing which the hostname of the machine would be used or +default to 'localhost'. You can give a name to a Synapse server instance by +specifiying -DSynapseServerName=<ServerName> property when you execute +the startup script, i.e. wso2server.bat or wso2server.sh. You can also edit the +wrapper.conf to do this where Synapse is started as a service.

+ +

Each service could define the target for received messages as a named +sequence or a direct endpoint. Target inSequence or endpoint is required for +the proxy configuration, and a target outSequence defines how responses should +be handled. Any supplied WS-Policies would apply as service level policies, and +any service parameters could be passed into the proxy services' AxisService +instance using the parameter elements (e.g. the JMS destination etc). If the +proxy service should enable WS-Reliable Messaging or Security, the appropriate +modules could be engaged, and specified service level policies will apply.

+ +

A Dynamic Proxy may be defined by specifying the properties of the proxy as +dynamic entries by refering them with the key. (For example one could specify +the inSequence or endpoint with a remote key, without defining it in the local +configuration) As the remote registry entry changes, the properties of the +proxy will dynamically be updated accordingly. (Note: proxy service definition +itself can not be specified to be dynamic; i.e <proxy key="string"/> is +wrong)

+ +

A WSDL for the proxy service can be published using the <publishWSDL> +element. The WSDL document can be loaded from the registry by specifying the +'key' attribute or from any other location by specifying the 'uri' attribute. +Alternatively the WSDL can be provided inline as a child element of +<publishWSDL>. Artifacts (schemas or other WSDL documents) imported by +the WSDL can be resolved from the registry by specifying appropriate +<resource> elements:

+
 <publishWSDL key="my.wsdl">
+   <resource location="http://www.standards.org/standard.wsdl" key="standard.wsdl"/>
+ </publishWSDL>
+ +

In this example the WSDL is retrieved from the registry using the key +'my.wsdl'. It imports another WSDL from location +'http://www.standards.org/standard.wsdl'. Instead of loading it from this +location, Synapse will retrieve the imported WSDL from the registry entry +'standard.wsdl'.

+ +

You can give the following as service parameters:

+ + + + + + + + + + + + + + + + + + + + + + + +
Parameter Value Default Description
useOriginalwsdl true|false false Use the given WSDL instead of generating the WSDL.
modifyUserWSDLPortAddress true|false true (Effective only with useOriginalwsdl=true) If true (default) modify + the port addresses to current host.
+ +

Transport specific parameters that may be set as service parameters:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Transport Require Parameter Description
JMS Optional transport.jms.ConnectionFactory The JMS connection factory definition (from axis2.xml) to be used to + listen for messages for this service
Optional transport.jms.Destination The JMS destination name (Defaults to the service name)
Optional transport.jms.DestinationType The JMS destination type. Accept values 'queue' or 'topic'
Optional transport.jms.ReplyDestination The destination where a reply will be posted
Optional transport.jms.Wrapper The wrapper element for the JMS message
VFS Required transport.vfs.FileURI The primary File (or Directory) URI in the vfs* transport format, for + this service
Required transport.vfs.ContentType The expected content type for files retrieved for this service. The + VFS transport uses this information to select the appropriate message + builder.
+ Examples: +
    +
  • text/xml for plain XML or SOAP
  • +
  • text/plain; charset=ISO-8859-1 for text files
  • +
  • application/octet-stream for binary data
  • +
+
Optional transport.vfs.FileNamePattern A file name regex pattern to match files against a directory + specified by the FileURI
Optional transport.PollInterval The poll interval (in seconds)
Optional transport.vfs.ActionAfterProcess DELETE or MOVE
Optional transport.vfs.MoveAfterProcess The directory to move files after processing (i.e. all files process + successfully)
Optional transport.vfs.ActionAfterErrors DELETE or MOVE
Optional transport.vfs.MoveAfterErrors The directory to move files after errors (i.e. some of the files + succeed but some fail)
Optional transport.vfs.ActionAfterFailure DELETE or MOVE
Optional transport.vfs.MoveAfterFailure The directory to move after failure (i.e. all files fail)
Optional transport.vfs.ReplyFileURI Reply file URI
Optional transport.vfs.ReplyFileName Reply file name (defaults to response.xml)
Optional transport.vfs.MoveTimestampFormat Timestamp prefix format for processed file name. + java.text.SimpleDateFormat compatible string. e.g. yyMMddHHmmss'-'
+ +

VFS Transport URI examples (See http://commons.apache.org/vfs/filesystems.html +for more samples)

+
file:///directory/filename.ext
+file:////somehost/someshare/afile.txt
+jar:../lib/classes.jar!/META-INF/manifest.mf
+jar:zip:outer.zip!/nested.jar!/somedir
+ftp://myusername:mypassword@somehost/pub/downloads/somefile.tgz[?vfs.passive=true]
+ +

Tasks

+ +

A <task> element is used to define a Synapse Startup Task.

+ +
 <task class="mypackage.MyTask" name="string" [pinnedServers="(serverName)+"]>
+   <property name="stringProp" value="String"/>
+   <property name="xmlProp">
+     <somexml>config</somexml>
+   </property>
+   <trigger ([[count="10"]? interval="1000"] | [cron="0 * 1 * * ?"] | [once=(true | false)])/>
+ </task>
+ +

A task is created and scheduled to run at specified time intervals or as +specified by the cron expression. The Task class specifies the actual task +implementation class (which must implement org.apache.synapse.startup.Task +interface) to be executed at the specified interval/s, and name specifies an +identifier for the scheduled task.

+ +

Fields in the task class can be set using properties provided as string +literals or as XML fragments. (For example; if the task implementation class +has a field named "version" with a corresponding setter method, the +configuration value which will be assigned to this field before running the +task can be specified using a property with the name 'version')

+ +

There are three different trigger mechanisms to schedule tasks. A simple +trigger is specified specifying a 'count' and an 'interval', implying that the +task will run a 'count' number of times at specified intervals. A trigger may +also be specified as a cron trigger using a cron expression. A one-time trigger +is specified using the 'once' attribute as true in the definition and could be +specified as true in which case this task will be executed only once just after +the initialization of Synapse

+ +

You can give a list of Synapse server names where this task should be +started using pinnedServers attribute. Refer to the explanation of this +attribute under proxy services for more information.

+ +

Event Sources

+

+A <eventSource> element is used to define an event source. +

+
<eventSource name="string">
+        <subscriptionManager class="my.package.MyClass">
+                   <parameter name="string"/>
+        </subscriptionManager>
+</eventSource>
+

+An event source is required to implement eventing in WSO2 ESB. Event sources are +used to inject subscription messages into the ESB and provide a service URL for the +users to send subscription requests. User can send messages to manage the subscriptions +(unsubscribe, renew, get-status) in the event source as well. +

+

+Subscription manager configured inside the event source will be responsible for +keeping track of the subscriptions, and provide operations to manage the +subscriptions. Subscription storage will be decided based on the implementation of +the subscription manager , e.g. Registry, memory, database. Additional information +required to setup the subscription manager can be set as parameters. +

+ +

Priority Executors

+

Below is the Priority Executor Configuration

+
<priority-executor name="priority-executor">
+    <queues isFixed="true|false" nextQueue="class implementing NextQueueAlgorithm">
+        <queue [size="size of the queue"] priority="priority of the messages put in to this queue"/>*
+    </queues>
+    <threads core="core number of threads" max="max number of threads' keep-alive="keep alive time"/>
+</priority-executor>
+

+ An executor is a Thread Pool Executor with separate queues for different priorities. +

+

+ The queues can have a fixed depths or they can have un-bounded capacities. This is controlled by + the isFixed attribute. +

+

+ An executor should have at least two or more queues. If only one queue is used there is no + point in using a priority executor. It only adds some overhead. +

+

+ A Queue can have a size and a priority. If the queues has unlimited length, no more than + core threads will be used. +

+

+ A Priority Executor has a core number of threads. When ESB is started with the priority + executor, this number of threads will be created. Max is the maximum number of threads this + executor will have. If the number of threads in the executor exceeds the core threads, they + will be in active for the keep-alive time only. After the keep-alive time those threads will + be be removed from the system. +

+ + +

Mediators

+ +

A mediator token refers to any of the following tokens:

+
send | drop | log | property | sequence | validate | fault | callout | xslt | header | filter | switch | in | out | router
+    | dblookup | dbreport | RMSequence | throttle | xquery | cache | clone | iterate | aggregate | class | pojoCommand | script | spring
+    | event | entitlement | OAuth | transaction | smooks
+ +

In addition to the above, Synapse will be able to load custom mediators via +the J2SE Service Provider model. Mediator extensions must implement the +MediatorFactory interface. The Class and POJO Command mediators allow custom +Java code to be easily invoked during mediation, while the Script mediator +allows Apache BSF scripts such as Javascript, Ruby, Groovy etc to be used for +mediation.

+ +

Core Mediators

+ +

Send

+ +

The send token represents a <send> element, used to send messages out +of Synapse to some endpoint. The send mediator also copies any message context +properties from the current message context to the reply message received on +the execution of the send operation so that the response could be correlated +back to the request. Messages may be correlated by WS-A MessageID, or even +simple custom text labels (see the property mediator and samples)

+ +

In the simplest case shown below, the destination to send a message is +implicit in the message via the 'To' address. Thus a request message will be +sent to its 'To' address, and a response message would be sent back to the +client. Removing the 'To' address of a message targets it back to the client, +and thus a request message received may be returned to the client after +changing its direction. (Note: to mark a message as a response set the property +RESPONSE to true)

+ +

Note: A send operation may be blocking or non-blocking +depending on the actual transport implementation used. As the default NIO based +http/s implementation does not block on a send, care must be taken if the same +message must be sent and then further processed (e.g. transformed). In such a +scenario, it maybe required to first clone the message into two copies and then +perform processing to avoid conflicts.

+
 <send/>
+ +

If the message is to be sent to one or more endpoints, then the following is +used:

+
 <send>
+   (endpointref | endpoint)+
+ </send>
+ +

where the endpointref token refers to the following:

+
 <endpoint key="name"/>
+ +

and the endpoint token refers to an anonymous endpoint definition.

+ +

Drop

+ +

The drop token refers to a <drop> element which is used to stop +further processing of a message:

+
 <drop/>
+ +

Once the <drop> mediator executes, further processing of the current +message stops. A the drop mediator does not necessarily close transports.

+ +

Log

+ +

The log token refers to a <log> element which may be used to log +messages being mediated:

+
 <log [level="string"] [separator="string"]>
+   <property name="string" (value="literal" | expression="xpath")/>*
+ </log>
+ +

The optional level attribute selects a pre-defined subset of properties to +be logged.

+ +

e.g.

+
    +
  • simple = To, From, WSAction, SOAPAction, ReplyTo, MessageID and any + properties
  • +
  • headers = All SOAP header blocks and any properties
  • +
  • full = all attributes included in log level 'simple' and the SOAP + envelope and any properties
  • +
  • custom = Only properties specified to the Log mediator
  • +
+ +

A separator if defined will be used to separate the attributes being logged. +The default separator is the ',' comma.

+ +

Property

+
 <property name="string" [action=set|remove] (value="literal" | expression="xpath") [scope=transport|axis2|axis2-client] [type="type name"]/>
+ +

The property token refers to a <property> element which is a mediator +that has no direct impact on the message but rather on the message context +flowing through Synapse. The properties set on a message can be later retrieved +through the synapse:get-property(prop-name) XPath extension function. If a +scope is specified for a property, the property could be set as a transport +header property or an (underlying) Axis2 message context property, or as a +Axis2 client option. If a scope is not specified, it will default to the +Synapse message context scope. Using the property element with action specified +as "remove" you can remove any existing message context properties.

+ +

With the type attribute, we can set properties with specific data types +into the message context. When this attribute is not used the specified property value +will be set as a string. Currently the following data type names are recognized +by the property mediator's type attribute:

+
    +
  • BOOLEAN
  • +
  • DOUBLE
  • +
  • FLOAT
  • +
  • INTEGER
  • +
  • LONG
  • +
  • OM
  • +
  • SHORT
  • +
  • STRING
  • +
+

When the type attribute is assigned one of the above mentioned values, the +specified property value will be converted to the specified type before setting +it into the message context. The type OM can be used to convert the property value +into an AXIOM OMElement. Please note that all type names mentioned above are case +sensitive.

+ +

There are some well-defined properties that you can get/set on the Synapse +message context scope:

+
    +
  • RESPONSE - 'true' means the message is to be marked as a response message +
  • +
  • OUT_ONLY - 'true' means the message is to be marked as an out-only + message that does not expect a response
  • +
  • ERROR_CODE - this is set to any error message code encountered during a + fault
  • +
  • ERROR_MESSAGE - this is set to any error message text encountered during + a fault
  • +
  • ERROR_DETAIL - this is set to any error message detail text encountered + during a fault
  • +
  • +
  • ERROR_EXCEPTION - this is set to any Java Exception encountered during a + fault
  • +
+ +

There are some Axis2 and module properties that are useful which are set at +scope="axis2"

+
    +
  • MercurySequenceKey - can be an identifier specifying an Mercury internal + sequence key, and
  • +
  • MercuryLastMessage - 'true' will make this the last message and terminate + the sequence
  • +
+ +

There are some Axis2 client side properties/options that are useful which +are set at scope="axis2-client"

+
    +
  • FORCE_HTTP_1.0 - forces outgoing http/s messages to use HTTP 1.0 (instead + of the default 1.1)
  • +
+ +
The synapse:get-property() XPath extension function
+ +

The get-property() function allows any XPath expression used in a +configuration to lookup information from the current message context. It is +possible to retrieve properties previously set with the property mediator, +and/or information from the Synapse or Axis2 message contexts or transport +header. The function accepts the scope as an optional parameter as shown below: +

+ +

synapse:get-property( [(axis2 | axis2-client | transport),] +<property_name> [,<dateformat>] )

+ +

Some useful properties from the Synapse message context follows:

+
    +
  • SYSTEM_DATE - Returns the current date as a String. Optionally a date + format as per standard date format may be supplied. e.g. + synapse:get-property("SYSTEM_DATE", "yyyy.MM.dd G 'at' HH:mm:ss z") or + get-property('SYSTEM_DATE')
  • +
  • SYSTEM_TIME - Returns the current time in milliseconds. (i.e. the + difference, measured in milliseconds, between the current time and + midnight, January 1, 1970 UTC)
  • +
  • To, From, Action, FaultTo, ReplyTo, MessageID the message To and Action + and WS-Addressing properties
  • +
  • MESSAGE_FORMAT - returns the message format - i.e. returns pox, get, + soap11 or soap12
  • +
  • OperationName - returns the operation name for the message
  • +
+ +

In addition to the above, one may use the get-property() function to +retrieve Axis2 message context properties or transport headers. e.g. +synapse:get-property('transport', 'USER_AGENT')

+ +
SynapseXpath variables
+ +

There are a set of predefined XPath variables when writing XPaths in the +Synapse Configuration. Those are as follows;

+
    +
  • body - The SOAP 1.1 or 1.2 body element
    + For example; expression="$body/getQuote" refers to the first getQuote element + in the SOAP body regardless of whether the message is SOAP-11 or SOAP-12
  • +
  • header - The SOAP 1.1 or 1.2 header element
    + For example; expression="$header/wsa:To" refers to the addressing To header + regardless of whether this message is SOAP-11 or SOAP-12
+ +

Further there are some variable prefixes defined in Synapse XPaths which can +be usefull in writing the configurations;

+
    +
  • ctx - Prefix for Synapse MessageContext properties
    + For example; expression="$ctx:RESPONSE" gives the value of the Synapse + message context property with name 'RESPONSE'
  • +
  • axis2 - Prefix for Axis2 MessageContext properties
    + For example; expression="$axis2:messageType" gives the value of the axis2 + message context property with name 'messageType'
  • +
  • trp - Prefix for the transport headers
    + For example; expression="$trp:Content-Type" gives the value of the + 'Content-Type' transport header, which is going to be the Content-Type of the + current message
+ +

Sequence

+
 <sequence key="name"/>
+ +

A sequence ref token refers to a <sequence> element which is used to +invoke a named sequence of mediators.

+ +

Validate

+
 <validate [source="xpath"]>
+   <property name="validation-feature-id" value="true|false"/>*
+   <schema key="string"/>+
+   <on-fail>
+     mediator+
+   </on-fail>
+ </validate>
+ +

The <validate> mediator validates the result of the evaluation of the +source xpath expression, against the schema specified. If the source attribute +is not specified, the validation is performed against the first child of the +SOAP body of the current message. If the validation fails, the on-fail sequence +of mediators is executed. Properties could be used to turn on/off some of the +underlying features of the validator (See http://xerces.apache.org/xerces2-j/features.html) +

+ +

Transformation Mediators

+ +

Fault

+
 <makefault [version="soap11|soap12|pox"]>
+   <code (value="literal" | expression="xpath")/>
+   <reason (value="literal" | expression="xpath")>
+   <node>?
+   <role>?
+   <detail>?
+ </makefault>
+ +

The fault mediator transforms the current message into a fault message, but +does NOT send it. The <send> mediator needs to be invoked to send a fault +message created this way. The fault message "To" header is set to the +"Fault-To" of the original message if such a header exists on the original +message. If a 'version' attribute is specified, the created fault message will +be created as a selected SOAP 1.1, SOAP 1.2 or POX fault.

+ +

Callout

+
 <callout serviceURL="string" [action="string"]>
+   <configuration [axis2xml="string"] [repository="string"]/>?
+   <source xpath="expression" | key="string">
+   <target xpath="expression" | key="string"/>
+ </callout>
+ +

The <callout> mediator performs a blocking external service invocation +during mediation. The serviceURL and the optional action specifies the +parameters for this external call. The source element specifies the payload for +the request message using an XPath expression; or a registry key that will be +used. The target element specifies a node, at which the resulting payload will +be attached into the current message, or the name of a key/property using which +the response would be attached to the current message context as a property. +

+ +

As the callout mediator performs a blocking call, it cannot use the default +non-blocking http/s transports based on Java NIO, and thus defaults to using +the samples/axis2Client/client_repo/conf/axis2.xml as the Axis2 configuration, +and samples/axis2Client/client_repo as the client repository unless these are +specified separately

+ +

XSLT

+
 <xslt key="string" [source="xpath"]>
+   <property name="string" (value="literal" | expression="xpath")/>*
+   <feature name="string" value="true| false" />*
+   <resource location="..." key="..."/>*
+ </xslt>
+ +

The <xslt> mediator applies the specified XSLT transformation to the +selected element of the current message payload. If the source element is not +specified, it defaults to the first child of the soap body. Optionally +parameters (XSLT) could be passed into the transformations through the +'property' elements. The 'feature' element defines any features which should be +explicitly set to the TransformerFactory. The feature +'http://ws.apache.org/ns/synapse/transform/feature/dom' turns on DOM based +transformations instead of serializing elements into Byte streams and/or +temporary files. Though this would be better in performance than using byte +streams, sometimes it may not work for all transformations.

+ +

Finally, the 'resource' element can be used to resolve XSLT imports and +includes from the repository. It works in exactly the same way as the +corresponding element in a <proxy> definition.

+ +

XQuery

+
<xquery key="string" [target="xpath"]>
+    <variable name="string" type="string" [key="string"] [expression="xpath"] [value="string"]/>?
+</xquery> 
+ +

The XQuery mediator can be used to perform an XQuery transformation. The +'key' attribute specifies the XQuery transformation, and the optional 'target' +attribute specifies the node of the message that should be transformed. This +defaults to the first child of the SOAP body of the payload. The 'variable' +elements define a variable that could be bound to the dynamic context of the +XQuery engine in order to access those variables through the XQuery script . +

+ +

It is possible to specify just a literal 'value', or an XPath expression +over the payload, or even specify a registry key or a registry key combined +with an XPath expression that selects the variable. The name of the variable +corresponds to the name of variable declaration in the XQuery script. The +'type' of the variable must be a valid type defined by the JSR-000225 (XQJ +API).

+ +

The supported types are:

+
    +
  • XQItemType.XQBASETYPE_INT -> INT
  • +
  • XQItemType.XQBASETYPE_INTEGER -> INTEGER
  • +
  • XQItemType.XQBASETYPE_BOOLEAN -> BOOLEAN
  • +
  • XQItemType.XQBASETYPE_BYTE - > BYTE
  • +
  • XQItemType.XQBASETYPE_DOUBLE -> DOUBLE
  • +
  • XQItemType.XQBASETYPE_SHORT -> SHORT
  • +
  • XQItemType.XQBASETYPE_LONG -> LONG
  • +
  • XQItemType.XQBASETYPE_FLOAT -> FLOAT
  • +
  • XQItemType.XQBASETYPE_STRING -> STRING
  • +
  • XQItemType.XQITEMKIND_DOCUMENT -> DOCUMENT
  • +
  • XQItemType.XQITEMKIND_DOCUMENT_ELEMENT -> DOCUMENT_ELEMENT
  • +
  • XQItemType.XQITEMKIND_ELEMENT -> ELEMENT
  • +
+ +

Header

+
 <header name="qname" (value="literal" | expression="xpath") [action="set"]/>
+ <header name="qname" action="remove"/>
+ +

The <header> mediator sets or removes a specified header from the +current soap infoset. Currently the set header only supports simple valued +headers. In the future we may extend this to have XML structured headers by +embedding the XML content within the element itself. The optional action +attribute specifies whether the mediator should set or remove the header. If +omitted, it defaults to a set-header.

+ +

Smooks

+
 <smooks key="string"/>
+ +

The <smooks> mediator can be used to perform complex content transformation efficiently +using the Smooks framework for XML processing. The key attribute should point to a local entry +or a registry resource which contains a Smooks configuration file. For more information on Smooks +transformation please visit the Smooks website.

+ +

Filter Mediators

+ +

Filter

+
 <filter (source="xpath" regex="string") | xpath="xpath">
+   mediator+
+ </filter>
+ +

The <filter> mediator either test the given xpath expression as a +boolean expression, or match the evaluation result of a source xpath expression +as a String against the given regular expression. If the test succeeds, the +filter mediator will execute the enclosed mediators in sequence.

+ +

One could also use this mediator to handle the failure case as well, in +which case the configuration would be as follows

+
 <filter (source="xpath" regex="string") | xpath="xpath">
+   <then [sequence="string"]>
+     mediator+
+   </then>
+   <else [sequence="string"]>
+     mediator+
+   </else>
+ </filter>
+ +

In this case the filter condition remains as earlier and the succeeded +messages will be mediated using the the set of mediators enclosed in the 'then' +element in sequence, while failed messages will be mediated using the set of +mediators enclosed in the else element in sequence

+ +

Switch

+
 <switch source="xpath">
+   <case regex="string">
+     mediator+
+   </case>+
+   <default>
+     mediator+
+   </default>?
+ </switch>
+ +

The <switch> mediator will evaluate the given source xpath expression +into its string value, and match it against the given regular expressions. If +the specified cases does not match and a default case exists, it will be +executed.

+ +

In / Out

+
<in>
mediator+ +</in>
+
<out>
+  mediator+
+</out>
+ +


+

+ +

The In and Out mediators will execute the child mediators over the current +message if the message matches the direction of the mediator. Hence all +incoming messages would pass through the "<in>" mediators and vice versa. +

+ +

Router

+
<router [continueAfter=(true | false)]>
+  <route expression="xpath" [match="regEx"] [breakRouter=(true | false)]>
+    <target [sequence="string"] [endpoint="string"]>
+      <sequence ....../>?
+      <endpoint ....../>?
+    </target>
+  </route>+
+</router>
+ +

Router mediator is represented by the 'router' root tag and it can contain +any number of routes which are represented with the 'route' tags. Router +mediator can be configured to continue or to stop the mediation after the +routing by setting the 'continueAfter' attribute value to be 'true' and 'false' +respectively. Each and every route must contain an 'expression' attribute which +is to specify the XPath over which the routing condition is evaluated. Apart +from that there can be an optional 'match' attribute as well. If both +expression and the match attirbutes are specified in a particualr route, the +evaluated string value of the XPath over the current message will be campared +with the reular expression provided as the value of the match attribute to see +whether this route is matching for the current message. Where as if only the +expression is specified, presence of the element specified by this XPath is +considered as the routing condition.

+ +

One can configure a route to break routing or continue evaluating further +routes to see any further matchings by setting the 'breakRouter' attribute to +'true' or 'false' respectively. For all the routes there has to be a 'target' +element which contains the information about the routing path as a sequence or +an endpoint both can be inlined as well as refered. If both an endpoint and a +sequence is specified message will be first mediated through the sequence and +sent to the endpoint after mediation. Particular target cannot contain an +inline sequence and a refered sequence at the same time. The same applies to +endpoit of the target as well.

+ +

Database Mediators

+ +

DB-lookup

+
<dblookup>
+   <connection>
+     <pool>
+      (
+       <driver/>
+       <url/>
+       <user/>
+       <password/>
+     |
+       <dsName/>
+       <icClass/>
+       <url/>
+       <user/>
+       <password/>
+     )
+       <property name="name" value="value"/>*
+     </pool>
+   </connection>
+   <statement>
+     <sql>select something from table where something_else = ?</sql>
+     <parameter [value="" | expression=""] type="CHAR|VARCHAR|LONGVARCHAR|NUMERIC|DECIMAL|BIT|TINYINT|SMALLINT|INTEGER|BIGINT|REAL|FLOAT|DOUBLE|DATE|TIME|TIMESTAMP"/>*
+     <result name="string" column="int|string"/>*
+   </statement>+
+</dblookup>
+ +

The dblookup mediator is capable of executing an arbitrary SQL select +statement, and then set some resulting values as local message properties on +the message context. The DB connection used maybe looked up from an external +DataSource or specified in-line, in which case an Apache DBCP connection pool +is established and used. Apache DBCP connection pools support the following +properties:

+
    +
  • autocommit = true | false
  • +
  • isolation = Connection.TRANSACTION_NONE | + Connection.TRANSACTION_READ_COMMITTED | + Connection.TRANSACTION_READ_UNCOMMITTED | + Connection.TRANSACTION_REPEATABLE_READ | + Connection.TRANSACTION_SERIALIZABLE
  • +
  • initialsize = int
  • +
  • maxactive = int
  • +
  • maxidle = int
  • +
  • maxopenstatements = int
  • +
  • maxwait = long
  • +
  • minidle = int
  • +
  • poolstatements = true | false
  • +
  • testonborrow = true | false
  • +
  • testonreturn = true | false
  • +
  • testwhileidle = true | false
  • +
  • validationquery = String
  • +
+ +

More than one statement may be specified, and the SQL statement may specify +parameters which could be specified as values or XPath expressions. The types +of parameters could be any valid SQL types. Only the first row of a result set +will be considered and any others are ignored. The single <result> +element contains the 'name' and the column' attributes. The 'name' attribute +defines the name under which the result is stored in the Synapse message +context, and the column attribute specifies a column number or name .

+ +

DB-report

+
<dbreport>
+   <connection>
+     <pool>
+      (
+       <driver/>
+       <url/>
+       <user/>
+       <password/>
+     |
+       <dsName/>
+       <icClass/>
+       <url/>
+       <user/>
+       <password/>
+     )
+       <property name="name" value="value"/>*
+     </pool>
+   </connection>
+   <statement>
+     <sql>insert into something values(?, ?, ?, ?)</sql>
+     <parameter [value="" | expression=""] type="CHAR|VARCHAR|LONGVARCHAR|NUMERIC|DECIMAL|BIT|TINYINT|SMALLINT|INTEGER|BIGINT|REAL|FLOAT|DOUBLE|DATE|TIME|TIMESTAMP"/>*
+    </statement>+
+</dblreport>
+ +

The dbreport mediator is very similar to the dblookup mediator, but writes +information to a Database, using the specified insert SQL statement.

+ +

Advanced Mediators

+ +

RMSequence

+
 <RMSequence (correlation="xpath" [last-message="xpath"]) | single="true" [version="1.0|1.1"]/>
+ +

The <RMSequence> mediator can be used to create a sequence of messages +to communicate via WS-Reliable Messaging with an WS-RM enabled endpoint +(<enableRM>). The simple use case of this mediator is to specify a +single="true" property, because this means that only one message is involved in +the same sequence. However if multiple messages should be sent in the same +sequence, the correlation property should be used with a XPath expression that +selects an unique element value from the incoming message. With the result of +the XPath expression, Synapse can group messages together that belong to the +same sequence. To close the sequence neatly, for the last message of the +sequence also an XPath expression should be specified. With the version +attribute the WS-RM specification version to be used can be specified, 1.0 or +1.1.

+ +

Throttle

+
<throttle [onReject="string"] [onAccept="string"] id="string">
+    (<policy key="string"/> | <policy>..</policy>)
+    <onReject>..</onReject>?
+    <onAccept>..</onAccept>?
+</throttle>
+ +

The Throttle mediator can be used for rate limiting as well as concurrency +based limiting. A WS-Policy dictates the throttling configuration and may be +specified inline or loaded from the registry. Please refer to the samples +document for sample throttling policies. The Throttle mediator could be added +in the request path for rate limiting and concurrent access limitation. When +using for concurrent access limitation, the same throttle mediator 'id' must be +triggered on the response flow so that completed responses are deducted from +the available limit. (i.e. two instances of the throttle mediator with the same +'id' attribute in the request and response flows). The 'onReject' and +'onAccept' sequence references or inline sequences define how accepted and +rejected messages are to be handled.

+ +

Cache

+
 <cache [id="string"] [hashGenerator="class"] [timeout="seconds"] [scope=(per-host | per-mediator)]
+     collector=(true | false) [maxMessageSize="in-bytes"]>
+   <onCacheHit [sequence="key"]>
+     (mediator)+
+   </onCacheHit>?
+   <implementation type=(memory | disk) maxSize="int"/>
+ </cache>
+ +

The <cache> mediator will evaluate the hash value of an incoming +message as described in the optional hash generator implementation (which +should be a class implementing the org.wso2.caching.digest.DigestGenerator +interface). The default hash generator is +'org.wso2.caching.digest.DOMHashGenerator'. If the generated hash value has +been found in the cache then the cache mediator will execute the onCacheHit +sequence which can be specified inline or referenced. The cache mediator must +be specified with an 'id' and two instances with this same 'id' that correlates +the response message into the cache for the request message hash. The optional +'timeout' specifies the valid duration for cached elements, and the scope +defines if mediator instances share a common cache per every host instance, or +per every cache mediator pair (i.e. 'id') instance. The 'collector' attribute +'true' specifies that the mediator instance is a response collection instance, +and 'false' specifies that its a cache serving instance. The maximum size of a +message to be cached could be specified with the optional 'maxMessageSize' +attributes in bytes and defaults to unlimited. Finally the 'implementation' +element may define if the cache is disk or memory based, and the 'maxSize' +attribute defines the maximum number of elements to be cached.

+ +

Clone

+
 <clone [id="id"] [continueParent=(true | false)] [sequential=(true | false)]>
+   <target [to="uri"] [soapAction="qname"] [sequence="sequence_ref"] [endpoint="endpoint_ref"]>
+     <sequence>
+       (mediator)+
+     </sequence>?
+     <endpoint>
+       endpoint
+     </endpoint>?
+   </target>+
+ </clone>
+ +

The clone mediator closely resembles the Message Splitter EIP and will split +the message into number of identical messages which will be processed in +parallel. They can also be set to process sequentially by setting +the value of the optional 'sequential' attribute to 'true'. +The original message cloned can be continued or dropped depending on +the boolean value of the optional 'continueParent' attribute. Optionally a +custom 'To' address and/or a 'Action' may be specified for cloned messages +The optional 'id' attribute can be used to identify the clone mediator which +created a particular splitted message when nested clone mediators are used. +This is particularly useful when aggregating responses of messages that are +created using nested clone mediators. +

+ +

Iterate

+
 <iterate [id="id"] [continueParent=(true | false)] [preservePayload=(true | false)] [sequential=(true | false)] (attachPath="xpath")? expression="xpath">
+   <target [to="uri"] [soapAction="qname"] [sequence="sequence_ref"] [endpoint="endpoint_ref"]>
+     <sequence>
+       (mediator)+
+     </sequence>?
+     <endpoint>
+       endpoint
+     </endpoint>?
+   </target>+
+ </iterate>
+ +

The iterate mediator implements another EIP and will split the message into +number of different messages derived from the parent message by finding +matching elements for the XPath expression specified. New messages will be +created for each and every matching element and processed in parallel(default +behavior) using either the specified sequence or endpoint. +Created messages can also be set to process sequentially by setting the optional 'sequential' +attribute to 'true'. Parent message can be continued or +dropped in the same way as in the clone mediator. The 'preservePayload' +attribute specifies if the original message should be used as a template when +creating the splitted messages, and defaults to 'false', in which case the +splitted messages would contain the split elements as the SOAP body. The optional 'id' attribute +can be used to identify the iterator which created a particular splitted message when nested iterate +mediators are used. This is particularly useful when aggregating responses of messages that are +created using nested iterate mediators.

+ +

Aggregate

+
 <aggregate [id="id"]>
+   <correlateOn expression="xpath"/>?
+   <completeCondition [timeout="time-in-seconds"]>
+     <messageCount min="int-min" max="int-max"/>?
+   </completeCondition>?
+   <onComplete expression="xpath" [sequence="sequence-ref"]>
+     (mediator +)?
+   </onComplete>
+ </aggregate>
+ +

The aggregate mediator implements the Message Aggregator EIP and will +aggregate the messages or responses for splitted messages using either the +clone or iterate mediators. At the same time it can aggregate messages on the +presence of matching elements specified by the correlateOn XPATH expression. +Aggregate will collect the messages coming into it until the messages collected +on the aggregation satisfies the complete condition. The completion condition +can specify a minimum or maximum number of messages to be collected, or a +timeout value in seconds, after which the aggregation terminates. On completion +of the aggregation it will merge all of the collected messages and invoke the +onComplete sequence on it. The merged message would be created using the XPath +expression specified by the attribute 'expression' on the 'onComplete' element. +The optional 'id' attribute can be used to aggregate only responses for splitted messages that +are created by a specific clone/iterate mediator. Aggregate ID should be same as the ID of the +corresponding clone/iterate mediator that creates splitted messages. This is particularly useful +when aggregating responses of messages that are created using nested clone/iterate mediators. +

+ +

Event

+
 <syn:eventPublisher eventSourceName="event-source-name"/>
+ +

Event mediator publishes events to the given event source. Thus, the +presence of defined event sources are necessary prior to the usage of this +mediator.

+ +

Entitlement

+
 <syn:entitlementService remoteServiceUrl="[IDENTITY_SERVER:PORT]/services" remoteServiceUserName="admin" remoteServicePassword="admin"/>
+ +

The Entitlement Mediator by passes the requests and evaluates the actions performed by the user +against the XACML policy defined at the Policy Decision Point [WSO2 Identity Server]

+ +

OAuth

+
 <syn:oauthService remoteServiceUrl="[IDENTITY_SERVER:PORT]/services"/>
+ +

The OAuth Mediator by passes the requests and evaluates RESRfull invocations based on 2-legged OAuth.

+ +

Transaction

+
 <syn:transaction action="transaction-action" />
+ +

Transaction mediator can provide transaction facility for a set of mediators +defined as its child mediators. A transaction mediator with the action "new" +indicates the entry point for the transaction. A transaction is marked +completed by a transaction mediator with the action "commit". The suspend and +resume actions are used to pause a transaction at some point and start it again +later. Additionally, the transaction mediator supports three other actions, +i.e. use-existing-or-new, fault-if-no-tx, rollback.

+ +

Extension mediators

+ +

Class

+
 <class name="class-name">
+   <property name="string" value="literal">
+     (either literal or XML child)
+   </property>
+ </class> 
+ +

The class mediator creates an instance of a custom specified class and sets +it as a mediator. The class must implement the org.apache.synapse.api.Mediator +interface. If any properties are specified, the corresponding setter methods +are invoked on the class, once, during initialization.

+ +

POJOCommand

+
 <pojoCommand name="class-name">
+   (
+   <property name="string" value="string"/> |
+   <property name="string" context-name="literal" [action=(ReadContext | UpdateContext | ReadAndUpdateContext)]>
+     (either literal or XML child)
+   </property> |
+   <property name="string" expression="xpath" [action=(ReadMessage | UpdateMessage | ReadAndUpdateMessage)]/>
+   )*
+ </pojoCommand> 
+ +

The pojoCommand mediator creates an instance of the specified command class +- which may implement the org.apache.synapse.Command interface or should have a +public void method "public void execute()". If any properties are specified, +the corresponding setter methods are invoked on the class before each message +is executed. It should be noted that a new instance of the POJO Command class +is created to process each message processed. After execution of the POJO +Command mediator, depending on the 'action' attribute of the property, the new +value returned by a call to the corresponding getter method is stored back to +the message or to the context. The 'action' attribute may specify whether this +behaviour is expected or not via the Read, Update and ReadAndUpdate properties. +

+ +

Scripting language mediators

+ +

Synapse supports Mediators implemented in a variety of scripting languages +such as JavaScript, Python or Ruby. There are two ways of defining script +mediators, either with the script program statements stored in a separate file +which is referenced via the local or remote registry entry, or with the script +program statements embedded in-line within the Synapse configuration. A script +mediator using a script off the registry (local or remote) is defined as +follows:

+
 <script key="string" language="string" [function="script-function-name"]/>
+ +

The property key is the registry key to load the script. The language +attribute specifies the scripting language of the script code (e.g. "js" for +Javascript, "rb" for ruby, "groovy" for Groovy, "py" for Python..). The +function is an optional attribute defining the name of the script function to +invoke, if not specified it defaults to a function named 'mediate'. The +function is passed a single parameter - which is the Synapse MessageContext. +The function may return a boolean, if it does not, then true is assumed, and +the script mediator returns this value. An inline script mediator has the +script source embedded in the configuration as follows:

+
 <script language="string">...script source code...<script/>
+ +

The execution context environment of the script has access to the Synapse +MessageContext predefined in a script variable named 'mc' . An example of an +inline mediator using JavaScript/E4X which returns false if the SOAP message +body contains an element named 'symbol' which has a value of 'IBM' would be: +

+
 <script language="js">mc.getPayloadXML()..symbol != "IBM";<script/>
+ +

Synapse uses the Apache Bean +Scripting Framework for the scripting language support, any script language +supported by BSF may be used to implement a Synapse Mediator.

+ +

Implementing a Mediator with a script language can have advantages over +using the built in Synapse Mediator types or implementing a custom Java class +Mediator. Script Mediators have all the flexibility of a class Mediator with +access to the Synapse MessageContext and SynapseEnvironment APIs, and the ease +of use and dynamic nature of scripting languages allows rapid development and +prototyping of custom mediators. An additional benefit of some scripting +languages is that they have very simple and elegant XML manipulation +capabilities, for example JavaScript E4X or Ruby REXML, so this makes them well +suited for use in the Synapse mediation environment. For both types of script +mediator definition the MessageContext passed into the script has additional +methods over the standard Synapse MessageContext to enable working with the XML +in a way natural to the scripting language. For example when using JavaScript +getPayloadXML and setPayloadXML, E4X XML objects, and when using Ruby, REXML +documents.

+ +

Extensibility of WSO2 ESB

+ +

The Synapse configuration language could be easily extended, with +configuration extensions as well as mediation extensions. The Spring mediator +is such an example.

+ +

Spring Configuration

+ +

A Spring configuration could be created as a localEntry or remote registry +entry providing a URL or a key reference to a Registry. The configuration is +then created on first use or as necessary (as per registry lookup semantics) by +the mediators which reference this configuration.

+
 <localEntry key="string"/>
+ <localEntry key="string" src="url"/>
+ +

The name attribute specifies a unique name for the configuration, and the +src, key or inlined XML references to the Spring configuration

+ +

Spring mediator

+
 <spring:spring bean="exampleBean1" key="string"/>
+ +

The <spring> element creates an instance of a mediator, which is +managed by Spring. This Spring bean must implement the Mediator interface for +it to act as a Mediator. The key will reference the Spring +ApplicationContext/Configuration used for the bean

+ +

The <spring> element creates an instance of a mediator, which is +managed by Spring. This Spring bean must implement the Mediator interface for +it to act as a Mediator. The key will reference the Spring +ApplicationContext/Configuration used for the bean

+ + +

Rule Mediator - Java Rule mediator

+ +

Rule mediator is to integrate the WSO2 Rules component to the WSO2 ESB in +order to define dynamic integration decisions in terms of rules.

+
 <rule>
+
+    <ruleset>
+        <source [ key="xs:string" ]>
+            [ in-Lined ]
+        </source>
+        <creation>
+            <property name="xs:string" value="xs:string"/>*
+        </creation>
+    </ruleset>
+
+    <session type="[stateless|stateful]"/>*
+
+    <facts>
+        <fact name="xs:string" type="xs:string" expression="xs:string" value="xs:string"/>+
+    </facts>
+
+    <results>
+        <result name="xs:string" type="xs:string" expression="xs:string" value="xs:string"/>*
+    </results>
+
+    [ <childMediators>
+        <mediator/>*
+      </childMediators> ]
+
+  </rule>
+        
+ +

The Configuration of the Rule Mediator

+ +

RuleSet

+ +

The source is the only mandatory element of the ruleset. However, the +properties required for the creation of the ruleset can also be specified +within ruleset. The key attribute is a registry key, which is to lookup the +rule script from the registry if the rule script is in the registry. The rule +set can be given as a child node of source elemenent. If the rule set is +non-XML, you may need to wrap it with a CDATA section inside a XML tag ex: +<X><![CDATA[ native code]]></X>

+ +

Note : The key or in-lined rule script must be defined. Otherwise, the rule +mediator configuration is invalid.

+ +

RuleSession

+ +

Rule Session specify the stateful or stateless behavior of the rule engine. +If this has value ‘stateful’, then the rule engine will execute +rules in a stateful manner, for any other value , it assumes as stateless. +There are optional properties, which are used when creating the rule session. +Rule session is optional and the default one is stateful.

+ +

Facts / Results

+
    +
  • name - the unique name
  • +
  • value - Represents any static value
  • +
  • expression - XPath expression for extracting data from the message being + passed between ESB components. The default value is the first child of the + SOAP Body.
  • +
  • type - Defines the type of the input data. There are a few built in types + such as Message, Context, Map, POJO and Mediator and there are samples + using these. Using the rule-component.conf, you can register new types + along with adapters, which are responsible for formulating specified types + from the data. If there is no registered adapter for a given type, then, we + assume the given type as a valid java class name and uses POJO adapter to + formulate the POJO instance whose class is the given type.
  • +
+ +

Facts specify the facts being used in rule set. It also defines how to +formulate facts from the message, etc. Results define how to handle results +from the rule set execution. Usually, results adapters enrich the message with +results. For example, If you are using POJO adapter (i.e. a java class as the +type – the class name of a result), then we transform POJO into an XML +and attached to the SOAP message.

+ +

UI Integration

+

As mentioned earlier the ESB management console provides tools that can be +used to construct mediation configurations. When these tools are used to create +endpoints, sequences, proxy services and other configuration elements they are +also saved under the appropriate child directory under the synapse-config +directory. For an example if you add an endpoint named 'foo' from the UI it will +be saved to a file named 'foo.xml' in the synapse-config/endpoints directory. +Further modifications to the endpoint 'foo' will be saved to the same configuration +file.

+

However there is a slight exception with the Synapse configuration editor in the +ESB management console (available under the 'Configure' menu). New elements add +through this editor will be saved to the top level synapse.xml file in the +synapse-config directory. Anyway, if an existing item is modified through the Synapse +configuration editor it will be still saved back to the original file where it was +loaded from.

+ + + + diff --git a/docs/xdoc/deployment_guide.xml b/docs/xdoc/deployment_guide.xml new file mode 100644 index 0000000000..b2f5fc77b3 --- /dev/null +++ b/docs/xdoc/deployment_guide.xml @@ -0,0 +1,493 @@ + + + + + + + + + WSO2 ESB - Deployment Guide + + + + + + [ Documentation Index ] +

+ WSO2 Enterprise Service Bus (ESB) Deployment Guide +

+

+ Deploying the WSO2 ESB correctly on your infrastructure is a vital task for the success + of the usage of the ESB. You should first analyze the requirement and then select the + best matching deployment mode. There are different set of possible deployment modes with + different configurations. +

+

+ Available Deployment options +

+

+ Standalone Deployment Guide : + Describes the default standalone installation and deployment of the ESB +

+

+ Webapp Deployment Guide : + Contains the information on deploying the ESB on an Application Server, this particular guide + explains the deployment of an existing Tomcat Servlet Container. +

+ +

Clustered Deployment Guide

+

+ This document describes the steps you need to follow to setup a working WSO2 ESB cluster in your environment. +

Clustering the ESB has two different aspects. +

+
    +
  1. Configuration sharing across the cluster nodes
  2. +
  3. Runtime state replication among the cluster nodes
  4. +
+ +

+ Configuration sharing across the cluster nodes +

+ +

The configuration sharing is done using the WSO2 Governance Registry. All the ESB nodes in the + cluster are pointed to one instance of WSO2 G-Reg and through this registry configuration is shared. +

+

+ WSO2 G-Reg consists of three registry spaces. +

+
    +
  • Local Registry - Per running instance of every product
  • +
  • Configuration Registry - Shared among all the instance of a cluster of one product
  • +
  • Governance Registry - Centrally managed & shared across multiple products and multiple + instances of those
  • +
+

So, when it comes to ESB clustering, we will be using local registry per each instance, + mounting the configuration registry of each ESB instance to the same config registry and + sharing the governance space among GReg and 2-ESB instances. +

+

First lets see how to set up ESB instances pointing to a single G-Reg.

+

+ WSO2 ESB Cluster Deployment Diagram
+ ESB clustered with GReg +

+

Setting UP WSO2 ESB cluster with GReg

+
    +
  • Extract the WSO2 ESB 4.0.0 distribution and as the first step we need to configure the database configuration.
  • +
  • Both GReg and ESB are shipped embedded H2 registry. However, for clustering purposes we will be using MySQL instead.
  • +
  • In the following setup, we have GReg running on mysql database which means it's local/config/governance registries are store in a mysql database and it's user-manager tables are also inside the same database.
  • +
  • In ESB instances, +
      +
    • Both master and slave ESBs are using unique local registries.
    • +
    • Both configuration registries mounted to the same directory of GReg.
    • +
    • Governance registry is mounted to the governance registry of GReg
    • +
    +
  • +
  • All the ESB instances in the cluster are sharing a common database for user-manager. (if you are using an LDAP you do not have to use a database for user-manager.)
  • +
+

+ (This documentation http://wso2.org/project/registry/3.5.0/docs/user_guide/registry_config.html contains database + configurations with different databases and we recommend you to go through it if you are using a + different database server other than mysql.) +

+ +

ESB cluster database configuration

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Instance NameRegistry SpaceInstance Name
Registry Space Mysql database name/mounted path (x.x.x.x)
ESB Master (x.x.x.x)localamamaster
configamagregdb /_system/esbConfig
governanceamagregdb /_system/governance
user-manageramausermgtdb
ESB Slave1 (x.x.x.x)localamaslave1
configamagregdb /_system/esbConfig
governanceamagregdb /_system/governance
user-manageramausermgtdb
GREG (x.x.x.x)Allamagregdb
+ +

In the above table there are 5 separate databases with following names

+
    +
  • amagregdb
  • +
  • amausermgtdb
  • +
  • amaslave1
  • +
  • amamaster
  • +
+ +

If you are having your database remotely, please + configure mysql instance to allow remote + connections to accept.

+ +

Running Multiple instance of the WSO2 Carbon Servers in the same machine

+

If you are running multiple instance same or different WSO2 Product Instances, then you need to + configure ports for each instance. You can configure $CARBON_HOME/repository/conf/carbon.xml by using portOffset +

+
+          <Offset>0</Offset>
+      
+

Please provide + Offset value

+

E.g: If Offset=2 and HTTPS port=9443, will be set the effective HTTPS port to 9445

+ + +

Settings for Governance Registry

+

+ If you see the table above you can see that we are using a single database + for all the queries in GREG instance. So we need to change the configuration in registry.xml and user-mgt.xml. +

+ +

Go to GREG_HOME/repository/conf/registry.xml file remove the original dbConfig element and add the + database configuration below. (IP addresses and database urls have to be changed acccording to your setup).

+
+   <currentDBConfig>wso2registry</currentDBConfig>
+   <readOnly>false</readOnly>
+   <registryRoot>/</registryRoot>
+   <dbConfig name="wso2registry">
+     <url>jdbc:mysql://x.x.x.x:3306/amagregdb?autoReconnect=true</url>
+        <userName>root</userName>
+        <password>root123</password>
+        <driverName>com.mysql.jdbc.Driver</driverName>
+        <maxActive>50</maxActive>
+        <maxWait>60000</maxWait>
+        <minIdle>5</minIdle>
+    </dbConfig>
+  
+ +

+ Go to GREG_HOME/repository/conf/user-mgt.xml file and change the database configuration as below(IP addresses and urls have to be changed according to your setup). +

+
+    <Property name="url">jdbc:mysql://x.x.x.x:3306/amagregdb?autoReconnect=true</Property>
+    <Property name="userName">root</Property>
+    <Property name="password">root123</Property>
+    <Property name="driverName">com.mysql.jdbc.Driver</Property>
+    <Property name="maxActive">50</Property>
+    <Property name="maxWait">60000</Property>
+    <Property name="minIdle">5</Property>
+       
+ + +

Copy mysql jdbc driver library to GREG_HOME/repository/components/lib direcotry since by default we do not ship the mysql drivers in GREG.

+

If we examine the above configuration we can see that we are pointing the same database (amagregdb)for registry and user store .

+

Start the GREG instance with -Dsetup + (This will create tables for user manager database and registry database(pick the database configuration from currentDBConfig element in registry.xml + since there might be number of database configurations in your registry.xml which we put + to perform mounting from other databases but only one database configuration is configured as currentDBConfig)). +

+ +

After successfully starting GREG instance create following directory from GREG's management console. Go to + management console-->Registry browser and create "esbConfig" collection under "system" path. + Configurations will be mounted by ESB instances running in the cluster to this directory.( /_system/esbConfig)

+ +

Settings for ESB Master Node

+ +

Here we are changing the default database configuration to point master node's local registry to amamaster and will be poinetd the user manager database + to amausermgtdb . Here ESB master node's configuration and Governance registriy's configuration also will be mounted from GREG database.

+ +

Let's first add local registry configuration and user-manager configuration.

+

Open the ESB_HOME/repository/conf/registry.xml file remove the original dbConfig element and add the database configuration below. + (IP addresses and database urls have to be changed according to your setup).

+ +
+    <currentDBConfig>wso2registry</currentDBConfig>
+        <readOnly>false</readOnly>
+       <registryRoot>/</registryRoot>
+        <dbConfig name="wso2registry">
+     <url>jdbc:mysql://x.x.x.x:3306/amamaster?autoReconnect=true</url>
+        <userName>root</userName>
+        <password>root123</password>
+        <driverName>com.mysql.jdbc.Driver</driverName>
+        <maxActive>50</maxActive>
+        <maxWait>60000</maxWait>
+        <minIdle>5</minIdle>
+    </dbConfig>
+      
+ + +

Open the ESB_HOME/repository/conf/user-mgt.xml file and change the database configuration as below(IP addresses and urls have to be changed according to your setup).

+
+  <Property name="url">jdbc:mysql://x.x.x.x:3306/amausermgtdb?autoReconnect=true</Property>
+        <Property name="userName">root</Property>
+        <Property name="password">root123</Property>
+        <Property name="driverName">com.mysql.jdbc.Driver</Property>
+        <Property name="maxActive">50</Property>
+        <Property name="maxWait">60000</Property>
+     <Property name="minIdle">5</Property>
+      
+

Now let's configure the mounting configuration. For that we need to add more parameters to registry.xml file.

+

Open the ESB_HOME/repository/conf/registry.xml file and add the following mount database configuration below. (IP addresses and database urls have to be changed acccording to your setup).

+
+      <dbConfig name="esbMountRegistry">
+         <url>jdbc:mysql://x.x.x.x:3306/amagregdb?autoReconnect=true</url>
+            <userName>root</userName>
+            <password>root123</password>
+            <driverName>com.mysql.jdbc.Driver</driverName>
+            <maxActive>50</maxActive>
+            <maxWait>60000</maxWait>
+            <minIdle>5</minIdle>
+        </dbConfig>
+
+
+        <remoteInstance url="https://x.x.x.x:9443/registry">
+            <id>Mount1</id>
+            <dbConfig>esbMountRegistry</dbConfig>
+            <readOnly>false</readOnly>
+            <registryRoot>/</registryRoot>
+        </remoteInstance>
+
+        <mount path="/_system/config" overwrite="true">
+            <instanceId>Mount1</instanceId>
+            <targetPath>/_system/esbConfig</targetPath>
+        </mount>
+
+        <mount path="/_system/governance" overwrite="true">
+            <instanceId>Mount1</instanceId>
+            <targetPath>/_system/governance</targetPath>
+        </mount>
+      
+

Please change the "remoteInstance URL" according to the configuration of the GREG instance. Please note that "InstanceIds", "id" and "dbConfig" elements should be mapped properly if you are using different + names for them.

+ +

Copy mysql jdbc driver library to ESB_HOME/repository/components/lib direcotry since by default we do not ship the mysql drivers in ESB.

+ +

Settings for ESB Slave Node

+ +

Here we are changing the default database configuration, to point slvae node's local registry to amaslave1 and will be pointed the user manager + database to amausermgtdb . Here ESB slave node's configuration and Governance registriy's configuration also will be mounted from GREG database.

+ +

Let's first add local registry configuration and user-manager configuration.

+

Open the ESB_SLAVE_HOME/repository/conf/registry.xml file , remove the original dbConfig element and add the database configuration below. (IP addresses and database + urls have to be changed acccording to your setup).

+
+      <currentDBConfig>wso2registry</currentDBConfig>
+            <readOnly>false</readOnly>
+           <registryRoot>/</registryRoot>
+            <dbConfig name="wso2registry">
+         <url>jdbc:mysql://x.x.x.x:3306/amaslave1?autoReconnect=true</url>
+            <userName>root</userName>
+            <password>root123</password>
+            <driverName>com.mysql.jdbc.Driver</driverName>
+            <maxActive>50</maxActive>
+            <maxWait>60000</maxWait>
+            <minIdle>5</minIdle>
+        </dbConfig>
+      
+

Open the ESB_SLAVE_HOME/repository/conf/user-mgt.xml file and change the database configuration as below(IP addresses and urls have to be changed according to your setup).

+

Note : Here we are changing the mode to 'readOnly' in database configuration.

+
+  <ReadOnly>true</ReadOnly>
+        <Property name="url">jdbc:mysql://x.x.x.x:3306/amausermgtdb?autoReconnect=true</Property>
+        <Property name="userName">root</Property>
+        <Property name="password">root123</Property>
+        <Property name="driverName">com.mysql.jdbc.Driver</Property>
+        <Property name="maxActive">50</Property>
+        <Property name="maxWait">60000</Property>
+     <Property name="minIdle">5</Property>
+      
+ +

Now let's configure the mounting configuration. For that we need to add more parameters to registry.xml file.

+

Open the ESB_SLAVE_HOME//repository/conf/registry.xml file and add the following mount database configuration below. (IP addresses and database urls have to be changed acccording to your setup).

+ + + +
+  <dbConfig name="esbMountRegistry">
+     <url>jdbc:mysql://x.x.x.x:3306/amagregdb?autoReconnect=true</url>
+        <userName>root</userName>
+        <password>root123</password>
+        <driverName>com.mysql.jdbc.Driver</driverName>
+        <maxActive>50</maxActive>
+        <maxWait>60000</maxWait>
+        <minIdle>5</minIdle>
+    </dbConfig>
+
+
+    <remoteInstance url="https://x.x.x.x:9443/registry">
+        <id>Mount1</id>
+        <dbConfig>esbMountRegistry</dbConfig>
+        <readOnly>true</readOnly>
+        <registryRoot>/</registryRoot>
+    </remoteInstance>
+
+    <mount path="/_system/config" overwrite="true">
+        <instanceId>Mount1</instanceId>
+        <targetPath>/_system/esbConfig</targetPath>
+    </mount>
+
+    <mount path="/_system/governance" overwrite="true">
+      <instanceId>Mount1</instanceId>
+        <targetPath>/_system/governance</targetPath>
+    </mount>
+      
+ + + +

+ Please change the remoteInstance URL according to the configuration of the GREG running machine. Please note that "InstanceIds", "id" and "dbConfig" elements + should be mapped properly if you are using different names for them. +

+

+ Note: If you compare the configuration with master node, we are only changing the configuration of local registry + and all the other configurations are same with the master node, but the registry access mode in mounting is readonly but the local registry + configuration should be read-write since it is specific for each node. +

+ +

Copy mysql jdbc driver library to ESB_SLAVE_HOME/repository/components/lib direcotry since by default we do not ship the mysql drivers in ESB.

+

Before starting the slave ESB node you need to load registry database schema to amaslave1 database. + You can find the required SQL script at ESB_SLAVE_HOME/dbscripts directory.

+ +

Running the setup

+ +

After successful configurations, run the wso2server.sh or wso2server.bat of master node based on your platform with '-Dsetup' option for the first time start up + to create the database tables, and after creating database tables, do not use '-Dsetup' option when run the server.

+
sh CARBON_HOME/bin/wso2server.sh -Dsetup
+ +

You don't need to specify the -Dsetup option for ESB slave node because we have created DB schema in the previous step.

+

Note: -Dsetup doesn't work with ESB slave node because we share a same database for user manager and -Dsetup option will try to + create user manager tables at the startup if you use -Dsetup option.

+ +

After setting up the ESB's pointing to a single Registry we have two options for sharing the configuration.

+ + +
    +
  1. Manual configuration sharing +

    In this mode ESB's can be configured to load the configuration from the Registry instead of the file system. The configuration loading happens only when the ESB starts up. So if a change is made to the master ESB node, other ESB's has to be restarted to get the new configuration. + + Lot of users prefer this mode because it guarantees a consistent configuration at the start up and configuration is not changed while the ESB is running. + By default ESB loads the configuration from the File System. If the configuration has to be loaded from the Registry following configuration has to be uncommented and changed in the carbon.xml

    +
    +<MediationConfig>
    +    <LoadFromRegistry>false</LoadFromRegistry>
    +    <SaveToFile>false</SaveToFile>
    +    <Persistence>enabled</Persistence>
    +    <RegistryPersistence>enabled</RegistryPersistence>
    +</MediationConfig>
    +                  
    +

    LoadFromRegistry parameter has to be changed to true in the slave nodes.

    + +
  2. +
  3. Deployment Synchronizer +

    The next approach is to use the Deployment Synchronizer shipped with the ESB. With the deployment + synchronizer, configurations can be updated in the slave nodes at the runtime.

    +
      +
    1. Configuration has to be changed in the master node.
    2. +
    3. The check in that configuration to the registry
    4. +
    5. Check out the configuration from the slave nodes
    6. +
    +
  4. +
+ + +

Runtime State Replication

+

WSO2 ESB flows are stateless for the most part. But in very rare deployments users have requested to share some of the runtime information among the cluster nodes. For example Caching can be used with runtime state sharing.

+ +

Runtime state replication is based on the Tribes group management system. It + provides group membership handling and group communication for clustered Carbon Server + instances. Although ESB ships with this built in Tribes based + implementation, other clustering implementations based on different group + management systems can be plugged in easily. The only thing you have to do is + to implement a set of clustering interfaces provided by Carbon Server.

+ +

+ +

ESB clustering currently does not support distributed locking for session + data replication. Therefore, we have to deploy primary backup clusters for + stateful services. This restriction does not apply to + stateless services and you can direct client requests to any node in the + cluster for such services.

+ +

+ +

ESB State Replication + Configuration

+ +

ESB clustering is configured using the axis2.xml file. So you have to + enable clustering in the axis2.xml of each node.

+

+ For more details about Carbon Server clustering, please see + + WSO Carbon Clustering Configuration Language + . +

+

NWe can enable clustering by changing the configuration in the axis2.xml. By default, clustering is + turned off to avoid additional overhead for individual deployments. Open + the axis2.xml and set the value 'true' for the "enable" attribute + of the "clustering" element as follows.

+ +
+              <clustering class="org.apache.axis2.clustering.tribes.TribesClusteringAgent" enable="true">
+          
+ +

You may also change clustering properties to suit your deployment as explianed + in the above article. However, the default configuration is sufficient for + the demonstration.

+ +

+ Other Resources +

+

+

+ The WSO2 Oxygen Tank + Library : The Library contains articles, tutorials, + presentations, and other knowledge base items published on The Oxygen + Tank on different styles of deployments. +

+ + diff --git a/docs/xdoc/docs_index.xml b/docs/xdoc/docs_index.xml new file mode 100644 index 0000000000..ab030e7e69 --- /dev/null +++ b/docs/xdoc/docs_index.xml @@ -0,0 +1,151 @@ + + + + + + + + + WSO2 ESB - Documentation Index + + + + + +

+ WSO2 Enterprise Service Bus (ESB) Documentation Index +

+

+ Getting Started +

+

+ Installation Guide : Gives + basic steps on how to download, install, and run WSO2 ESB using the binary + distribution, and how to build WSO2 ESB using the source distribution. +

+

+ Quick Start Guide : + Demonstrates two sample applications covering the basic and the most + common usage scenarios of the WSO2 ESB - Message mediation and Service + mediation. +

+

+ User Guide : A + manual on how to run and configure the WSO2 ESB through the management + console. Descriptions include how to manage the underlying Synapse + configuration elements and the integrated registry, and how to interpret + statistics generated by the system. +

+

+ Administrator Guide : A + manual on how to administrate and configure the WSO2 ESB through the management + console. Descriptions on advanced configurations like Remote/Embedded Registry + configuration, adding external libraries, Key store & User management. Briefly + describes the performance tunning the ESB as well. +

+

+ Deployment Guide : A + manual on how to deploy the WSO2 ESB on different Application Servers, including the + configuration that are required to setup the ESB on those Application Servers. +

+

+ Samples +

+

+ Samples Setup Guide : + Provides step-by-step instructions on how to install the prerequisites, + and set up the samples given in this distribution - generic instructions + on how to start the sample server, deploy a service, and run the client. +

+

+ How to Run the WSO2 ESB Samples : + While the document above gives you a generic description on how to set up + and and run the WSO2 ESB samples, this document takes each sample, one by + one and discusses the objective of the sample, its prerequisites, and its + expected behavior when the sample is built. +

+

+ Advanced Topics +

+

+ Extending Synapse : Explains how + to write custom mediator implementations and custom configuration + implementations for mediators by extending Apache Synapse through WSO2 + ESB. It also provides guidelines on how to configure these mediators. +

+

+ Synapse Configuration + Language : Describes the configuration language used by the + underlying Synapse mediation engine. This document is provided only as a + reference, as the WSO2 ESB management console allows users to configure + the underlying engine graphically, through the management console +

+

+ Secure Vault : Describes how you can + keep the secret information securely within the WSO2 ESB. You can secure any secret + including the passwords, keys or pass phrases. +

+

+ Transactions : Describes the transaction support in WSO2 + ESB. This guide contains information on using transaction mediator(which adds the distributed transaction + support) and also JMS transactions(local and distributed JMS transactions support) in WSO2 ESB. +

+

Catalogs

+

+ Mediator Catalog : Comprehensive catalog of all the + available default mediators in the WSO2 ESB 4.0.0. +

+

+ Endpoint Catalog : Comprehensive catalog of all the + available default endpoints in the WSO2 ESB 4.0.0. +

+

+ Transport Catalog : Comprehensive catalog of + all the available default transports in the WSO2 ESB 4.0.0. +

+

+ Other Resources +

+

+ Frequently Asked Questions : Contains a set of FAQ's on WSO2 ESB, and + the related Axis2, Synapse components. +

+

+ WSO2 ESB Features : Gives a high + level overview of the features pf the WSO2 ESB. +

+

+ Java Docs : Application + Programing Interface of the Apache Synapse version used underneath the WSO2 ESB. If you want + to write advanced custom mediators, you will need this API. +

+

+ External articles : A collection of external articles published on WSO2 + ESB. +

+

+ The WSO2 Oxygen Tank + Library : The Library contains articles, tutorials, + presentations, and other knowledge base items published on The Oxygen + Tank. +

+ + diff --git a/docs/xdoc/endpoint_guide.xml b/docs/xdoc/endpoint_guide.xml new file mode 100644 index 0000000000..f3635eeaaf --- /dev/null +++ b/docs/xdoc/endpoint_guide.xml @@ -0,0 +1,550 @@ + + + + + + + + WSO2 ESB - Endpoint Catalog + + + + + + + + [ Documentation Index ] +

WSO2 Enterprise Service Bus (ESB) Endpoint Catalog

+

The endpoints catalog wlks you through the endpoints which are there inside the WSO2 ESB. +This will cover the very basics of the endpoints and dive deeper in to the configurtion details and +the technical implementation details as well

+ +

Contents

+ +

Endpoints - Introduction

+

An endpoint +defines an external destination for an outgoing message through WSO2 +ESB. An <endpoint> element defines an endpoint in the +configuration. An endpoint may be specified as an address endpoint, WSDL based endpoint, a load +balancing endpoint or a fail-over endpoint as follows: +

+ +
+    <endpoint [name="string"] [key="string"]>
+        address-endpoint | default-endpoint | wsdl-endpoint | load-balanced-endpoint | fail-over-endpoint
+    </endpoint>
+
+

+All the types of endpoints can have a name attribute which specify the name of the endpoint and such named endpoints + can be referred by other endpoints using a key attribute. For example if there is an endpoint named as "foo", +the following endpoint can be used in any place, where "foo" has to be used. +

+ +
+    <endpoint key="foo"/>
+
+

This let the users to reuse the already defined endpoints in several places.

+

The endpoints also have a trace attribute which turns on detailed trace information for messages being sent to the + endpoint. These are available in the trace.log configured via the log4j.properties file(which can be found within + lib folder once you unzip wso2 ESB zip). Setting the trace log level to TRACE will dump detailed trace information + including message payloads. +

+

+At any given time an endpoint can be one of the following four states.

+ +

[1] Active - Endpoint is active and running.

+

[2] TimeOut - The endpoint can be in TimeOut state if + we get a timeout error when invoking the endpoint (because the endpoint is currently unavailable or due to a + network failure) or if it returns a previously defined error code for timeout state, the endpoint said to be in + TimeOut state. The possible error codes can be found in the SynapseConstant class (under the endpoint failure section). A timed out endpoint is a candidate for a suspenstion. + The configuration related to marking an endpoint for suspension is given by markForSuspension.If the configuration + does have a positive retrieve count (see the configuration section below) the endpoint will be retrieve again + (the number of time to retrieve can be configured using the same configuration element) and if it fails in further attempts it will transfer + into Suspended state.

+

[3] Suspended - When invoking the endpoint if a previously defined error code for Suspended state is returned + or a if a TimeOut endpoint fails in further attempts the endpoint is said to be in Suspended state. + The endpoint can goes into Active state once the suspend duration is over. The configuration section + called suspendOnFailure.

+

[4] Switch Off - The endpoint is moved into maintains mode. +

+ +

+A state transfer between any state to Switch off state can be done only manually using JMX based API. + And also an endpoint which is in SwitchOff state can only transfer into Active state again using + the JMX based API. See section on using JMX based API to learn how to do this. +

+ +

+The state transition between states can be shown as follows. +

+ +
endpoint-state-image
+

Figure1: The state transition between states in an endpoint

+ +

Using jconsole to manage state transition between states

+ +

The jconsole tool is a JMX-compliant graphical tool for monitoring a Java virtual machine. If you have installed + java you'll automatically get this tool. We'll add an endpoint (name 'ep1') and monitor the states transition + between states in ep1 +

+ +

1. Add an address endpoint called 'ep1'. Refer endpoint userguide to see how this can be done.

+

2. Start jconsole by typing jconsole at your termnial, if you encounter any problem please consult your operatying + system guide. You'll see the following console once you select Mbeans tab.

+ +
jconsole-mbean-tab
+ +

Figure2: Jconsole Mbeans tab

+

3.Go to org.apache.synpase menu from left hand and expand it. You'll see the following figure with the + endpoint ep1 that we just added. +

+ +
endpoint-mbean-show
+

Figure3: Endpoint Mbean is selected

+ +

4. Select the ep1 endpoint and you'll see the information related to this endpoint and please note that the state + is given as active as the first entry and value is set to true. The endpoint is in active state. +

+
endpoint-information-image
+

Figure4: The ep1 endpoint attributes. The endpoint is active.

+ +

5. Now go to the Operations tab and switch off the endpoint. You'll see a message saying the + operation was successful. +

+
endpoint-off-image
+

Figure5: Switching off the endpoint.

+ +

You'll also see a INFO level log message saying that the endpoint was switched off manually.

+ +

[2009-06-23 12:18:21,149] INFO - EndpointContext Manually switching off endpoint : ep1

+ +

6. Next again switch back to Attributes tab and see the state of the endpoint after refreshing it. You'll see + endpoint is inactive and the endpoint is in switch off state. At this point if you try to use a client which + use this endpoint you'll see it fails since the endpoint is down. You can use a similar approach activate the + endpoint back. +

+ +
endpoint-switched-off-image
+

Figure6: Endpoint is in Switch off state.

+ +

Address Endpoint

+

Address endpoint is an endpoint defined by specifying the EPR (Endpoint Reference) and other attributes + of the configuration.

+ +

Address endpoint configuration

+ +
+<address uri="endpoint address" [format="soap11|soap12|pox|get"] [optimize="mtom|swa"]
+    [encoding="charset encoding"]
+    [statistics="enable|disable"] [trace="enable|disable"]>
+
+    <enableRM [policy="key"]/>?
+    <enableSec [policy="key"]/>?
+    <enableAddressing [version="final|submission"] [separateListener="true|false"]/>?
+
+    <timeout>
+        <duration>timeout duration in milliseconds</duration>
+        <action>discard|fault</action>
+    </timeout>?
+
+    <markForSuspension>
+        [<errorCodes>xxx,yyy</errorCodes>]
+        <retriesBeforeSuspension>m</retriesBeforeSuspension>
+        <retryDelay>d</retryDelay>
+    </markForSuspension>
+
+    <suspendOnFailure>
+        [<errorCodes>xxx,yyy</errorCodes>]
+        <initialDuration>n</initialDuration>
+        <progressionFactor>r</progressionFactor>
+        <maximumDuration>l</maximumDuration>
+    </suspendOnFailure>
+</address>
+
+ +

Address endpoint attributes

+
+ + + + + + +
uri
EPR of the target endpoint. + See the table below for a possible list of transports.
format
Message format for the endpoint.
optimize
Method to optimize the attachments.
encoding
The charset encoding to use for the endpoint.
statistics
This enables statistics for the endpoint.
trace
This enables trace for the endpoint.
+ +

QoS for the endpoint

+

QoS (Quility of service) aspects such as WS-RM(WS-Reliable messaging), WS-Security and WS-Addressing may be + enabled on messages send to an endpoint using enableRM, enableSec and enableAddressing + elements. Optionally, the WS-RM and WS-Security policies could be specified using policy attribute. +

+

QoS configuration

+ +
+ + + + +
enableRM [policy="key"]
This enables WS-Reliable messaging + for the message which goes for the endpoint. The optional policy attribute specify the WS-RM + policy.
enableSec [policy="key"]
This enables WS-Security for + the message which goes for the endpoint. The optional policy attribute specify the WS-Security + policy.
enableAddressing [version="final | submission"] [seperateListener=" true | false"]
+
This enables WS-Addressing for the message which goes for the endpoint. User can specify + to have seperate listener with version final or submission.
+ +

Endpoint timeout

+

Address(and also WSDL) endpoints can timeout if the response fails to arrive at Synapse by a predefined + timeout duration specified in seconds. The timeout action specifies whether to discard reponse that arives + later, or to trigger a fault. Synapse has a periodic timeout handler that triggers itself at each 15 seconds + interval. Thus endpoint timeout will have a +/- erroce on trigger time. Though this can be minimized by + setting a System property "synapse.timeout_handler_interval"(This property can be set in synapse.properties + synpase property file which is located in conf directory inside repository once you unzipped WSO2 ESB ) + to a millisecond duration below the desired endpoint timeout, care must be taken as a lesser value may have a + higher overhead on the system.

+ +

timeout configuration

+
+ + + +
duration
Timeout duration in millisecond.
action
Once a timeout occurs the action to perform, avilable + options are discard (discard the response which arrives late) or fault (trigger a fault) + .
+ +

Marking endpoint for suspension

+

As described before (see description on Timeout state above) this configuration element describes the configuration + for a timeout endpoint. +

+

markForSuspension configuration

+
+ + + +
errorCodes
A comma separated error code list which can be + returned by the endpoint. See SynpaseConstant class for a possible list of error codes.
retriesBeforeSuspensionNumber of retries before go into suspended + state.
retryDelayThe delay between each try.
+

Suspending endpoint on failure

+

Leaf endpoints(Address and WSDL) endpoint can be put into suspended state if it is detected as failed. An endpoint that + fails may be suspended for a specified duration after such a failure, during which new messages will not be + processed through the endpoint. The amount of time waiting before next attempt follows the following formula. +
+ next suspension time period = Max (Initial Suspension duration * (progression factor try count), Maximum Duration)
+ + All the variables in the above formula are configuration values used to calculate the try count. Try count means, + how many tries occurred after the endpoint is SUSPENDED. As the try count increases, the next SUSPENSION time + period will also increase. This increase is bound to a maximum duration.
+

+ +

suspendOnFailure configuration

+
+ + + + + + + + + + + + + + + + + + + +
errorCode
+
A comma separated error code list which can be returned by the endpoint. See SynpaseConstant class for a possible list of error codes.
+
+initialDuration +Initial duration(in milliseconds) to suspend the endpoint.
+
+progressionFactor +The progression factor for the geometric series. See above for a more detailed description.
+
+maximumDuration +Maximum duration(in milliseconds) to suspend the endpoint.
+
+
+ +

Following are the sample address URI definitions.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
Transport
+
Sample Address
+
HTTP
+
http://localhost:9000/services/SimpleStockQuoteService
JMS
+
jms:/SimpleStockQuoteService?
+ transport.jms.ConnectionFactoryJNDIName=QueueConnectionFactory&
+ java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&
+ java.naming.provider.url=tcp://localhost:61616&
+ transport.jms.DestinationType=topic
Mail
+
mailto:guest@host
VFS
+
vfs:file:///home/user/directory
+ vfs:file:///home/user/file
+ vfs:ftp://guest:guest@localhost/directory?vfs.passive=true +
FIX
+
fix://host:port?BeginString=FIX4.4&SenderCompID=WSO2&TargetCompID=APACHE
+
+
+
+ +

Default Endpoint

+

Default endpoint is an endpoint defined for adding QoS and other configurations + to the endpoint which is resolved from the 'To' address of the message context. + All the configurations such as message format for the endpoint, the method + to optimize attachments, reliable messaging, security policies for the endpoint + can be specified as in the Address Endpoint. This endpoint differs from the address + endpoint only in the uri attribute which will not be present in this endpoint. + Following section describes the configuration of a default endpoint.

+

Default endpoint configuration

+
+<default [format="soap11|soap12|pox|get"] [optimize="mtom|swa"]
+     [encoding="charset encoding"]
+     [statistics="enable|disable"] [trace="enable|disable"]>
+
+    <enableRM [policy="key"]/>?
+    <enableSec [policy="key"]/>?
+    <enableAddressing [version="final|submission"] [separateListener="true|false"]/>?
+
+    <timeout>
+        <duration>timeout duration in milliseconds</duration>
+        <action>discard|fault</action>
+    </timeout>?
+
+    <markForSuspension>
+        [<errorCodes>xxx,yyy</errorCodes>]
+        <retriesBeforeSuspension>m</retriesBeforeSuspension>
+        <retryDelay>d</retryDelay>
+    </markForSuspension>
+
+    <suspendOnFailure>
+        [<errorCodes>xxx,yyy</errorCodes>]
+        <initialDuration>n</initialDuration>
+        <progressionFactor>r</progressionFactor>
+        <maximumDuration>l</maximumDuration>
+    </suspendOnFailure>
+</default>
+
+ +

WSDL endpoint

+

WSDL endpoint is an endpoint definition based on a specified WSDL document. The WSDL document can be specified + either as a URI or as an inlined definition within the configuration. The service and port name + containing the target EPR has to be specified with the 'service' and 'port' (or 'endpoint') attributes + respectively. enableRM, enableSec, enableAddressing, suspendDurationOnFailure and timeout elements are same + as for an Address endpoint.

+ +

WSDL endpoint configuration

+
+<wsdl [uri="wsdl-uri"] service="qname" port/endpoint="qname">
+    <wsdl:definition>...</wsdl:definition>?
+    <wsdl20:description>...</wsdl20:description>?
+    <enableRM [policy="key"]/>?
+    <enableSec [policy="key"]/>?
+    <enableAddressing/>?
+
+    <timeout>
+        <duration>timeout duration in milliseconds</duration>
+        <action>discard|fault</action>
+    </timeout>?
+
+    <markForSuspension>
+        [<errorCodes>xxx,yyy</errorCodes>]
+        <retriesBeforeSuspension>m</retriesBeforeSuspension>
+        <retryDelay>d</retryDelay>
+    </markForSuspension>
+
+    <suspendOnFailure>
+        [<errorCodes>xxx,yyy</errorCodes>]
+        <initialDuration>n</initialDuration>
+        <progressionFactor>r</progressionFactor>
+        <maximumDuration>l</maximumDuration>
+    </suspendOnFailure>
+</wsdl>
+
+ +

Load balance Endpoint

+

A Load balanced endpoint distributes the messages (load) arriving at it + among a set of listed endpoints or static members by evaluating the load balancing policy + and any other relevant parameters. The policy attribute of the load balance + element specifies the load balance policy (algorithm) to be used for + selecting the target endpoint or static member. Currently only the roundRobin policy is + supported. The failover attribute determines if the next endpoint or static member should be + selected once the currently selected endpoint or static member has failed, and defaults to + true. The set of endpoints or static members amongst which the load has to be distributed + can be listed under the 'loadBalance' element. These endpoints can belong to any + endpoint type mentioned in this document. For example, failover endpoints + can be listed inside the load balance endpoint to load balance between + failover groups etc. The loadbalance element cannot have both endpoint & member child + elements in the same configuration. In the case of the member child element, the hostName, + httpPort and/or httpsPort attributes could be specified.

+

+ The optional 'session' element makes the endpoint a session affinity based + load balancing endpoint. If it is specified, sessions are bound to + endpoints in the first message and all successive messages for those + sessions are directed to their associated endpoints. Currently there are two types + of sessions supported in SAL endpoints. Namely HTTP transport based session + which identifies the sessions based on http cookies and the client session which + identifies the session by looking at a SOAP header sent by the client with the QName + '{http://ws.apache.org/ns/synapse}ClientID'. The 'failover' attribute mentioned above + is not applicable for session affinity based endpoints and it is always + considered as set to false. If it is required to have failover behavior in session + affinity based load balance endpoints, list failover endpoints as the target endpoints. +

+ +

Load balance endpoint configuration

+
+<session type="http|simpleClientSession"/>?
+<loadBalance [policy="roundRobin"] [algorithm="impl of org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm"]
+        [failover="true|false"]>
+    <endpoint .../>+
+    <member hostName="host" [httpPort="port"] [httpsPort="port2"]>+
+</loadBalance>
+
+ + +

Failover Endpoint

+

Failover endpoints send messages to the listed endpoints with the following failover behavior. At the start, the + first listed endpoint is selected as the primary and all other endpoints are treated as backups. + Incoming messages are always sent only to the primary endpoint. If the primary endpoint fails, + next active endpoint is selected as the primary and failed endpoint is marked as inactive. + Thus it sends messages successfully as long as there is at least one active endpoint among the listed + endpoints.

+ +

Failover endpoint configuration

+
+<failover>
+    <endpoint .../>+
+</failover>
+
+ +

Dynamic Load balance Endpoint

+

A Dynamic Load balanced endpoint distributes the messages (load) arriving at it among a application members by + evaluating the load balancing policy and any other relevant parameters. These application members will be + discovered using the membershipHandler class. Generally, this class will use a group communication mechanism + to discover the application members. The class attribute of the membershipHandler element should be an + implementation of org.apache.synapse.core.LoadBalanceMembershipHandler. membershipHandler specific properties + can be specified using the property elements. The policy attribute of the dynamicLoadbalance element specifies + the load balance policy (algorithm) to be used for selecting the next member to which the message has to be + forwaded to. Currently only the roundRobin policy is supported. The failover attribute determines if the next + member should be selected once the currently selected member has failed, and defaults to true.

+

Dynamic Load balance endpoint configuration

+
+  <dynamicLoadBalance [policy="roundRobin"] [failover="true|false"]>
+    <membershipHandler class="impl of org.apache.synapse.core.LoadBalanceMembershipHandler">
+      <property name="name" value="value"/>
+    </membershipHandler>
+  </dynamicLoadBalance>
+
+ + + \ No newline at end of file diff --git a/docs/xdoc/extensions_guide.xml b/docs/xdoc/extensions_guide.xml new file mode 100644 index 0000000000..08ba706a71 --- /dev/null +++ b/docs/xdoc/extensions_guide.xml @@ -0,0 +1,890 @@ + + + + + + + + + + WSO2 ESB - Extending + + + + + + + [ Documentation Index ] +

+ Extending WSO2 Enterprise Service Bus (ESB) +

+

+ This document explains how to write custom mediator implementations and + custom configuration implementations for mediators by extending Apache + Synapse through WSO2 ESB. It also provides guidelines on how to configure + these mediators. +

+

Contents

+ +

+ Writing Custom Mediator Implementations +

+

+ The primary interface of the Synapse API is the MessageContext interface + defined below. This essentially defines the per-message context passed + through the chain of mediators, for each and every message received and + processed by Synapse. Each message instance is wrapped within a + MessageContext instance, and the message context is set with the + references to the SynapseConfiguration and SynapseEnvironments. The + SynapseConfiguration holds the global configuration model that defines + mediation rules, local registry entries and other configuration, while + the environment gives access to the underlying SOAP implementation used - + Apache Axis2. A typical mediator would need to manipulate the + MessageContext by referring to the SynapseConfiguration. However, it is + strongly recommended that the SynapseConfiguration is not updated by + mediator instances as it is shared by all messages, and may be updated by + Synapse administration or configuration modules. Mediator instances may + store local message properties into the MessageContext for later retrieval + by successive mediators. Extending the AbstractMediator class is the + easiest way to write a new mediator, than implementing the Mediator + interface. +

+

+ MessageContext + Interface +

+

+

package org.apache.synapse;
+
+import ...
+
+public interface MessageContext {
+
+    /**
+     * Get a reference to the current SynapseConfiguration
+     *
+     * @return the current synapse configuration
+     */
+    public SynapseConfiguration getConfiguration();
+
+    /**
+     * Set or replace the Synapse Configuration instance to be used. May be used to
+     * programmatically change the configuration at runtime etc.
+     *
+     * @param cfg The new synapse configuration instance
+     */
+    public void setConfiguration(SynapseConfiguration cfg);
+
+    /**
+     * Returns a reference to the host Synapse Environment
+     * @return the Synapse Environment
+     */
+    public SynapseEnvironment getEnvironment();
+
+    /**
+     * Sets the SynapseEnvironment reference to this context
+     * @param se the reference to the Synapse Environment
+     */
+    public void setEnvironment(SynapseEnvironment se);
+
+    /**
+     * Get the value of a custom (local) property set on the message instance
+     * @param key key to look up property
+     * @return value for the given key
+     */
+    public Object getProperty(String key);
+
+    /**
+     * Set a custom (local) property with the given name on the message instance
+     * @param key key to be used
+     * @param value value to be saved
+     */
+    public void setProperty(String key, Object value);
+
+    /**
+     * Returns the Set of keys over the properties on this message context
+     * @return a Set of keys over message properties
+     */
+    public Set getPropertyKeySet();
+
+    /**
+     * Get the SOAP envelope of this message
+     * @return the SOAP envelope of the message
+     */
+    public SOAPEnvelope getEnvelope();
+
+    /**
+     * Sets the given envelope as the current SOAPEnvelope for this message
+     * @param envelope the envelope to be set
+     * @throws org.apache.axis2.AxisFault on exception
+     */
+    public void setEnvelope(SOAPEnvelope envelope) throws AxisFault;
+
+    /**
+     * SOAP message related getters and setters
+     */
+    public ....get/set()...
+
+}
+

+ The MessageContext interface is based on the Axis2 MessageContext + interface, and it uses the Axis2 EndpointReference and + SOAPEnvelope classes/interfaces. The purpose of this interface is to + capture a message as it flows through the system. As you will see the + message payload is represented using the SOAP infoset. Binary messages can + be embedded in the Envelope using MTOM (SOAP Message Transmission + Optimization Mechanism) or SwA (SOAP with Attachments) using the AXIOM + (AXis Object Model) object model. +

+

+ Mediator + Interface +

+

+ The second key interface for mediator writers is the Mediator interface: +

+
package org.apache.synapse;
+
+import org.apache.synapse.MessageContext;
+
+/**
+ * All Synapse mediators must implement this Mediator interface. As a message passes
+ * through the synapse system, each mediator's mediate() method is invoked in the
+ * sequence/order defined in the SynapseConfiguration.
+ */
+public interface Mediator {
+
+    /**
+     * Invokes the mediator passing the current message for mediation. Each
+     * mediator performs its mediation action, and returns true if mediation
+     * should continue, or false if further mediation should be aborted.
+     *
+     * @param synCtx the current message for mediation
+     * @return true if further mediation should continue
+     */
+    public boolean mediate(MessageContext synCtx);
+
+    /**
+     * This is used for debugging purposes and exposes the type of the current
+     * mediator for logging and debugging purposes
+     * @return a String representation of the mediator type
+     */
+    public String getType();
+
+    /**
+     * This is used to check whether the tracing should be enabled on the current mediator or not
+     * @return value that indicate whether tracing is on, off or unset
+     */
+    public int getTraceState();
+
+    /**
+     * This is used to set the value of tracing enable variable
+     * @param traceState Set whether the tracing is enabled or not
+     */
+    public void setTraceState(int traceState);
+}
+

+ A mediator can read and/or modify the SynapseMessage in + any suitable manner - adjusting the routing headers or changing the + message body. If the mediate() method returns false, it signals to the + Synapse processing model to stop further processing of the message. For + example, if the mediator is a security agent it may decide that this + message is dangerous and should not be processed further. This is + generally the exception as mediators are usually designed to co-operate to + process the message onwards. +

+

+ Leaf and Node Mediators, List Mediators and Filter Mediators +

+

+ Mediators may be Node mediators (i.e. these that can contain child + mediators) or Leaf mediators (mediators that does not hold any other child + mediators). A Node mediator must implement the + org.apache.synapse.api.ListMediator interface listed below, or extend from + the org.apache.synapse.mediators.AbstractListMediator. +

+

+ The + ListMediator Interface +

+
package org.apache.synapse.mediators;
+
+import java.util.List;
+
+/**
+* The List mediator executes a given sequence/list of child mediators
+*/
+public interface ListMediator extends Mediator {
+    /**
+    * Appends the specified mediator to the end of this mediator's (children) list
+    * @param m the mediator to be added
+    * @return true (as per the general contract of the Collection.add method)
+    */
+    public boolean addChild(Mediator m);
+
+    /**
+    * Appends all of the mediators in the specified collection to the end of this mediator's (children)
+    * list, in the order that they are returned by the specified collection's iterator
+    * @param c the list of mediators to be added
+    * @return true if this list changed as a result of the call
+    */
+    public boolean addAll(List c);
+
+    /**
+    * Returns the mediator at the specified position
+    * @param pos index of mediator to return
+    * @return the mediator at the specified position in this list
+    */
+    public Mediator getChild(int pos);
+
+    /**
+    * Removes the first occurrence in this list of the specified mediator
+    * @param m mediator to be removed from this list, if present
+    * @return true if this list contained the specified mediator
+    */
+    public boolean removeChild(Mediator m);
+
+    /**
+    * Removes the mediator at the specified position in this list
+    * @param pos the index of the mediator to remove
+    * @return the mediator previously at the specified position
+    */
+    public Mediator removeChild(int pos);
+
+    /**
+    * Return the list of mediators of this List mediator instance
+    * @return the child/sub mediator list
+    */
+    public List getList();
+}
+

+ A ListMediator implementation should call super.mediate(synCtx) to process + its sub mediator sequence. A FilterMediator is a ListMediator which + executes its sequence of sub mediators on successful outcome of a test + condition. The Mediator instance which performs filtering should implement + the FilterMediator interface. +

+

+ FilterMediator + Interface +

+
package org.apache.synapse.mediators;
+
+import org.apache.synapse.MessageContext;
+
+/**
+ * The filter mediator is a list mediator, which executes the given (sub) list of mediators
+ * if the specified condition is satisfied
+ *
+ * @see FilterMediator#test(org.apache.synapse.MessageContext)
+ */
+public interface FilterMediator extends ListMediator {
+
+    /**
+     * Should return true if the sub/child mediators should execute. i.e. if the filter
+     * condition is satisfied
+     * @param synCtx
+     * @return true if the configured filter condition evaluates to true
+     */
+    public boolean test(MessageContext synCtx);
+}
+

+ Writing Custom Configuration Implementations for Mediators +

+

+ You may write your own custom configurator for the Mediator implementation + you write without relying on the Class mediator or Spring extension for + its initialization. You could thus write a MediatorFactory implementation + which defines how to digest a custom XML configuration element to be used + to create and configure the custom mediator instance. A MediatorSerializer + implementation defines how a configuration should be serialized back into + an XML configuration. The custom MediatorFactory and MediatorSerializer + implementations and the mediator class/es must be bundled as a "Synapse-Core" fragment bundle, + which exporting these classes (See the description for Extensions below for more + details and examples) and placed into the ESB_HOME/repository/components/dropins + folder, so that the Synapse runtime could find and load the definition. +

+

+ For eg: Your MANIFEST.MF file will look like; +

+
+	Bundle-Name: surcharge-stock-quote-mediator
+	Created-By: Apache Maven Bundle Plugin
+	DynamicImport-Package: *
+	Fragment-Host: synapse-core
+	Build-Jdk: 1.6.0_20
+	Bundle-Version: 1.0.0
+	Bnd-LastModified: 1322212580393
+	Bundle-ManifestVersion: 2
+	Bundle-Description: Tutorial
+	Bundle-SymbolicName: surcharge-stock-quote-mediator
+	Import-Package: javax.xml.namespace;version="0.0.0",org.apache.axiom.o
+	m;resolution:=optional,org.apache.axiom.om.xpath;resolution:=optional
+	,org.apache.axiom.soap;resolution:=optional,org.apache.commons.loggin
+	g;resolution:=optional,org.apache.synapse;resolution:=optional,org.ap
+	ache.synapse.config.xml;resolution:=optional,org.apache.synapse.media
+	tors;resolution:=optional,org.jaxen;resolution:=optional,org.wso2.esb
+	.tutorial.mediators;resolution:=optional
+	
+

+ Essentially this means that a custom JAR file must bundle your classes + implementing the Mediator interface, MediatorSerializer and the MediatorFactory + interfaces. It should also contain two text files named + "org.apache.synapse.config.xml.MediatorFactory" and + "org.apache.synapse.config.xml.MediatorSerializer" which will contain the + fully qualified name(s) of your MediatorFactory and MediatorSerializer + implementation classes. Any dependencies should be made available through OSGi + bundles in the same plugins directory. +

+ +

Note: + However there is a limitation with this custom mediators. Currently ESB supports them as + fragments of synapse-core, since that custom mediators can not own their Activator classes. + So,they can not override the information present in the host bundle, which is the synapse-core. +

+ +

+ The MediatorFactory interface listing is given below, which you should + implement, and its getTagQName() method must define the fully qualified + element of interest for custom configuration. The Synapse initialization + will call back to this MediatorFactory instance through the + createMediator(OMElement elem) method passing in this XML element, so that + an instance of the mediator could be created utilizing the custom XML + specification and returned. See the ValidateMediator and the + ValidateMediatorFactory classes under modules/extensions in the Synapse + source distribution for examples. +

+

+ The + MediatorFactory Interface +

+
package org.apache.synapse.config.xml;
+
+import ...
+
+/**
+ * A mediator factory capable of creating an instance of a mediator through a given
+ * XML should implement this interface
+ */
+public interface MediatorFactory {
+    /**
+     * Creates an instance of the mediator using the OMElement
+     * @param elem
+     * @return the created mediator
+     */
+    public Mediator createMediator(OMElement elem);
+
+    /**
+     * The QName of this mediator element in the XML config
+     * @return QName of the mediator element
+     */
+    public QName getTagQName();
+}
+

+

+ The + MediatorSerializer Interface +

+
package org.apache.synapse.config.xml;
+
+import ...
+
+/**
+ * Interface which should be implemented by mediator serializers. Does the
+ * reverse of the MediatorFactory
+ */
+public interface MediatorSerializer {
+
+    /**
+     * Return the XML representation of this mediator
+     * @param m mediator to be serialized
+     * @param parent the OMElement to which the serialization should be attached
+     * @return the serialized mediator XML
+     */
+    public OMElement serializeMediator(OMElement parent, Mediator m);
+
+    /**
+     * Return the class name of the mediator which can be serialized
+     * @return the class name
+     */
+    public String getMediatorClassName();
+}
+

+ Configuring Mediators +

+

+ Mediators could access the Synapse registry to load resources and + configure the local behaviour. Refer to the Spring mediator and Script + mediator implementations for examples on how this could be achieved. +

+

+ Loading of Extensions by the Synapse Runtime +

+

+ Synapse loads available extensions from the runtime classpath using the J2SE + Service Provider model. This essentially iterates over the + available JAR files, for a META-INF/services directory within each file, + and looks for text files with the name + org.apache.synapse.config.xml.MediatorFactory and org.apache.synapse.config.xml.MediatorSerializer + which contains a list of fully qualified class name that implement the above interface, listing each + class in a separate line. For example, the built-in synapse-extensions.jar + contains the following structure: +

+
synapse-extensions.jar
+    /META-INF/services
+        org.apache.synapse.config.xml.MediatorFactory
+        org.apache.synapse.config.xml.MediatorSerializer
+    /... the implementation classes as usual...
+ + +

Scheduled Tasks

+ +

+ +

Task is a one of method to automatically driving the mediation in the ESB. +This is an implementation of ESB Startup which allowed adding tasks should run +at ESB startup. Task is a Startup and it is based on Quartz, an open source job +scheduling system. Task can be used to create simple or complex schedules. A +simple schedule may be a schedule to run a task periodically. A complex +schedule may be a schedule to run at specific time in future. A complex +schedule can be specified using cron expressions.

+ +

+
<task class="string" name="string" [group="string"] [pinnedServers="(serverName)+"]>
+       <property name="string" value="String"/>
+       <property name="string"><somexml>config</somexml></property>
+       <trigger ([[count="int"]? interval="int"] | [cron="string"] | [once=(true | false)])/>
+</task>
+ +

+ +

A task is created and scheduled to run at specified time intervals or as +specified by the cron expression. The Task class specifies the actual task +implementation class

+ +

(which must implement +org.apache.synapse.task.Taskinterface) to be +executed at the specified interval/s, and name specifies an identifier for the +scheduled task.

+ +

In the current ESB , there is only one implementation - +org.apache.synapse.startup.tasks.MessageInjector.This can be +used to inject messages at ESB startup.

+ +

+ +

Fields in the task class can be set using properties provided as string +literals or as XML fragments. (For example; if the task implementation class +has a field named "version" with a corresponding setter method, the +configuration value which will be assigned to this field before running the +task can be specified using a property with the name 'version')

+ +

+ +

There are three different trigger mechanisms to schedule tasks. A simple +trigger is specified specifying a 'count' and an 'interval', implying that the +task will run a 'count' number of times at specified intervals. A trigger may +also be specified as a cron trigger using a cron expression. A one-time trigger +is specified using the 'once' attribute as true in the definition and could be +specified as true in which case this task will be executed only once just after +the initialization of ESB. You can give a list of Synapse server names where +this task should be started using pinnedServers attribute. Refer to the +explanation of this attribute under proxy services for more information.

+ +

+ +

Extending Task

+ +

A custom Task can be developed by writing a custom Java class that +implements the org.apache.synapse.task.Task interface. Task +interface is shown bellow.

+ +

+
package org.apache.synapse.task;
+
+/*** Represents an executable Task*/
+
+public interface Task {
+
+   /*** Execute method will be invoked by the QuartzJOb.
+   */
+   public void execute();
+
+}
+ +

+ Xpath Extension Framework +

+

+ WSO2 ESB configuration language is a powerful and flexible tool to perform + authentication, validation, transformation, logging, routing based on the content etc. + It could be easily extended, with configuration extensions , mediation extensions and + even expression level extension. An expression is a lowest level particle in the + synapase configuration. To be precise , unlike static values ,expressions can be used to + define dynamically extracted values (using xpath) in a configuration. + Mediators extensively uses expressions to extract properties from message context. + Expression is defined under attribute "expression" of a particular configuration. (see + property/header/iterator mediator ) .Although expressions can be purely xpath , synapse + allows extensions to define extended expressions as well. These special xpath expressions + can be two fold , that is , +

+
+            1.xpath variable expressions
+            2.xpath function expressions
+        
+

+ this allows us to access xpath variables with "$" . Currently there are several + predefined synapse xpath variables avaiable. +

+
+            Ie:- $body - message SOAP body
+            $header ? message SOAP header
+            $ctxt:SOME_PROPERTY ? a property belonging to synapse meessage context scope
+            $axis2:SOME_PROPERTY ? a property belonging to axis2 meessage context scope
+            $trp:SOME_TRANSPORT_HEADER ? a transport header
+        
+

+ Synapse get-property() is an example xpath function expressions. The get-property() + function allows any XPath expression used in a configuration to lookup information from + the current message context. Similar to above , It is possible to retrieve properties + previously set with the property mediator, and/or information from the Synapse or Axis2 + message contexts or transport header using get-property(). +

+

+ see synapse documentation for more details on usage of these expressions. + Xpath extension framework allows users to further extend xpath expressions to + suite user requirement. More specifically it allows users to define custom xpath + expressions and custom xpath functions that is required in a specific usecase + configuration scenario. Let's see how we can do this. We start by writng our HELLO_WORLD + custom xpath variable and hello-world() custom xpath function. +

+

+ Implementing HELLO_WORLD custom xpath variable +

+

+ Before going into implementation details , let me first define our final objective here. + What we need to do is to expose an HELLO_WORLD message in xml format to outside , so + that users would be able to access it using a xpath expression="$HELLOWORLD/...". + Following is the HELLO_WORLD mesasge we have. +

+
+            <HELLO_WORLD>
+            <name>WSO2-ESB</name>
+            <version>4.0.0</version>
+            <release_date>20/12/2010</release_date>
+            </HELLO_WORLD>
+        
+

Every custom xpath extension should implement + org.apache.synapse.util.xpath.ext.SynapseXpathVariableResolver interface to expose a + custom xpath variable. This interface consists of two methods , #getResolvingQName , + #resolve . First interface method is used to indicate the fully qualified + variable name that this extesion support (in our case it is HELLO_WORLD). Later method + should contain what ever resolving logic required to give the desired output.(in our + case it should return HELLO_WORLD element) . Following is the implementation of our + custom xpath variable HELLO_WORLD, +

+
+            package org.sample;
+
+            import org.apache.axiom.om.OMAbstractFactory;
+            import org.apache.axiom.om.OMElement;
+            import org.apache.axiom.om.OMFactory;
+            import org.apache.synapse.MessageContext;
+            import org.apache.synapse.util.xpath.ext.SynapseXpathVariableResolver;
+
+            import javax.xml.namespace.QName;
+
+            public class HelloWorldXpathVariableResolver implements SynapseXpathVariableResolver {
+
+            public static final QName HELLO_WORLD = new QName("HELLO_WORLD");
+
+            public Object resolve(MessageContext messageContext) {
+                //create Hello world message
+                OMFactory factory = OMAbstractFactory.getOMFactory();
+                OMElement helloWorldElement = factory.createOMElement(HELLO_WORLD);
+
+                OMElement nameElement = factory.createOMElement(new QName("name"));
+                nameElement.setText("synapse");
+                OMElement versionElem = factory.createOMElement(new QName("version"));
+                versionElem.setText("3.1.0");
+                OMElement releaseDateElem = factory.createOMElement(new QName("release_date"));
+                releaseDateElem.setText("12/12/2010");
+
+                helloWorldElement.addChild(nameElement);
+                helloWorldElement.addChild(versionElem);
+                helloWorldElement.addChild(releaseDateElem);
+
+                return helloWorldElement;
+            }
+
+            public QName getResolvingQName() {
+                //to support xpath expression="$HELLO_WORLD"
+                return HELLO_WORLD;
+            }
+
+            }
+        
+

+ with implementation in place mediators can refer version , name , release date on + HELLO_WORLD message using expression="$HELLO_WORLD/version" , etc +

+

+ Implementing hello-world() custom xpath function +

+

+ Having an xpath function extension is easy as implementing an xpath variable extension. + In this case Extension class should implement + org.apache.synapse.util.xpath.ext.SynapseXpathFunctionContextProvider . This interface + also do have methods , #getResolvingQName and #getInitializedExtFunction . First method + serves the same purpose as in the previous example. However later method should be + implementated in such a way that this extension should return a custom jaxen function to + synapse , initialized with synapse message context. It is extension developers + responsibility to provide a properly initialized xpath function so that it can be + resolved at runtime. Our sample implementation is shown below +

+
+            package org.sample;
+
+            import org.apache.synapse.MessageContext;
+            import org.apache.synapse.util.xpath.ext.SynapseXpathFunctionContextProvider;
+            import org.jaxen.Function;
+            import javax.xml.namespace.QName;
+
+            public class HelloWorldXpathFunctionProvider implements SynapseXpathFunctionContextProvider {
+
+            public Function getInitializedExtFunction(MessageContext messageContext) {
+                CustomHelloWorldFunction helloWorldFunction = new CustomHelloWorldFunction(messageContext);
+                return helloWorldFunction;
+            }
+
+            public QName getResolvingQName() {
+                //letting know synapse new hello-world extension function
+                return new QName("hello-world");
+            }
+            }
+
+        
+

+ Shown bellow is the custom xpath function returned by our xpath function extension. Note + that this should implement org.jaxen.Function to resolve xpath . +

+
+            package org.sample;
+
+            import org.apache.axiom.om.OMAbstractFactory;
+            import org.apache.axiom.om.OMElement;
+            import org.apache.axiom.om.OMFactory;
+            import org.apache.commons.logging.Log;
+            import org.apache.commons.logging.LogFactory;
+            import org.apache.synapse.MessageContext;
+            import org.apache.synapse.SynapseConstants;
+            import org.jaxen.Context;
+            import org.jaxen.Function;
+            import org.jaxen.FunctionCallException;
+            import org.jaxen.function.StringFunction;
+
+            import javax.xml.namespace.QName;
+            import java.util.List;
+
+
+            public class CustomHelloWorldFunction implements Function {
+            private MessageContext synCtx;
+
+            private Log log = LogFactory.getLog(CustomHelloWorldFunction.class);
+            private static final Log trace = LogFactory.getLog(SynapseConstants.TRACE_LOGGER);
+
+            private String NULL_STRING = "";
+            public static final QName HELLO_WORLD = new QName("HELLO_WORLD");
+            private OMElement helloWorld;
+
+            public CustomHelloWorldFunction(MessageContext ctxt) {
+                this.synCtx = ctxt;
+                //create hello world message
+                OMFactory factory = OMAbstractFactory.getOMFactory();
+                OMElement helloWorldElement = factory.createOMElement(HELLO_WORLD);
+
+                OMElement nameElement = factory.createOMElement(new QName("name"));
+                nameElement.setText("synapse");
+                OMElement versionElem = factory.createOMElement(new QName("version"));
+                versionElem.setText("3.1.0");
+                OMElement releaseDateElem = factory.createOMElement(new QName("release_date"));
+                releaseDateElem.setText("12/12/2010");
+
+                helloWorldElement.addChild(nameElement);
+                helloWorldElement.addChild(versionElem);
+                helloWorldElement.addChild(releaseDateElem);
+                this.helloWorld = helloWorldElement;
+            }
+
+            /**
+            * Returns the string value of the hello world message for the corresponding child
+            proeprty
+            * arguments are hello-world(name | version | release_date)
+            *
+            * @param context the context at the point in the expression when the function is called
+            * @param args arguments of the functions
+            * @return The string value of the property
+            * @throws org.jaxen.FunctionCallException
+            *
+            */
+            public Object call(Context context, List args) throws FunctionCallException {
+
+                if (synCtx == null) {
+                    if (log.isDebugEnabled()) {
+                    log.debug("Synapse message context has not been set for the " +
+                    "XPath extension function 'synapse:hello-world(arg_name)'");
+                    }
+                    return null;
+                }
+
+                boolean traceOn = synCtx.getTracingState() == SynapseConstants.TRACING_ON;
+                boolean traceOrDebugOn = traceOn || log.isDebugEnabled();
+
+                if (args == null || args.size() == 0) {
+                    if (traceOrDebugOn) {
+                        traceOrDebug(traceOn, "argument key value for lookup is not specified");
+                    }
+                    return NULL_STRING;
+                } else
+                {
+                    int size = args.size();
+                    if (size == 1) {
+                        String argument = StringFunction.evaluate(args.get(0), context.getNavigator());
+                    if ("name".equals(argument) || "version".equals(argument) ||
+                        "release_date".equals(argument)) {
+                         return helloWorld.getFirstChildWithName(new QName(argument));
+                    }else{
+                        return helloWorld;
+                    }
+                }
+                }
+                return NULL_STRING;
+            }
+
+            private void traceOrDebug(boolean traceOn, String msg) {
+                if (traceOn) {
+                    trace.info(msg);
+                }
+                if (log.isDebugEnabled()) {
+                    log.debug(msg);
+                }
+            }
+
+            }
+        
+

+ Here we basically select an child element or the whole Hello World message based on the + aguments. Please refer to org.jaxen.Function for further details on the implementation. + With this extension in place synapse configuration can refer to a particular element of + our Hello World message with expression = "hello-world('name')" ,expression = + "hello-world('version')" , etc +

+

+ Registering Extensions +

+

+ We need one additional step to make all these extensions integrate into Synapse configuration language. + Registering extensions is done by declaring them in synapse.properties file. + synapse.properties can be found $SYNAPSE_HOME/repository/conf . Functions should be + declared under property synapse.xpath.func.extensions while Variables should be under + synapse.xpath.var.extensions . +

+
+            synapse.xpath.var.extensions=org.sample.HelloWorldXpathVariableResolver
+            synapse.xpath.func.extensions=org.sample. HelloWorldXpathFunctionProvider
+        
+

+ If multiple function / variable extesnions are needed comma delimited list can be + declared. WSO2 ESB at startup will register all these declared extensions (defined under + its CLASSPATH) and our HELLO-WORLD xpath extensions will be ready to roll. +

+ + diff --git a/docs/xdoc/external_articles.xml b/docs/xdoc/external_articles.xml new file mode 100644 index 0000000000..70854955c8 --- /dev/null +++ b/docs/xdoc/external_articles.xml @@ -0,0 +1,113 @@ + + + + + + + + + WSO2 ESB - External Articles + + + + + + [ Documentation Index ] +

Articles on WSO2 ESB

+ +

Webinars, Screencasts and presenations on WSO2 ESB

+ + + diff --git a/docs/xdoc/faq.xml b/docs/xdoc/faq.xml new file mode 100644 index 0000000000..11cc9bff9b --- /dev/null +++ b/docs/xdoc/faq.xml @@ -0,0 +1,1130 @@ + + + + + + + + + WSO2 ESB - Frequently Asked Questions + + + + + + [ Documentation Index ] +

WSO2 Enterprise Service Bus (ESB) Frequently Asked Questions

+

+ This article provides answers to most commonly asked questions regarding WSO2 ESB, + its underlying Carbon framework, ESB deployment and configuration. +

+

Contents

+ + +
+

General (General ESB questions - Non technical)

+
    +
  1. + What is WSO2 ESB? +
  2. +
  3. + What makes WSO2 ESB unique? +
  4. +
  5. + What is the Open Source License of WSO2 ESB? +
  6. +
  7. + How do I get WSO2 ESB? +
  8. +
  9. + Does WSO2 ESB has performance comparison with other popular ESBs? +
  10. +
  11. + Is their commercial support available for WSO2 ESB? +
  12. +
  13. + Can I get involved with the ESB development activities? +
  14. +
+ +

Core (Questions related to the Carbon core and underlying framework)

+
    +
  1. + What are the technologies used underneath WSO2 ESB? +
  2. +
  3. + What are the minimum requirements to run WSO2 ESB? +
  4. +
  5. + What makes WSO2 ESB so fast? +
  6. +
  7. + Does WSO2 ESB support clustering? +
  8. +
  9. + In what occasions do I have to deploy a third party library into WSO2 ESB? +
  10. +
  11. + How do I deploy a third party library into the ESB? +
  12. +
  13. + Can I extend the management console UI to add custom UIs ? +
  14. +
  15. + Can I use an external user store to manage and authenticate WSO2 ESB users? +
  16. +
  17. + Does WSO2 ESB interop with a .net client/service? +
  18. +
  19. + Does WSO2 ESB support hessian binary web service protocol +
  20. +
  21. + I don't want some of the features that come with WSO2 ESB. Can I get rid of them? +
  22. +
  23. + Can I add support for other language for the management console ? +
  24. +
+ +

Mediation (Questions related to sequences, endpoints, proxies etc)

+
    +
  1. + What is a proxy service? +
  2. +
  3. + Does WSO2 ESB has support for transactions ? +
  4. +
  5. + Does WSO2 ESB has support for PEPPOL? +
  6. +
  7. + Where do I have to put my custom mediators in WSO2 ESB? +
  8. +
  9. + Where does WSO2 ESB load its configuration from? +
  10. +
  11. + Can I get the ESB to load mediation configuration from the registry? +
  12. +
  13. + What is a mediator? +
  14. +
  15. + What is a sequence? +
  16. +
  17. + What is an Endpoint? +
  18. +
  19. + Can Endpoint perform error handling? +
  20. +
  21. + What are local entries? +
  22. +
  23. + How can a sequence refer to another sequence? +
  24. +
  25. + How does dynamic endpoints and sequences work? +
  26. +
  27. + How can I change the endpoint dynamically? +
  28. +
  29. + I have heard of dynamic sequences and endpoints. Are there also dynamic proxy services? +
  30. +
  31. + + I want to mediate messages containing binary content through the ESB. What are the features + available in WSO2 ESB to support my requirement? + +
  32. +
  33. + How can I implement a persistence mechanism within my mediation chain? +
  34. +
  35. + + I have some dynamic sequences which are loaded from the registry. What will happen to my ESB if + the registry goes down or registry becomes unusable for a while? + +
  36. +
+ +

Transports (Transport related questions)

+
    +
  1. + What are the transports supported by the WSO2 ESB? +
  2. +
  3. + Do I need a external JMS broker for the JMS transport? +
  4. +
  5. + Does WSO2 ESB support AMQP ? +
  6. +
  7. + How to change the host name in WSO2 ESB? +
  8. +
  9. + + I have several JMS connection factories defined under the JMS transport receiver in the axis2.xml. + How can I get a particular proxy service to receive messages from one of those connection factories? + +
  10. +
  11. + Does WSO2 ESB support two way JMS scenario (request/response) ? +
  12. +
  13. + What are the JMS brokers that work with WSO2 ESB? +
  14. +
  15. + What is the NHTTP transport? +
  16. +
  17. + What is the underlying HTTP library used by the NHTTP transport? +
  18. +
  19. + How can I tune up the NHTTP transport? +
  20. +
  21. + Where is the general configuration of NHTTP transport? +
  22. +
+ +

Production (Questions related to production environments)

+
    +
  1. + Where do I keep the WSDLs required by my proxy services? +
  2. +
  3. + What is a graceful shut down? +
  4. +
  5. + What are the implications of hot deployment/hot update in a production environment? +
  6. +
  7. + I already have a WSO2 Governance Registry instance that contains my organization's SOA metadata. + Can I get WSO2 ESB to use that registry instance as the metadata store? +
  8. + + I need to setup a cluster of ESB instances. How can I share the same configuration + among all the ESB nodes? +
  9. +
+ +

Deployment Questions (Questions related to ESB deployments)

+
    +
  1. + What are the versions of Java supported by the ESB? +
  2. +
  3. + What are the minimum artifacts required to deploy WSO2? +
  4. +
  5. + How can I disable the management console ? +
  6. +
  7. + Does WSO2 ESB supports application server deployments? +
  8. +
  9. + What are the recommended hardware and software configurations for a typical WSO2 ESB deployment? +
  10. +
  11. + How can I deploy a custom task? +
  12. +
  13. + How do I embed a third party registry with WSO2 ESB? +
  14. +
  15. + What is the database management system used in WSO2 ESB? +
  16. +
  17. + How can I change the memory allocation for the WSO2 ESB? +
  18. +
+ +

Monitoring

+
    +
  1. + Does ESB supports JMX monitoring? +
  2. +
  3. + Does ESB allows custom statistics collection? +
  4. +
  5. + What is logging framework used in WSO2 ESB? +
  6. +
  7. + + I have a sequence which does not behave the way I want it to. How can I find out what's + wrong with it? + +
  8. +
  9. + + My WSO2 ESB instance is receiving messages. But why I don't see any statistics on the + mediation statistics page? + +
  10. +
  11. + + My ESB instance is behaving weird for certain input messages. What are the tools provided + in the ESB to help me debug the issue? + +
  12. +
+
+ +

General (General ESB questions - Non technical)

+
    +
  1. +

    + What is WSO2 ESB? +

    +

    + WSO2 ESB is a fast, lightweight, open source Enterprise Service Bus implementation. It supports + message routing, inter-mediation, transformation, logging, load balancing, fail over routing, + task scheduling, eventing and much more. +

    +
  2. +
  3. +

    + What makes WSO2 ESB unique? +

    +

    + WSO2 ESB is fast and able to handle thousands of concurrent connections with constant memory usage. + It comes with a rich set of mediators to support almost any integration scenario out of the box. + It is also easily extensible and highly customizable. The feature rich admin console makes it + so easy to configure, control and monitor the ESB runtime. +

    +
  4. +
  5. +

    + What is the Open Source License of WSO2 ESB? +

    +

    + It is released under + Apache Software License Version 2.0. +

    +
  6. +
  7. +

    + How do I get WSO2 ESB? +

    +

    + WSO2 ESB is distributed completely free and all the distribution packs can be downloaded from the + WSO2 Oxygen Tank. WSO2 ESB can be downloaded as a binary distribution or a source distribution and + if required one can even checkout the complete source code from the + WSO2 SVN repository. +

    +
  8. +
  9. +

    + Does WSO2 ESB has performance comparison with other popular ESBs? +

    +

    + Yes, several rounds of performance comparison has been carried out and the results are available + in WSO2 Oxygen Tank +

    +
  10. +
  11. +

    + Is their commercial support available for WSO2 ESB? +

    +

    + 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 + more details and to take advantage of this unique opportunity please visit + WSO2 Support. + +

    +
  12. +
  13. +

    + Can I get involved with the ESB development activities? +

    +

    + Not only you are allowed, but it is encouraged. You can start by subscribing to carbon-dev@wso2.org + and architecture@wso2.org mailing lists. Feel free to provide ideas, feed back and help us make our + code better. You can also report bugs on our issue tracker and you can even submit patches. Visit + WSO2 Oxygen Tank for more information about our mailig lists. +

    +
  14. +
+ +

Core (Questions related to the Carbon core and underlying framework)

+
    +
  1. +

    + What are the technologies used underneath WSO2 ESB? +

    +

    + WSO2 ESB is built on top of WSO2 Carbon, an OSGi based components framework for SOA. It uses + Apache Synapse as the underlying mediation engine. + Java is the primary programming language used to develop WSO2 ESB. +

    +
  2. +
  3. +

    + What are the minimum requirements to run WSO2 ESB? +

    +
      +
    • + Hardware Requirements: +
        +
      • Pentium 800MHz or equivalent processor
      • +
      • 256 MB of memory
      • +
      • The extracted binary distribution of WSO2 ESB takes up about 130 MB of disk space + (WSO2 ESB will require more disk space at runtime to keep temporary files, + server logs etc) +
      • +
      +
    • +
    • + Software Requirements: +
        +
      • Java Runtime Environment 1.5 or above
      • +
      +
    • +
    +
  4. +
  5. +

    + What makes WSO2 ESB so fast? +

    +

    + The mediation core of WSO2 ESB is designed to be completely asynchronous, non-blocking and + streaming. It comes with a non-blocking HTTP transport adapter based on Apache HTTP Core-NIO which + is capable of handling a large number of concurrent connections. WSO2 ESB also uses Apache AXIOM, a + StAX based XML infoset model, to process XML and SOAP. This enables WSO2 ESB to stream messages + through the mediation engine without having to invoke slow XML processing routines for each and + every message. +

    +
  6. + +
  7. +

    + Does WSO2 ESB support clustering? +

    +

    Yes, it supports clustered deployment. WSO2 ESB uses the Apache Axis2 clustering framework to + support the following two clustering schemes:

    +
      +
    • Multicast based clustering
    • +
    • Well known addressing based clustering
    • +
    +
  8. + +
  9. +

    + In what occasions do I have to deploy a third party library into WSO2 ESB? +

    +
      +
    • When enabling a new transport you will have to deploy the libraries required by the + transport implementation (eg: When enabling JMS you need to deploy the client libraries required + to connect to your JMS broker) +
    • +
    • When adding a custom mediator or a task you might have to deploy the dependencies required + by the custom code
    • +
    +
  10. + +
  11. +

    + How do I deploy a third party library into the ESB? +

    +

    + You can deploy any third party jar into the repository/components/lib directory. You also need to + restart the server for the newly deployed jars to be picked up by the server runtime. WSO2 ESB will + convert any jar files copied into the above location into OSGi bundles. These OSGi bundles are + placed in the repository/components/dropins directory. +

    +
  12. + +
  13. +

    + Can I extend the management console UI to add custom UIs ? +

    +

    + Yes, you can extend the management console easily by writing a custom UI component. +

    +
  14. + +
  15. +

    + Can I use an external user store to manage and authenticate WSO2 ESB users? +

    +

    + Yes you can. You can connect WSO2 ESB with any external user store implementation. + The user store could be LDAP based, JDBC based or a custom developed user store. Please + refer user core documentation for more details. +

    +
  16. + +
  17. +

    + Does WSO2 ESB interop with a .net client/service? +

    +

    + Yes, it does with both. WSO2 ESB can be easily configured to bridge Java services with .NET clients + and .NET services with Java clients. +

    +
  18. + +
  19. +

    + Does WSO2 ESB support hessian binary web service protocol +

    +

    + Yes, it does +

    +
  20. + +
  21. +

    + I don't want some of the features that come with WSO2 ESB. Can I get rid of them? +

    +

    + Yes you can. Login to the ESB management console and browse to the Feature Manager. Open the + 'Installed Features' tab. From here you can uninstall any unwanted features. +

    +
  22. + +
  23. +

    + Can I add support for other language for the management console ? +

    +

    + Yes, WSO2 ESB comes with a UI framework which supports i18n (internationalization) which lets you + to use a language of your choice for the management console. +

    +
  24. + +
+ +

Mediation (Questions related to sequences, endpoints, proxies etc)

+
    +
  1. +

    + What is a proxy service? +

    +

    + A proxy service is a virtual service hosted on the ESB. It can accept requests from service clients, + just like a real Web Service. A proxy service can process requests and forward them to an actual + Web Service (back end service) to be further processed. The responses coming back from the back + end service can be routed back to the original client. Proxy services are mostly used + to expose an existing service over a different transport, format or QoS configuration. +

    +
  2. + +
  3. +

    + Does WSO2 ESB has support for transactions ? +

    +

    + Yes it does. It has support for distributed transaction, local JMS transactions and distributed JMS + transactions. +

    +
  4. +
  5. +

    + Does WSO2 ESB has support for PEPPOL? +

    +

    + Yes it does. You can use WSO2 ESB in an Access point. +

    +
  6. +
  7. +

    + Where do I have to put my custom mediators in WSO2 ESB? +

    +

    + In version 3.0.1 you can place your non-OSGi custom mediators and class mediators in + $ESB_HOME/repository/components/mediators and OSGi bundles + in $ESB_HOME/repository/components/dropins. +

    +
  8. +
  9. +

    + Where does WSO2 ESB load its configuration from? +

    +

    + WSO2 ESB reads its mediation configuration from a set of XML files located at + repository/conf/synapse-config directory. XML files are written in the Synapse configuration + language. Any changes done to the configuration through the UI are saved back to the configuration + files. (Configuration is also written to the registry by default) +

    +
  10. +
  11. +

    + Can I get the ESB to load mediation configuration from the registry? +

    +

    + Yes you can. The necessary steps are given in the + ESB administrator guide. +

    +
  12. + +
  13. +

    + What is a mediator? +

    +

    + A mediator is the basic message processing unit in the ESB. A mediator can take a message, carry + out some predefined actions on it and output the modified message. WSO2 ESB ships with a range of + mediators capable of carrying out various tasks on input messages. +

    +
      +
    • Log mediator - Logs the input message
    • +
    • Send mediator - Sends the input message to a given endpoint
    • +
    • XSLT mediator - Transforms the input message using a given XSLT
    • +
    +
  14. + +
  15. +

    + What is a sequence? +

    +

    + A sequence is an ordered list of mediators (a mediator chain). When a sequence is given a message, + it will go through all the mediators in the sequence. A sequence can also handover messages to + other sequences. +

    +
  16. + +
  17. +

    + What is an Endpoint? +

    +

    + Endpoint is a target or collection of targets that a message can deliver. +

    +
  18. + +
  19. +

    + Can Endpoint perform error handling? +

    +

    + Yes. Endpoints can do error handling. User can configure the behavior of an endpoints when it + faced to a erroneous situation. You can find detailed article about endpoint error handling + + here. + +

    +
  20. + +
  21. +

    + What are local entries? +

    +

    + Local entries can be used to hold various configuration elements required by sequences and proxy + services. Usually they are used to hold WSDLs, XSDs, XSLT files etc. A local entry can contain XML + content as well as plain text content. A local entry can be configured to load content from a + remote file too. +

    +
  22. + +
  23. +

    + How can a sequence refer to another sequence? +

    +

    + To refer to a sequence named foo use the sequence mediator as follows: +

    +
    +<sequence key="foo"/>
    +                
    +

    + You can also refer to dynamic sequences saved in the registry by specifying the registry key to the + sequence resource as follows: +

    +
    +<sequence key="gov:/dev/sequences/foo"/>
    +                
    +

    The above sequence mediator will load the sequence configuration from the resource at + /dev/sequences/foo in the governance registry.

    +
  24. + +
  25. +

    + How does dynamic endpoints and sequences work? +

    +

    + Dynamic endpoints and sequences are just XML configuration bits saved in the registry. These + configurations are loaded to the mediation configuration at runtime. Once loaded they will be cached + for a specified duration in the memory. Once the cache is expired it will be loaded again from the + registry. Therefore changes done to dynamic sequences and endpoints at runtime will take effect + once the ESB reloads them after a cache timeout. +

    +

    To use dynamic sequences and endpoints the mediation registry must be included in the + mediation configuration as follows: +

    +
    +<sequence key="foo"/>
    +<registry xmlns="http://ws.apache.org/ns/synapse" provider="org.wso2.carbon.mediation.registry.WSO2Registry">
    +    <parameter name="cachableDuration">15000</parameter>
    +</registry>
    +                
    +

    + This configuration can be found in a file named registry.xml in the repository/conf/synapse-config + directory by default. Note how the cache duration is set to 15000 ms (15s). This duration can be + reduced or extended as necessary by editing the registry.xml file or through the configuration + source editor in the UI. +

    +
  26. + +
  27. +

    + How can I change the endpoint dynamically? +

    +

    + If you want to change the endpoint dynamically per each message, you can use a header mediator to + calculate the new 'To' address. +

    +
    +<header name="To" expression="XPath to create the address dynamically"/>
    +                
    +
  28. + +
  29. +

    + I have heard of dynamic sequences and endpoints. Are there also dynamic proxy services? +

    +

    + WSO2 ESB does not support dynamic proxy services. But a proxy service may use a dynamic + endpoint as the target endpoint and dynamic sequences as the in sequence and the out sequence. + This effectively makes the entire proxy service dynamic. +

    +
  30. + +
  31. +

    + I want to mediate messages containing binary content through the ESB. What are the features + available in WSO2 ESB to support my requirement? +

    +

    +

    +
  32. + +
  33. +

    + How can I implement a persistence mechanism within my mediation chain? +

    +

    + You have two options. One option is to use dbreport and dblookup mediators to + persist the message into a database and lookup it later from the database. The other option is + to use JMS transport in which you can use a JMS broker to persist the message. +

    +
  34. + +
  35. +

    + I have some dynamic sequences which are loaded from the registry. What will happen to my ESB if + the registry goes down or registry becomes unusable for a while? +

    +

    + If the dynamic sequences are loaded to the memory at least once, the ESB will continue to use the + cached version of the sequence, as long as the registry is unreachable. A warning will be logged + every time ESB attempts to load the sequence from the registry and fails. As soon as the registry + comes back on-line, ESB will load the sequence from the registry. +

    +
  36. +
+ +

Transports (Transport related questions)

+
    +
  1. +

    + What are the transports supported by the WSO2 ESB? +

    +

    + HTTP, HTTPS, VFS based file transport, FIX, Hessian, HL7,UDP, JMS, Mail, TCP, XMPP +

    +
  2. + +
  3. +

    + Do I need an external JMS broker for the JMS transport? +

    +

    + Yes, WSO2 ESB requires an external JMS broker like + Apache ActiveMQ. +

    +
  4. + +
  5. +

    + Does WSO2 ESB support AMQP? +

    +

    + WSO2 ESB supports AMQP through its JMS transport. The JMS transport can be configured to + connect to an AMQP broker as if it was connecting to a JMS broker. This functionality has been + tested with Apache Qpid and RabbitMQ. +

    +
  6. + +
  7. +

    + How to change the host name in WSO2 ESB? +

    +

    + You can edit parameter bind-address in http/https transport receiver to change the host name of WSO2 + ESB. This hostname will be displayed on service endpoints and generated WSDLs. +

    +
  8. + +
  9. +

    + I have several JMS connection factories defined under the JMS transport receiver in the axis2.xml. + How can I get a particular proxy service to receive messages from one of those connection factories? +

    +

    + You can specify the preferred connection factory by adding the following parameter to the proxy + service configuration. +

    +
    +<parameter name="transport.jms.ConnectionFactory">MyConnectionFactory</parameter>
    +                
    +

    Replace 'MyConnectionFactory' with the name of the appropriate connection factory. + If the above parameter is not specified, proxy service will bind to the connection + factory named 'default'. +

    +
  10. + +
  11. +

    + Does WSO2 ESB support two way JMS scenario (request/response) ? +

    +

    + Yes, you can refer sample 264 + which demonstrates exactly the JMS request/response scenario. +

    +
  12. + +
  13. +

    + What are the JMS brokers that work with WSO2 ESB? +

    +

    + Any JMS broker that provides JNDI support can be integrated with WSO2 ESB. The default + configurations are for Apache ActiveMQ. WSO2 ESB has also been tested with IBM Websphere MQ, + Swift MQ and JBOSS MQ. +

    +
  14. +
  15. +

    + What is the NHTTP transport? +

    +

    + This is the default HTTP transport used by WSO2 ESB. NHTTP stands for non-blocking HTTP. + NHTTP transport uses the Java Non-blocking I/O API. This allows the NHTTP transport to scale into + handling hundreds of connections without blocking the threads. The server worker threads used + by the NHTTP transport do not get blocked on I/O until the ESB receives responses for the already + forwarded requests. Therefore WSO2 ESB can accept more concurrent connections and requests than + most HTTP server products. +

    +
  16. + +
  17. +

    + What is the underlying HTTP library used by the NHTTP transport? +

    +

    + NHTTP transport uses the + Apache Http Core NIO library underneath. This library provides low level + I/O handling and HTTP level detail handling. +

    +
  18. + +
  19. +

    + How can I tune up the NHTTP transport? +

    +

    + There is a file called nhttp.properties in the webapps/ROOT/WEB-INF/classes directory. User can + change various configuration parameters like number of threads, keep alive connections through + this file. More information can be found in the ESB Administrator Guide. +

    +
  20. + +
  21. +

    + Where is the general configuration of NHTTP transport? +

    +

    + The NHTTP transport configuration has two parts and they are transportReceiver and transportSender. + Both configuration are located axis2.xml file. +

    +
  22. +
+ + + +

Production (Questions related to production environments)

+ +
    +
  1. +

    + Where do I keep the WSDLs required by my proxy services? +

    +

    + You can keep them as local entries. But it is recommended to keep them in the registry instead, for + easier and better management. +

    +
  2. + +
  3. +

    + What is a graceful shut down? +

    +

    + When a graceful shut down is initiated ESB will serve the accepted requests but stops processing + new requests +

    +
  4. + +
  5. +

    + What are the implications of hot deployment/hot update in a production environment? +

    +

    + Hot deployment/hot update may take the system to inconsistent states if the updates are not properly + coordinated. Therefore it is recommended to turn hot deployment and hot update off for + production deployments. +

    +
  6. + +
  7. +

    + I already have a WSO2 Governance Registry instance that contains my organization's SOA metadata. + Can I get WSO2 ESB to use that registry instance as the metadata store? +

    +

    + WSO2 ESB integrates with WSO2 Governance Registry out of the box. Refer the administrator + guide for the necessary steps involved in remote registry configuration. +

    +
  8. + +
  9. +

    + I need to setup a cluster of ESB instances. How can I share the same configuration + among all the ESB nodes? +

    +

    + You just need to put the configuration into the registry and point all ESB instances to that + registry instance. +

    +
  10. +
+ +

Deployment (Questions related to ESB deployments)

+
    +
  1. +

    + What are the versions of Java supported by the ESB? +

    +

    + It is tested on JDK 1.5 and JDK 1.6. Sun JDK and IBM JDK are supported. +

    +
  2. + +
  3. +

    + What are the minimum artifacts required to deploy WSO2? +

    +

    + When deploying you can remove, $ESB_HOME/samples and $ESB_HOME/repository/samples from the + standard distribution. +

    +
  4. + +
  5. +

    + How can I disable the management console ? +

    +

    + You can uninstall all the UI components using the feature manager which will disable the + management console. +

    +
  6. + +
  7. +

    + Does WSO2 ESB supports application server deployments? +

    +

    + Yes it has been tested on the following app servers. JBoss, Weblogic, Websphere and Tomcat. +

    +
  8. + +
  9. +

    + What are the recommended hardware and software configurations for a typical WSO2 ESB deployment? +

    +
      +
    • + Hardware configuration: +
        +
      • 2 GHz Multicore processor
      • +
      • 2 GB of memory
      • +
      • The extracted binary distribution of WSO2 ESB takes up about 130 MB of disk space + (WSO2 ESB will require more disk space at runtime to keep temporary files, + server logs etc) +
      • +
      +
    • +
    • + Software Requirements: +
        +
      • Java Runtime Environment 1.6
      • +
      +
    • +
    +
  10. + +
  11. +

    + How can I deploy a custom task? +

    +

    + See the documentation to see how to write a custom task. Put your non-OSGi task jar + into $esbhome/repository/components/lib directory. WSO2 ESB will automatically deploy + your custom task. +

    +
  12. + +
  13. +

    + How do I embed a third party registry with WSO2 ESB? +

    +

    + You need to write a class implementing the org.apache.synapse.registry.Registry interface to + integrate the third party registry to WSO2 ESB. +

    +
  14. + +
  15. +

    + What is the database management system used in WSO2 ESB? +

    +

    + WSO2 ESB ships with an embedded H2 database. However any database management system can be plugged + into the ESB via JDBC. The relevant database configurations are available in + repository/conf/registry.xml and repository/cong/user-mgt.xml files. WSO2 ESB has been tested + with MySQL, Oracle, MSSQL and PostgreSQL databases. +

    +
  16. + +
  17. +

    + How can I change the memory allocation for the WSO2 ESB? +

    +

    + The memory allocation setting are in the wso2server.sh. The user can change the memory allocation + settings by changing the following configuration. +

    +

    + -Xms256m -Xmx512m -XX:MaxPermSize=128m +

    +
  18. + + +
+ + +

Monitoring

+
    +
  1. +

    + Does ESB supports JMX monitoring? +

    +

    + Yes it support JMX monitoring. Users can use the JConsole for simple monitoring and use + JMX clients for + custom monitoring +

    +
  2. +
  3. +

    + Does ESB allows custom statistics collection? +

    +

    + Users can write and plug their own statistics collection mechanisms to the ESB. This allows users + to report statistics to their own statistics collection systems. +

    +
  4. + +
  5. +

    + What is logging framework used in WSO2 ESB? +

    +

    + WSO2 ESB uses Apache Log4/J over Apache Commons Logging as the logging framework. + Logging configuration is loaded from the log4j.properties file in the lib directory. + The UI also allows configuring logging at runtime. The generated server logs can be found in + the repository/logs directory. +

    +
  6. + +
  7. +

    + I have a sequence which does not behave the way I want it to. How can I find out what's + wrong with it? +

    +

    + Login to the ESB management console and go to the sequence management page. Enable tracing for the + sequence you want to debug. Send a few messages to the sequence and go to the system logs viewer in + the UI (or open the wso2-esb.log file in repository/logs). Go through the generated trace logs and + locate the problem. +

    +
  8. + +
  9. +

    + My WSO2 ESB instance is receiving messages. But why I don't see any statistics on the + mediation statistics page? +

    +

    + You need to enable statistics on sequences, endpoints, proxy services for the ESB to collect + statistics on them. By default WSO2 ESB does not collect statistics on anything to keep the overhead + at a minimum. Simply enable statistics for the items you are interested in using the UI and + mediation statistics page will start to get updated. +

    +
  10. + +
  11. +

    + My ESB instance is behaving weird for certain input messages. What are the tools provided + in the ESB to help me debug the issue? +

    +

    + You can use the SOAP tracer in the UI to capture and monitor actual content of the incoming + messages. Enable tracing on the appropriate sequences to trace the flow of messages through + the ESB. ESB also comes with Apache TCPMon which is a simple but extremely useful too for + monitoring message flows. +

    +
  12. +
+ + + diff --git a/docs/xdoc/feature_guide.xml b/docs/xdoc/feature_guide.xml new file mode 100644 index 0000000000..ea0b6dd553 --- /dev/null +++ b/docs/xdoc/feature_guide.xml @@ -0,0 +1,84 @@ + + + + + + + + WSO2 ESB - Feature Guide + + + + + + + [ Documentation Index ] +

WSO2 Enterprise Service Bus (ESB) - Feature Guide

+

WSO2 Carbon is an OSGi-based component framework allows the complete set of products to leverage + shared components, ensuring a consistent set of features between products, a consistent user + experience, and reusing of identical components.WSO2 Carbon provides the core capabilities + for security, clustering, logging,statistics, and management, and through a technology + called OSGi, higher level capabilities can be readily added as components to this core. + WSO2 ESB can be considered as WSO2 Carbon and bunch of features related to ESB. + With the power of componentized architecture of WSO2 Platform, user can add/remove various + features from all WSO2 product.

+ + +

Introduction

+

This documentation provides guideline on feature management related to WSO2 ESB.

+ +

Installing various features in WSO2 ESB?

+ +

Using the Feature Manager (Configure > Feature in the tabbed pane) you can install any feature +available in the feature repository(p2-repo). Please refer +Feature Manager Documentation.

+

+ BPEL Feature installed on ESB +
+

+ +

Installing ESB features on other WSO2 Products

+

+ Also there can be cases where we need to install the ESB related features inside other WSO2 Products. + For instance, we might have to install the ESB Features on raw Carbon Server. For such cases, ESB provides + a single feature which install all the ESB Related features. Using the Feature Manager + (Configure > Feature in the tabbed pane) you can install 'ESB Mediation' feature to get the functionality + of ESB in to any other WSO2 Product. +

+

+
+ Installing ESB Mediation Feature in Carbon Server +
+ ESB Mediation Feature installed on Carbon Server
+

+ +

In addition to that you have to modify some configuration files to get the complete functionality of the + ESB.

+ +

After applying above changes, we have to restart the Carbon Server.

+ + diff --git a/docs/xdoc/index.xml b/docs/xdoc/index.xml new file mode 100644 index 0000000000..50d7673d22 --- /dev/null +++ b/docs/xdoc/index.xml @@ -0,0 +1,169 @@ + + + + + + + + + Welcome to WSO2 ESB v4.0.0 + + + + + +

+ Welcome to WSO2 Enterprise Service Bus (ESB) v4.0.0 +

+ +

+ WSO2 ESB is a lightweight and easy-to-use Open Source Enterprise Service Bus (ESB) + available under the Apache + Software License v2.0. WSO2 ESB allows system administrators and SOA architects to + simply and easily configure message routing, virtualization, intermediation, + transformation, logging, task scheduling, load balancing, fail-over routing, event + brokering and much more. The runtime has been designed to be completely asynchronous, non-blocking + and streaming based on the Apache Synapse mediation + engine. +

+ +

+ WSO2 ESB 4.0.0 is developed on top of the revolutionary + WSO2 Carbon platform (Middleware a' la carte), + and is based on OSGi to provide better modularity and componentization + to your Service Oriented Architecture (SOA). This release also contains a number of + new features and many other optional components to customize the behavior of the server. + Further, if you do not want any built-in features, you can uninstall those + features without any trouble. In other words, WSO2 ESB can be customized and tailored to + suit your exact SOA requirements. +

+ +

+ You can download WSO2 ESB 4.0.0 distribution from Project + Download Page and give it a try. +

+ +

Getting Started

+

Getting your integration project off the ground with WSO2 ESB is simple.

+
    +
  1. Download WSO2 ESB 4.0.0
  2. +
  3. Read through the Documentation Index
  4. +
  5. Visit our Official Website
  6. +
  7. Look at the Release Notes for the high level + features, or the WSO2 ESB Data + Sheet
  8. +
  9. + Developer Mailing List : carbon-dev@wso2.org + | Subscribe + | Unsubscribe + | Mail Archive +
  10. +
  11. + User Mailing List : esb-java-user@wso2.org + | Subscribe + | Unsubscribe + | Mail Archive +
  12. +
  13. + Discussion forum for WSO2 ESB developers/users +
  14. +
  15. + Report issues on the ESB JIRA or the + Carbon JIRA +
  16. +
+

WSO2 ESB Component Architecture

+ +
ESB Architecture
+ +

+ WSO2 ESB supports many application layer protocols and messaging standards (collectively known + as transports), including HTTP/S, E-mail, Java Message Service (JMS) and Virtual File System + (VFS). It also supports a range of domain specific protocols such as Financial Information + eXchange (FIX), Advanced Message Queueing Protocol (AMQP) and Health Layer 7 (HL7). New + transports can be easily plugged into the server thanks to the seamless extensibility offered + by the Axis2 transports framework. +

+

+ ESB uses message builder components to parse the messages + arriving via different transports. A message builder is usually associated with a content type. + Depending on the actual content type of an incoming message, the ESB will select a suitable + message builder, which will then parse the message content and convert it into the Apache AXIOM + based XML infoset. WSO2 ESB ships with message builders for handling text messages (plain text, + SOAP, POX etc) as well as binary messages. Message formatters are the opposite partners of the + builders. A formatter converts the message back to its original format by referring the content + type just before the message is handed over to the transports again for routing. Similar to the + transports, user can implement new message builders and formatters by using the Axis2 API. +

+

+ Endpoints stay as a logical component with the transports. There are three types of top level + endpoints, namely Address endpoints, WSDL endpoints and Default endpoints. In addition to these + there are secondary endpoint types such as load balanced endpoints and fail over endpoints which + are composed of one or more top level endpoints. An endpoint can use any available transport + to dispatch the messages and they can even enforce various QoS constraints (security, RM etc) + on outgoing messages. +

+

+ Proxy services are virtual services hosted in WSO2 ESB. These are implemented using Axis2 message + receivers and hence can be opened up to accept incoming messages. A proxy service can be accessed + using a URL similar to a regular web service address. Proxy services allow publishing a WSDL as + well so that a client can connect to a proxy service just like connecting to an actual Web Service. + Any available transport can be use to receive and send messages through the proxy services. Proxy + services are a great way for exposing existing services over different transports, schemas and QoS + configurations. +

+

+ The power of WSO2 ESB lies in the comprehensive mediator library that provides various message + processing and inter-mediation capabilities. Using the mediator library we can implement all widely + used Message Exchange Patterns (MEP) and Enterprise Integration Patterns (EIP). There are simple + mediators which provide fundamental message processing capabilities such as logging and content + transformation as well as advanced mediators which can be used to access databases, add security to + message flows and so on. In situations where the built-in mediators are not sufficient to implement + a given scenario one can write a custom mediator on top of the simple but powerful API provided + by WSO2 ESB. Mediators can be implemented using various technologies including Java, scripting and + Spring, all of which are considered as extension points to the WSO2 ESB. +

+

+ Sequences are special mediators that act as the configuration component for the mediators. Sequences + allow organizing the mediators to implement ordered pipes and filters pattern to achieve actual + message processing and mediation. +

+

+ Tasks provide the ability to configure scheduled jobs in WSO2 ESB and they allow executing + internal and external commands for mediation. QoS components that implement reliable messaging + and security for the proxy services and for mediation come with the Apache implementations of + those two modules for Axis2, namely Rampart and Sandesha. +

+

+ WSO2 ESB has an in-built registry/repository to store the configuration and configuration + metadata and it provides the facility to use a remote repository as well. Components like + clustering, load balancing and high availability makes WSO2 ESB a production ready server. + Finally the GUI components provide comprehensive management, configuration + and monitoring capabilities to the ESB. GUI is built on a layered architecture by separating the + backend and frontend concerns. This allow the user to connect to multiple servers using a single + GUI console. The component based architecture of the WSO2 ESB has enhanced its loosely coupled + nature with the usage of OSGi. All the components are built as OSGi bundles. +

+ + + diff --git a/docs/xdoc/installation_guide.xml b/docs/xdoc/installation_guide.xml new file mode 100644 index 0000000000..e02584851a --- /dev/null +++ b/docs/xdoc/installation_guide.xml @@ -0,0 +1,435 @@ + + + + + + + + + + WSO2 ESB - Installation Guide + + + + + [ Documentation Index ] +

+ WSO2 Enterprise Service Bus (ESB) Installation Guide +

+

+ +

This installation guide provides information on,

+
    +
  1. Prerequisites for installing WSO2 ESB
  2. +
  3. Installation instructions
  4. +
  5. Starting up WSO2 ESB
  6. +
  7. Accessing the management console
  8. +
+ +

+ This document describes the distribution packages available in WSO2 ESB - + the binary distribution and the source distribution for more advanced + users. It is followed by simple instructions on how to install and run + WSO2 ESB using the binary distribution and how to build WSO2 ESB using the + source distribution. +

+ +

Contents

+ +

+ Distribution Packages +

+

+ The following distribution packages are available for download. +

+

+ 1. Binary Distribution : Includes binary files for both MS Windows and + Linux operating systems, compressed into a single a zip file. Recommended + for normal users. +

+

+ 2. Source Distribution : Includes the source code for both MS Windows and Linux + operating systems, compressed into a single zip file which can be used to build the binary files. + Recommended for more advanced users. +

+

+ Installing and Running WSO2 ESB using the Binary Distribution +

+

+ Prerequisites +

+

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Java SE + Development Kit + + + 1.6.0_23 or higher (For instructions on setting up the JDK on different operating + systems, visit http://www.oracle.com/technetwork/java/index.html) +

+

+ To build WSO2 ESB from the Source distribution, it is necessary + that you have JDK 1.6.x version and Maven 2.2.0 or later +

+
+ Apache ActiveMQ + -JMS Provider + +

+ Apache ActiveMQ 5.0.0 or higher is required to enable the WSO2 ESB JMS + transport and try out JMS samples. The ActiveMQ client libraries must + be installed in the ESB classpath before you can enable the JMS transport. + Alternatively you may use the built-in Qpid broker that comes with + WSO2 ESB. +

+

+ If you are using any other JMS provider (eg: IBM Websphere), you will need + to install necessary libraries. +

+
+ Apache Ant + - To run ESB samples + +

+ To compile and run the sample clients, an Ant installation is required. + Ant 1.7.0 version or higher is recommended. +

+
+ Apache Maven- To + build ESB from Source + + To build the WSO2 ESB from its source distribution, you will need + Maven 2.2.0 or later +
+ Web browser - To start the ESB Management Console + + Mozilla Firefox 3.0 or higher at a resolution of 1024x768 is recommended. MS + Internet Explorer 7 or Google Chrome may be used as well. Once + the WSO2 ESB is started with the default settings, point the browser to + https://localhost:9443/carbon in order to access your Management Console. + See the WSO2 ESB User Guide for more details. +
+ Memory + + No minimum requirement - A heap size of 1GB is generally + sufficient to process typical SOAP messages. Requirements may vary + with larger message size and on the number of messages processed + concurrently +
+ Disk + + No minimum requirement. The installation will require ~125 MB + excluding space allocated for log files and Databases. +
+ Operating System + + Linux, Solaris, MS Windows - XP/2003/2008 (Not fully tested on Windows + Vista or Windows 7). Since WSO2 ESB is a Java application, it will generally + be possible to run it on other operating systems with a JDK 1.6.x + runtime. Linux/Solaris is recommended for a production deployment. +
+

+ +

Installing on Linux/Unix

+

+ The following steps will take you through the binary distribution + installation on Unix/Linux systems. +

+
    +
  1. + Download the WSO2 ESB binary distribution. +
  2. +
  3. + Extract the zip archive where you want the WSO2 ESB installed (e.g. into /opt) +
  4. +
  5. + Set the JAVA_HOME environment variable to your + Java home using the export command or by editing /etc/profile, and add the Java /bin + directory to your PATH +
  6. +
  7. + Execute the WSO2 ESB start script or the daemon script from the bin + directory. e.g. ./wso2server.sh OR ./daemon.sh start OR + ./wso2server.sh --console +
  8. +
  9. + Check your WSO2 ESB instance using the URL https://localhost:9443/carbon + which will take you to the WSO2 ESB Management Console. (Note that server + start up may take time) +
  10. +
  11. + Login as "admin" using the default password "admin" +
  12. +
+ +

+ Installing on MS Windows +

+

+ The following steps will take you through the installation for the MS + Windows operating system. +

+
    +
  1. + Download the WSO2 ESB binary distribution. +
  2. +
  3. + Extract the zip archive where you want the WSO2 ESB installed +
  4. +
  5. + Set the JAVA_HOME environment variable to your + Java installation, and the PATH environment variable to the Java /bin directory. +
  6. +
  7. + Execute the WSO2 ESB start script from the bin folder. e.g. wso2server.bat +
  8. +
  9. + If you would like to install the WSO2 ESB as a Windows service, use the + install.bat script +
  10. +
  11. + Check your WSO2 ESB instance using the URL https://localhost:9443/carbon + which will take you to the WSO2 ESB Management Console. +
  12. +
  13. + Login as "admin" using the default password "admin" +
  14. +
+

+ Building WSO2 ESB Using the Source Distribution +

+

+ Prerequisites +

+

+ + + + + + + + + + + + + + + +
+ Java SE + Development Kit + + + 1.6.x (For instructions on setting up the JDK in different operating + systems, visit http://java.sun.com) +
+ Apache Maven- To + build ESB from Source + + To build the WSO2 ESB from its source distribution, you will need + Maven 2.2.0 or later +
+ Operating System + + Linux, Solaris, MS Windows - XP/2003/2008 (Not fully tested on Windows + Vista) +
+

+

+ Setting up the Environment and Tools +

+

+

+ Maven: +

+

+ The WSO2 ESB build is based on Apache + Maven 2. Hence, it is a prerequisite to have Maven (version 2.2.0 or later) + and JDK (version 1.6.x) installed in order to build WSO2 ESB from the + source distribution. Extensive instructions on using Maven 2 are available + on the Maven website. +

+

+ Please refer to the + Maven + Getting Started Guide + + for more information on Maven +

+
    +
  • + Unix based OS (e.g., Linux) +
  • +
+
    +
  1. + Download Apache Maven tar ball or the zip archive. +
  2. +
  3. + Expand it to a directory of choice. +
  4. +
  5. + Set the environment variable M2_HOME and add M2_HOME/bin to the + path as well. +
  6. +
  7. + Run mvn --version to verify that it is correctly installed. +
  8. +
+
    +
  • + MS Windows +
  • +
+
    +
  1. + Download and run the Apache Maven Windows installer package. +
  2. +
  3. + Set the 'Environment Variables' (create the system variable M2_HOME + and edit the path. e.g., "C:\Program Files\Apache Software + Foundation\maven-2.2.1"; path %M2_HOME%\bin) +
  4. +
  5. + Make sure that the system variable + JAVA_HOME + is set to the location of your JDK, e.g., C:\Program Files\Java\jdk1.6 +
  6. +
  7. + Run mvn --version to verify that it is correctly installed. +
  8. +
+

+ Once Maven is properly installed, you can start building the WSO2 ESB. +

+

+ Building WSO2 ESB +

+
    +
  1. + Download + the source distribution, which is available as a zip archive. +
  2. +
  3. + Extract the source archive to a directory of your choice. +
  4. +
  5. + All the necessary build scripts are included with the source distribution. +
  6. +
  7. + You can run the following command inside that directory to build the + WSO2 ESB. Note that you will require a connection to the Internet for the Maven build + to download dependencies required for the build. +
    +

    + Command: mvn clean install +

    +
  8. +
+

+ This will create the complete release artifacts including the binary and + source distributions in the modules/distribution/target/ directory which can be installed using + the above instructions. +

+

+ Note: The first time you run Maven it will automatically download the + dependency jar files. Therefore, the first run will take more time. It is also + recommended to allocate for memory for Maven since the ESB build process takes up + a significant amount of resources. More memory can be allocated for Maven by setting + the MAVEN_OPTS environment variable. +

+ + diff --git a/docs/xdoc/java_home_setup.xml b/docs/xdoc/java_home_setup.xml new file mode 100644 index 0000000000..ebd5169ef2 --- /dev/null +++ b/docs/xdoc/java_home_setup.xml @@ -0,0 +1,31 @@ + + + + + + + + Setting up Java Home + + + + + diff --git a/docs/xdoc/mediator_guide.xml b/docs/xdoc/mediator_guide.xml new file mode 100644 index 0000000000..bd0df36272 --- /dev/null +++ b/docs/xdoc/mediator_guide.xml @@ -0,0 +1,428 @@ + + + + + + + + WSO2 ESB - Mediator Catalog + + + + + + + [ Documentation Index ] +

WSO2 Enterprise Service Bus (ESB) Mediator Catalog

+

Mediators are the basic component of a mediation framework and the WSO2 ESB has a + comprehensive set of mediators. This guide will walk you through the genral concept of + mediation inside the WSO2 ESB and will also describe each and every mediator shipped with + WSO2 ESB, one by one

+

Contents

+ +

Introduction

+

Message mediation is a fundamental part of any ESB. WSO2 ESB achieves +message mediation through it's mediators. ESB comes with a rich set of 30 plus +mediators to support the most common mediation functionalities as well as +advanced functionalities.

+ +

Built in mediator capabilities of ESB provide functionality to match +incompatible protocols, data formats and interaction patterns across different +resources. Data can be split, cloned, aggregated and enriched, allowing ESB to +match the different capabilities of services. XQuery and XSLT allows rich +transformations on the messages. Rule based message mediation allows user to +cope with the uncertainty of business logic. Content based routing using XPath +filtering is supported in different flavors, allowing users to get the most +convenient configuration experience. Built in capability to handle transactions +allows message mediation to be done transactionally inside the ESB. With the +Eventing capabilities of ESB, EDA based components can be easily +interconnected. With features like throttling and caching integrated in to the +message mediation, powerful interconnections can be made, allowing ESB to be +used in the front end of organizations SOA infrastructure.

+ +

ESB mediation framework is designed from the ground up to be extensible. +Everyday users write their own custom mediators to facilitate their custom +requirements.

+ +

Now let's briefly look at how the mediation framework works.

+ +

How does a mediator work?

+ +

A mediator is a full powered processing unit in ESB. In run-time it has +access to all the parts of ESB along with the current message. Usually a +mediator is configured using XML. Different mediators have their own XML +configurations.

+ +

At the run-time a Message is injected in to the mediator with the ESB +run-time information. Then this mediator can do virtually anything with the +message. Here are some examples of mediator functionalities.

+
    +
  • Drop Mediator : Drops a message, stopping further processing of the + message
  • +
  • Send Mediator : Send the message out, using information inside the + message or according to some external configuration
  • +
  • Script Mediator : Executes a scripting language with the message
  • +
  • Filter Mediator : Filter messages using XPath
  • +
  • XSLT Mediator : Do XSLT transformations on messages
  • +
+ +

Wide range usage of mediators is visible through the above few examples.

+ +

Also mediators are considered as one of the main mechanisms for extending +ESB. A user can write a mediator and put it in to ESB. This custom mediator and +any other built in mediator will be exactly same from the API and the +privileges.

+ +

Sequences

+ +

Sequence is a List Mediator of the ESB. That means it can hold other +mediators and execute them. It is a part of the core of ESB and message +mediation cannot live without this mediator. When a message is delivered to a +sequence, it sends the message through all it's child mediators.

+ +

There are two types of sequences.

+ +

In-line Sequences

+ +

<sequence name="string">other mediators</sequence>

+ +

In-line sequences has their child mediators defined inside the sequence +itself.

+ +

Named Sequences

+ +

<sequence key="name"/>

+ +

Named sequences refer other sequences using a key. This allows re-using of +sequences.

+ +

There are two predefined sequences. They are called "main" and "fault". If a +user doesn't specify these two sequences in the configuration, default +sequences will be created automatically.

+ +

Here are the default configurations for main and fault

+ +

Main:

+
  <syn:sequence name="main" xmlns:syn="http://ws.apache.org/ns/synapse">
+      <syn:log/>
+      <syn:drop/>
+  </syn:sequence>
+ +

Fault:

+
  <syn:sequence name="fault" xmlns:syn="http://ws.apache.org/ns/synapse">
+      <syn:log level="full">
+      <syn:property name="MESSAGE" value="Executing default&quot;fault&quot; sequence"/>
+      <syn:property name="ERROR_CODE" expression="get-property('ERROR_CODE')"/>
+      <syn:property name="ERROR_MESSAGE" expression="get-property('ERROR_MESSAGE')"/>
+      </syn:log>
+      <syn:drop/>
+  </syn:sequence>
+  
+ +

All the messages that are not for proxy services, will be sent through the +Main Sequence.

+ +

A sequence can have an error handler. Error handler is again another +sequence. If an error occurs while executing a sequence, its error handler will +be called. Every sequence has an error handler. If one isn't explicitly +specified, fault sequence will be treated as the error handler.

+ +

How does a message comes to a mediator?

+ +

There are two operational modes in the ESB. They are message mediation and +proxy services. Message mediation is all about mediators. Proxy services can +use message mediation as well.

+ +

Message Mediation

+ +

A message comes to the main sequence of the ESB if the message is not for +any of the proxy services defined in the ESB.

+ +

Then this message goes through each of the mediators inside the main +sequence.

+ +

If the message is sent to an Endpoint from the main sequence, response +message will also comes to the main sequence.

+ +

Response message will also go through every child mediator of main +sequence

+ +

If an error occurs in a sequence, message will go through sequence's fault +sequence.

+ +

Proxy Services

+ +

Proxy service can have 3 sequences. Depending on the message path these +three sequences can be executed. All the three sequences are optional.

+
    +
  1. In Sequence : A request message coming to a proxy service will go through + this sequence if the sequence is specified.
  2. +
  3. Out Sequence : A response message coming from the actual endpoint will go + through this sequence if the sequence is specified.
  4. +
  5. Fault Sequence : If an error occurs withing the proxy service operation, + message will go through this sequence
  6. +
+ +

As mentioned earlier, every sequence is a collection of mediators. A message +delivered to a sequence will go through all its child mediators.

+ +

WSO2 ESB has a built in sequence editor which helps user to develop/edit +sequences. The Sequence Editor Guide gives +an introduction to the usage of the sequence editor. Following is the catalog +of the built in mediators of WSO2 ESB.

+ +

The Mediator Catalog

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Category Name Description
CoreSendSend a message out
+ Log Logs a message
+ Property Set or remove properties associated with the message
+ Sequence Refer a sequence
+ EventSend event notifications to an event source
+ Drop Drops a message
+ Enrich Enriches a message
+ EnqueueCreate a enqueue meadiator
FilterFilter Filter a messages using XPath, If else kind of logic
+ Out Inbuilt filter for choosing messages in ESB out path
+ InInbuilt filter for choosing messages in ESB in path
+ Switch Filter messages using XPath, Switch logic
+ RouterRoute messages based on XPath filtering
+ Conditional RouterRoute messages based on 'Condition'
+ ValidateSchema validation for messages
Transform XSLT XSLT transformations
+ XQueryXQuey
+ Header Sets or remove SOAP headers
+ Fault Create SOAP Faults
+ URLRewriteCreate a rewrite mediator
+ Relay Transformer XSLT transformations
Advanced CacheEvaluate messages based on weather the same message came to the ESB +
+ Clone Clones a message
+ Iterate Splits a message
+ AggregateCombines messages
+ CalloutBlocking web services calls
+ TransactionExecutes a set of mediators transactionally
+ ThrottleLimit the number of messages
+ RMSequenceReliable messaging
+ DBReportWrites data to a database
+ DBLookupRetrieve information from a database
+ RuleExecutes Rules
+ EntitlementFine grained authorization
+ OAuth2-legged OAuth support
Extension Class Create and execute a custom mediator
+ POJOCommand Executes a custom command
+ ScriptExecutes a mediator written in a Scripting language
+ SpringCreate a mediator managed by Spring
+ SmooksCreate a smooks meadiator
+ + Store + Create Mediator to Store messages in a Message store
+ + + diff --git a/docs/xdoc/mediators/aggregate.xml b/docs/xdoc/mediators/aggregate.xml new file mode 100644 index 0000000000..3ea62a44ff --- /dev/null +++ b/docs/xdoc/mediators/aggregate.xml @@ -0,0 +1,107 @@ + + + + + + WSO2 ESB - Aggregate Mediator + + + + + +

Aggregate Mediator

+ +

The aggregate mediator implements the Message Aggregator EIP and will +aggregate the messages or responses for splitted messages using either the +clone or iterate mediators. At the same time it can aggregate messages on the +presence of matching elements specified by the correlateOn XPATH expression. +Aggregate will collect the messages coming into it until the messages collected +on the aggregation satisfies the complete condition. The completion condition +can specify a minimum or maximum number of messages to be collected, or a +timeout value in seconds, after which the aggregation terminates. On completion +of the aggregation it will merge all of the collected messages and invoke the +onComplete sequence on it. The merged message would be created using the XPath +expression specified by the attribute 'expression' on the 'onComplete' element. +

+ +

Syntax

+
 <aggregate [id="id"]>
+   <correlateOn expression="xpath"/>?
+   <completeCondition [timeout="time-in-seconds"]>
+     <messageCount min="int-min" max="int-max"/>?
+   </completeCondition>?
+   <onComplete expression="xpath" [sequence="sequence-ref"]>
+     (mediator +)?
+   </onComplete>
+ </aggregate>
+ +

UI Configuration

+ +
+ + +

Aggregator specific options

+
+ +

Aggregate mediator field descriptions,

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Field nameDescription
Aggregate IDThis optional attribute can be used to aggregate only responses for splitted messages that + are created by a specific clone/iterate mediator. Aggregate ID should be same as the ID of the + corresponding clone/iterate mediator that creates splitted messages. This is particularly useful + when aggregating responses of messages that are created using nested clone/iterate mediators. +
Aggregation ExpressionAn XPath expression specifying based on which elements to aggregate. + Set of messages that's taken for aggregation is determined through + Correlation Expression .
Completion TimeoutTime that the aggregator waits for messages.
Completion Max-messagesMaximum number of messages that can exist in an aggregation.
Completion Min-messagesMinimum number of messages required for the aggregation to complete. +
Correlation Expression An XPath expression specifying the pattern messages will be collected + for aggregation. Specific aggregation condition will be set through + Aggregation Expression .
+ +

Example

+
+<outSequence>
+    <aggregate>
+        <onComplete expression="//m0:getQuoteResponse"
+                xmlns:m0="http://services.samples">
+            <send/>
+        </onComplete>
+    </aggregate>
+</outSequence>
+
+ +

In this scenario the mediator aggregates the responses coming in to ESB and on completion it sends the + aggregated message through the send mediator.

+ + diff --git a/docs/xdoc/mediators/cache.xml b/docs/xdoc/mediators/cache.xml new file mode 100644 index 0000000000..ba28839138 --- /dev/null +++ b/docs/xdoc/mediators/cache.xml @@ -0,0 +1,118 @@ + + + + + + WSO2 ESB - Cache Mediator + + + + + +

Cache Mediator

+ +

When a message comes to the Cache mediator, it checks weather an equivalent message is +seen before. If the message is seen before it will execute a specified +sequence. It uses message hashes for checking the equivalence of messages. Once the Cache +meditor finds that the message is a cached message, it will fetch +the cached response and prepare ESB for sending the response. If a +sequence is specified for a cache hit, user can send back the response message +within this sequence using a send mediator. If a sequence is not specified +cached response is sent back to the requestor.

+ +

Syntax

+
 <cache [id="string"] [hashGenerator="class"] [timeout="seconds"] [scope=(per-host | per-mediator)]
+     collector=(true | false) [maxMessageSize="in-bytes"]>
+   <onCacheHit [sequence="key"]>
+     (mediator)+
+   </onCacheHit>?
+   <implementation type=(memory | disk) maxSize="int"/>
+ </cache>
+ +

The cache mediator will evaluate the hash value of an incoming message as +described in the optional hash generator implementation (which should be a +class implementing the org.wso2.caching.digest.DigestGenerator interface). The +default hash generator is 'org.wso2.caching.digest.DOMHashGenerator'. If the +generated hash value has been found in the cache then the cache mediator will +execute the onCacheHit sequence which can be specified inline or referenced. +The cache mediator must be specified with an 'id' and two instances with this +same 'id' that correlates the response message into the cache for the request +message hash. The optional 'timeout' specifies the valid duration for cached +elements, and the scope defines if mediator instances share a common cache per +every host instance, or per every cache mediator pair (i.e. 'id') instance. The +'collector' attribute 'true' specifies that the mediator instance is a response +collection instance, and 'false' specifies that its a cache serving instance. +The maximum size of a message to be cached could be specified with the optional +'maxMessageSize' attributes in bytes and defaults to unlimited. Finally the +'implementation' element may define if the cache is disk or memory based, and +the 'maxSize' attribute defines the maximum number of elements to be cached. +

+ +

+ +

UI Configuration

+ +
    +
  • Cache Id: Id for the cache configuration. You should have same id for a + cache mediator instance in incoming path and the corresponding mediator + instance in outgoing message path.
  • +
  • Cache Scope: Scope of the cache. This is important if the service is + deployed in a cluster. +
      +
    • Per-Host: The cache is kept only for the current host in a cluster. +
    • +
    • Per-Mediator: The cache is kept once for the whole cluster.
    • +
    +
  • +
  • Cache Type: Whether the mediator is in the incoming path (check request) + or the outgoing path (cache the response). +
      +
    • Finder: Set if the message is incoming path. This indicate the + mediator find for the request hash of each incoming message.
    • +
    • Collector: Set if the message is in outgoing path. This indicate the + mediator collect the response message in the cache.
    • +
    +
  • +
  • Hash Generator: The logic for finding the hash which check against each + incoming message. Default to org.wso2.caching.digest.DOMHASHGenerator
  • +
  • Cache Timeout: The cache timeout(The time to keep the cache before + expiring) in seconds.
  • +
  • Maximum Message Size: The limit of the message to cache in bytes.
  • +
  • Implementation Type: Currently only "In-Memory" is available.
  • +
  • On Cache Hit: Specify the sequence to follow when the cache mediator is + hit. You can either specify it as anonymous where you can define child + mediators for the Cache mediator or you can refer a named sequence of + mediators from the registry.
  • +
+ +

Example

+
<definitions xmlns="http://ws.apache.org/ns/synapse">
+  <in>
+    <cache timeout="20" scope="per-host" collector="false"
+      hashGenerator="org.wso2.caching.digest.DOMHASHGenerator">
+      <implementation type="memory" maxSize="100"/>
+    </cache>
+
+    <send>
+      <endpoint>
+        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
+      </endpoint>
+    </send>
+  </in>
+  
+  <out>
+    <cache collector="true"/>
+    <send/>
+  </out>
+</definitions>
+ +

In this example, first message will be sent to the endpoint specified as +cache is not hit. The responce will come to the cache mediator inside the out +meduator and this will cache the response. The second equal message will match +the cache and response will be directly fetch from the cache and sent to the +requestor. This happens because no onCacheHit sequence is defined.

+ + diff --git a/docs/xdoc/mediators/callout.xml b/docs/xdoc/mediators/callout.xml new file mode 100644 index 0000000000..bc5edc9123 --- /dev/null +++ b/docs/xdoc/mediators/callout.xml @@ -0,0 +1,78 @@ + + + + + + WSO2 ESB - Callout Mediator + + + + + +

Callout Mediator

+

+ The <callout> mediator performs a blocking external service invocation + during mediation. The serviceURL and the optional action specifies the + parameters for this external call. The source element specifies the payload for + the request message using an XPath expression; or a registry key that will be + used. The target element specifies a node, at which the resulting payload will + be attached into the current message, or the name of a key/property using which + the response would be attached to the current message context as a property. +

+ +

+ As the callout mediator performs a blocking call, it cannot use the default + non-blocking http/s transports based on Java NIO, and thus defaults to using + the samples/axis2Client/client_repo/conf/axis2.xml as the Axis2 configuration, + and samples/axis2Client/client_repo as the client repository unless these are + specified separately +

+

Syntax

+
 
+  <callout serviceURL="string" [action="string"]>
+      <configuration [axis2xml="string"] [repository="string"]/>?
+      <source xpath="expression" | key="string">
+      <target xpath="expression" | key="string"/>
+  </callout>
+

UI Configuration

+

+ +

+

+ Figure 1: Callout mediator specific options +

+

+ Callout mediator specific options, +

+
    +
  • ServiceURL - URL of the service
  • +
  • Action - SOAP action
  • +
  • Axis2 Repository - Full path to Axis2 Repository Location, This is the place where services and modules are
  • +
  • Axis2 XML - Full path to Axis2 XML file location
  • +
  • Source - Payload of the message
  • +
  • Target - A node to attach the response element
  • +
+ +

Example

+
+<callout serviceURL="http://localhost:9000/services/SimpleStockQuoteService"
+         action="urn:getQuote">
+    <source xmlns:s11="http://schemas.xmlsoap.org/soap/envelope/"
+            xmlns:s12="http://www.w3.org/2003/05/soap-envelope"
+            xpath="s11:Body/child::*[fn:position()=1] | s12:Body/child::*[fn:position()=1]"/>
+    <target xmlns:s11="http://schemas.xmlsoap.org/soap/envelope/"
+            xmlns:s12="http://www.w3.org/2003/05/soap-envelope"
+            xpath="s11:Body/child::*[fn:position()=1] | s12:Body/child::*[fn:position()=1]"/>
+</callout>
+
+
+ +

In this scenario, Callout mediator does the direct service invocation to the StockQuoteService using the client + request, get the response and set it as the first child of the SOAP message body. Then using the send mediator, + the message is sent back to the client.

+ +

+ + diff --git a/docs/xdoc/mediators/class.xml b/docs/xdoc/mediators/class.xml new file mode 100644 index 0000000000..0f2645efb2 --- /dev/null +++ b/docs/xdoc/mediators/class.xml @@ -0,0 +1,163 @@ + + + + + + WSO2 ESB - Class Mediator + + + + + +

Class Mediator

+ +

The class mediator creates an instance of a custom specified class and sets it as a mediator. The class must + implement the org.apache.synapse.api.Mediator interface. If any properties are specified, the corresponding + setter methods are invoked on the class, once, during initialization.

+ +

Syntax

+
 <class name="class-name">
+   <property name="string" value="literal"> 
+    (either literal or XML child)
+   </property>
+ </class>
+
+ +

UI Configuration

+ Figure 1: Adding a Class mediator +

+

+ Clicking on the 'Class' mediator option as shown in above figure, will open + up the 'Class' mediator specific options. You can specify the specific implementaion class and load it by + clicking 'LoadClass' button. Once you load the class, you'll see the configuration options + as in figure2.

+
+

+ Class mediator configuration descriptions +

+
    +
  • + Class Name: The class name of the class. You have to give the qualified name of the class and click + "Load Class" button. +
  • +
  • + Properties defined for Class mediator: This list the properties with setter functions of the uploaded class. + Following fields are listed for each property. +
      +
    • + Property Name - Name of the property. +
    • +
    • + Property Value - The value to be set to the property. +
    • +
    • + Action - Link to delete the unused properties, from the list. +
    • +
    +
  • +
+ +

Example

+
<definitions xmlns="http://ws.apache.org/ns/synapse">
+
+        <sequence name="fault">
+            <makefault>
+                <code value="tns:Receiver" xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
+                <reason value="Mediation failed."/>
+            </makefault>
+            <send/>
+        </sequence>
+
+        <sequence name="main" onError="fault">
+            <in>
+                <send>
+                    <endpoint name="stockquote">
+                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
+                    </endpoint>
+                </send>
+            </in>
+            <out>
+                <class name="samples.mediators.SimpleClassMediator">
+                    <property name="varible1" value="10"/>
+                    <property name="varible2" value="5"/>
+                </class>
+                <send/>
+            </out>
+        </sequence>
+
+    </definitions>
+ +

In this configuration, ESB hands over the request message to the specified endpoint, which sends it to the + Axis2 server running on port 9000. But the response message is passed through the class mediator before sending it + back to the client. Two parameters named "varible1" and "varible2" are passed to the instance mediator + implementation class(SimpleClassMediator). Look at the following sample class mediator. Note how the + SynapseMessageContext and to the full Synapse API in there.

+

A simple class mediator implementaion.

+ +
package samples.mediators;
+
+    import org.apache.synapse.MessageContext;
+    import org.apache.synapse.Mediator;
+    import org.apache.axiom.om.OMElement;
+    import org.apache.axiom.om.OMAbstractFactory;
+    import org.apache.axiom.om.OMFactory;
+    import org.apache.axiom.soap.SOAPFactory;
+    import org.apache.commons.logging.Log;
+    import org.apache.commons.logging.LogFactory;
+
+    import javax.xml.namespace.QName;
+
+    public class SimpleClassMediator implements Mediator {
+
+        private static final Log log = LogFactory.getLog(DiscountQuoteMediator.class);
+
+        private String varible1="10";
+
+        private String varible2="10";
+
+        private int varible3=0;
+
+        public DiscountQuoteMediator(){}
+
+        public boolean mediate(MessageContext mc) {
+            // Do somthing useful..
+            // Note the access to the Synapse Message context
+            return true;
+        }
+
+        public String getType() {
+            return null;
+        }
+
+        public void setTraceState(int traceState) {
+            traceState = 0;
+        }
+
+        public int getTraceState() {
+            return 0;
+        }
+
+        public void setvarible1(String newValue) {
+            varible1=newValue;
+        }
+
+        public String getvarible1() {
+            return varible1;
+        }
+
+        public void setvarible2(String newValue){
+            varible2=newValue;
+        }
+
+        public String getvarible2(){
+            return varible2;
+        }
+    }
+ +

A fully working sample is availble. See synapase configuration lanaguge guide for detailed(under + section called class mediator) working sample.

+ + + diff --git a/docs/xdoc/mediators/clone.xml b/docs/xdoc/mediators/clone.xml new file mode 100644 index 0000000000..ca8938e30e --- /dev/null +++ b/docs/xdoc/mediators/clone.xml @@ -0,0 +1,94 @@ + + + + + + WSO2 ESB - Clone Mediator + + + + + +

Clone Mediator

+ +

As the name suggests clone meditor can be used to clone a message in to +several messages.

+ +

The clone mediator closely resembles the Message Splitter EIP and will split +the message into number of identical messages which will be processed in +parallel. They can also be set to process sequentially by setting +the value of the optional 'sequential' attribute to 'true'. +The original message cloned can be continued or dropped depending on +the boolean value of the optional 'continueParent' attribute. Optionally a +custom 'To' address and/or a 'Action' may be specified for cloned messages. +The optional 'id' attribute can be used to identify the clone mediator which +created a particular splitted message when nested clone mediators are used. +This is particularly useful when aggregating responses of messages that are +created using nested clone mediators. +

+ +

Syntax

+
 <clone [id="id"] [continueParent=(true | false)] [sequential=(true | false)]>
+   <target [to="uri"] [soapAction="qname"] [sequence="sequence_ref"] [endpoint="endpoint_ref"]>
+     <sequence>
+       (mediator)+
+     </sequence>?
+     <endpoint>
+       endpoint
+     </endpoint>?
+   </target>+
+ </clone>
+ +

UI Configuration

+ +
+ + +

Figure 1: Clone mediator options

+
+ +

Clone mediator field descriptions,

+
    +
  • Clone ID - This can be used to identify messages created by this clone mediator. This is + particularly useful when aggregating responses of messages that are created using nested + iterate mediators. +
  • +
  • Sequential Mediation - If "Yes" created messages will be processed sequentially, otherwise + they will be processed in parallel. +
  • +
  • Continue Parent - If "Yes" the original message will be continued. If + "No" the original message will be dropped.
  • +
  • Number of clones - Number of clones created. This can be controlled by + adding one or more clone targets by clicking Add Clone Target.Targets can then have it's own set of mediators.
  • +
+ +

+ +

Figure 2: Adding a clone target

+ +

For more information about target refer Target.

+ + + +

Example

+
+<clone xmlns="http://ws.apache.org/ns/synapse">
+   <target>
+      <endpoint name="endpoint_urn_uuid_73A47733EB1E6F30812921609540392-849227072">
+         <default />
+      </endpoint>
+   </target>
+   <target sequence="test1" />
+</clone>
+
+
+ +

In this example the clone mediator clones messages and redirect them two a default endpoint and an existing sequence.

+ + +

+ + diff --git a/docs/xdoc/mediators/conditionalrouter.xml b/docs/xdoc/mediators/conditionalrouter.xml new file mode 100644 index 0000000000..ec186a5f9d --- /dev/null +++ b/docs/xdoc/mediators/conditionalrouter.xml @@ -0,0 +1,66 @@ + + + + + + WSO2 ESB - Conditional Router Mediator + + + + + +

Conditional Router Mediator

+ +

Conditional Router mediator is used to route messages based on 'Condition' provided by user.

+ +

+The Conditional Router mediator can be used to specify the routing of the message according to given conditions. Mediator checks whether the
+ 'Condition' evaluates to true and mediates using the target sequence. + Matching route will break the router if the 'Break after route' is set to true. +

+ +

Syntax

+ +
+ <conditionalRouter continueAfter="(true|false)">
+    <route breakRoute="(true|false)">
+      <condition ../>
+      <target ../>
+    </route>+
+   </conditionalRouter>
+
+ +

UI Configuration

+ +

conditional router Mediator

+ +

Figure1: Conditional Router Mediator

+ +

Configurations

+ +

User can define any number of routes. Each and every route must contain a 'condition' which is to be evaluated and a predefined + 'Target' sequence, which will be used to mediate further. +

+ +

conditional router Mediator

+

Figure 2: Route Configuration

+ +
    +
  • +Continue after routing: (Yes/No), Whether to continue the routing if any of the child routes are executed. The default value is No. +
  • +
  • +Break after route : If set to true, matching route will break the router. +
  • +
  • +Evaluator Expression : Route condition . +
  • +
  • +Target Sequence : Target sequence need to be provided as registry key/local entry to do further mediate processing. +
  • +
+ + + diff --git a/docs/xdoc/mediators/dblookup.xml b/docs/xdoc/mediators/dblookup.xml new file mode 100644 index 0000000000..47edf27e30 --- /dev/null +++ b/docs/xdoc/mediators/dblookup.xml @@ -0,0 +1,231 @@ + + + + + + WSO2 ESB - DBLookup Mediator + + + + + +

DBLookup Mediator

+ +

The dblookup mediator is capable of executing an arbitrary SQL select +statement, and then set some resulting values as local message properties on +the message context. The DB connection used maybe looked up from an external +DataSource or specified in-line, in which case an Apache DBCP connection pool +is established and used.

+ +

In-lined Data Source

+
    +
  • driver - Database driver class name
  • +
  • url - Database URL
  • +
  • user - User name for access Database
  • +
  • password Password for access Database
  • +
+ +

This new Datasource is based on Apache DBCP connection pools. This +connection pool support the following configuration properties:

+
    +
  • autocommit = true | false
  • +
  • isolation = Connection.TRANSACTION_NONE | + Connection.TRANSACTION_READ_COMMITTED | + Connection.TRANSACTION_READ_UNCOMMITTED | + Connection.TRANSACTION_REPEATABLE_READ | + Connection.TRANSACTION_SERIALIZABLE
  • +
  • initialsize = int
  • +
  • maxactive = int
  • +
  • maxidle = int
  • +
  • maxopenstatements = int
  • +
  • maxwait = long
  • +
  • minidle = int
  • +
  • poolstatements = true | false
  • +
  • testonborrow = true | false
  • +
  • testonreturn = true | false
  • +
  • testwhileidle = true | false
  • +
  • validationquery = String
  • +
+ +

External Data Source

+
    +
  • dsName - The name of the Datasource to be looked up
  • +
  • icClass - Initial context factory class. The + corresponding java environment property is + java.naming.factory.initial
  • +
  • url - The naming service provider url . The + corresponding java environment property is + java.naming.provider.url
  • +
  • user - This is corresponding to the java environment + property java.naming.security.principal
  • +
  • password - This is corresponding to the java environment + property This is corresponding to the java environment property + java.naming.security.principal
  • +
+ +

SQL Statements

+
    +
  • sql - One or more SQL Statements
  • +
  • parameter - Specify how the values of parameter in the + SQL would be calculated. A value can be static literal text and can be + calculated at runtime based on the given expression.
  • +
  • result - Specify how to deal with rerun result from + Database query execution.
  • +
+ +

More than one statement may be specified, and the SQL statement may specify +parameters which could be specified as values or XPath expressions. The types +of parameters could be any valid SQL types. Only the first row of a result set +will be considered and any others are ignored. The single +<result> element contains the 'name' +and the 'column' attributes. The 'name' +attribute defines the name under which the result is stored in the Synapse +message context, and the column attribute specifies a column number or name . +

+ +

Syntax

+
<dblookup>
+   <connection>
+     <pool>
+      (
+       <driver/>
+       <url/>
+       <user/>
+       <password/>
+     |
+       <dsName/>
+       <icClass/>
+       <url/>
+       <user/>
+       <password/>
+     )
+       <property name="name" value="value"/>*
+     </pool>
+   </connection>
+   <statement>
+     <sql>select something from table where something_else = ?</sql>
+     <parameter [value="" | expression=""] type="CHAR|VARCHAR|LONGVARCHAR|NUMERIC|DECIMAL|BIT|TINYINT|SMALLINT|INTEGER|BIGINT|REAL|FLOAT|DOUBLE|DATE|TIME|TIMESTAMP"/>*
+     <result name="string" column="int|string"/>*
+   </statement>+
+</dblookup>
+ +

UI Configuration

+ +

+

+ +
+

Figure 1: DBLookup mediator options

+
+ +

DBLookup mediator options field descriptions,

+
    +
  • Connection Information - Specify whether the connection is taken from a + connection pool or from a data source
  • +
  • Driver - Database driver
  • +
  • Url - JDBC URL of the database that data will be looked up.
  • +
  • User - Username that's used to connect to the database.
  • +
  • Password - Password used to connect to the database.
  • +
+ +

Data sources

+ +

Carbon Datasources

+ +

If existing data source is choosen, clicking "Load Data Sources" will give +the available datasource. Then a data source can be selected.

+
+ +

Figure 2: Carbon Datasources

+
+ +

External Datasources

+ +

Like in Pool connection data source configuration properties should be +specified.

+
+ +

Figure 3: External Datasources

+
+ + +

Adding properties

+ +
+ + +

Figure 4: Adding a property

+
+ +

Property field descriptions,

+
    +
  • autocommit = true | false
  • +
  • isolation = Connection.TRANSACTION_NONE | + Connection.TRANSACTION_READ_COMMITTED | + Connection.TRANSACTION_READ_UNCOMMITTED | + Connection.TRANSACTION_REPEATABLE_READ | + Connection.TRANSACTION_SERIALIZABLE
  • +
  • initialsize = int
  • +
  • maxactive = int
  • +
  • maxidle = int
  • +
  • maxopenstatements = int
  • +
  • maxwait = long
  • +
  • minidle = int
  • +
  • poolstatements = true | false
  • +
  • testonborrow = true | false
  • +
  • testwhileidle = true | false
  • +
  • validationquery = String
  • +
+ +

Adding SQL statements

+
    +
  1. Click Add Statement link shown in figure 2 and it'll open up the screen + where you could enter SQL statement option. This is shown in figure 3.
  2. +
  3. More than one statement may be specified.
  4. +
+
    +
  • The SQL statement may specify parameters which could be specified as + values or XPath expressions.
  • +
  • The types of parameters could be any valid SQL types. Only the first row + of a result set will be considered and any others are ignored.
  • +
+ +
+ + +

Figure 5: Adding SQL statements

+
+ +

Example

+
+
+<dblookup xmlns="http://ws.apache.org/ns/synapse">
+    <connection>
+        <pool>
+            <driver>org.apache.derby.jdbc.ClientDriver</driver>
+            <url>jdbc:derby://localhost:1527/esbdb;create=false</url>
+            <user>esb</user>
+            <password>esb</password>
+        </pool>
+    </connection>
+    <statement>
+        <sql>select * from company where name =?</sql>
+        <parameter expression="//m0:getQuote/m0:request/m0:symbol"
+                   xmlns:m0="http://services.samples/xsd" type="VARCHAR"/>
+        <result name="company_id" column="id"/>
+    </statement>
+</dblookup>
+
+ +

In this example, when a message arrives at dblookup mediator, it opens a connection to the database and executes the + SQL query. The SQL query use '?' character for attributes that will be filled at runtime. The parameters define how + to calculate the value of those attributes at runtime. In this sample a dblookup mediator has been used + to extract 'id' of the company from the company database using the symbol which is evaluated using an xpath against + the SOAP envelope.

+ + +

+ + diff --git a/docs/xdoc/mediators/dbreport.xml b/docs/xdoc/mediators/dbreport.xml new file mode 100644 index 0000000000..4f4377bb84 --- /dev/null +++ b/docs/xdoc/mediators/dbreport.xml @@ -0,0 +1,165 @@ + + + + + + WSO2 ESB - DBReport Mediator + + + + + +

DBReport Mediator

+ +

The dbreport mediator is very similar to the dblookup mediator, but writes +information to a Database, using the specified insert SQL statement. For +configuration information about db mediators , refer dblookup mediator guide

+ +

Syntax

+
<dbreport>
+   <connection>
+     <pool>
+      (
+       <driver/>
+       <url/>
+       <user/>
+       <password/>
+     |
+       <dsName/>
+       <icClass/>
+       <url/>
+       <user/>
+       <password/>
+     )
+       <property name="name" value="value"/>*
+     </pool>
+   </connection>
+   <statement>
+     <sql>insert into something values(?, ?, ?, ?)</sql>
+     <parameter [value="" | expression=""] type="CHAR|VARCHAR|LONGVARCHAR|NUMERIC|DECIMAL|BIT|TINYINT|SMALLINT|INTEGER|BIGINT|REAL|FLOAT|DOUBLE|DATE|TIME|TIMESTAMP"/>*
+    </statement>+
+</dblreport>
+ +

UI Configuration

+ +
+ + +

Figure 1: DBReport options

+
+ +

DBReport mediator options field descriptions,

+
    +
  • Connection Information - Specify whether the connection is taken from a + connection pool or from a data source
  • +
  • Driver - Database driver
  • +
  • Url - JDBC URL of the database that data will be looked up.
  • +
  • User - Username that's used to connect to the database.
  • +
  • Password - Password used to connect to the database.
  • +
+ +

Data sources

+ +

Carbon Datasources

+ +

If existing data source is choosen, clicking "Load Data Sources" will give +the available datasource. Then a data source can be selected.

+
+ +

Figure 2: Carbon Datasources

+
+ + +

External Datasources

+ +

Like in Pool connection data source configuration properties should be +specified.

+
+ +

Figure 3: External Datasources

+
+ + +

Adding properties

+ +

Properties can be added to the DBReport Mediator by clicking Add Property,

+ +
+ +

Figure 4: Adding a property

+
+ +

Property field descriptions,

+
    +
  • autocommit = true | false
  • +
  • isolation = Connection.TRANSACTION_NONE | + Connection.TRANSACTION_READ_COMMITTED | + Connection.TRANSACTION_READ_UNCOMMITTED | + Connection.TRANSACTION_REPEATABLE_READ | + Connection.TRANSACTION_SERIALIZABLE
  • +
  • initialsize = int
  • +
  • maxactive = int
  • +
  • maxidle = int
  • +
  • maxopenstatements = int
  • +
  • maxwait = long
  • +
  • minidle = int
  • +
  • poolstatements = true | false
  • +
  • testonborrow = true | false
  • +
  • testwhileidle = true | false
  • +
  • validationquery = String
  • +
+ +

Adding SQL statements

+
    +
  1. Click Add Statement link shown in figure 2 and it'll open up the screen + where you could enter SQL statement option. This is shown in figure 3.
  2. +
  3. More than one statement may be specified.
  4. +
+
    +
  • The SQL statement may specify parameters which could be specified as + values or XPath expressions.
  • +
  • The types of parameters could be any valid SQL types. Only the first row + of a result set will be considered and any others are ignored.
  • +
+ +
+ + +

Figure 5: Adding SQL statements

+
+ +

Example

+
+<dbreport xmlns="http://ws.apache.org/ns/synapse">
+    <connection>
+        <pool>
+            <driver>org.apache.derby.jdbc.ClientDriver</driver>
+            <url>jdbc:derby://localhost:1527/esbdb;create=false</url>
+            <user>esb</user>
+            <password>esb</password>
+        </pool>
+    </connection>
+    <statement>
+        <sql>update company set price=? where name =?</sql>
+        <parameter expression="//m0:return/m1:last/child::text()"
+                   xmlns:m0="http://services.samples" xmlns:m1="http://services.samples/xsd" type="DOUBLE"/>
+        <parameter expression="//m0:return/m1:symbol/child::text()"
+                   xmlns:m0="http://services.samples" xmlns:m1="http://services.samples/xsd" type="VARCHAR"/>
+    </statement>
+</dbreport>
+
+ +

This sample demonstrate simple database write operations. The dbreport mediator writes + to a table using the message details. It works the same as the dblookup mediator. In this sample , dbreport + mediator is used for updating the stock price of the company using the last quote value which is calculated by + evaluating an XPath against the response message. +

+ + + +

+ + diff --git a/docs/xdoc/mediators/drop.xml b/docs/xdoc/mediators/drop.xml new file mode 100644 index 0000000000..7caffa75f4 --- /dev/null +++ b/docs/xdoc/mediators/drop.xml @@ -0,0 +1,41 @@ + + + + + + WSO2 ESB - Send Mediator + + + + + +

Drop Mediator

+ +

Drop mediator stops the processing of the current message.

+ +

Syntax

+
 <drop/>
+ +

UI Configuration

+ +

none.

+ +

Usage Scenario

+
<definitions xmlns="http://ws.apache.org/ns/synapse">    
+    <filter source="get-property('To')" regex=".*/StockQuote.*">
+        <send>
+            <endpoint>
+                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
+            </endpoint>
+        </send>
+        <drop/>
+    </filter>
+    <send/>
+</definitions> 
+ +

In this scenario message is dropped after it is sent to the end point. This +will prevent message being sent twice from the in-path.

+ + diff --git a/docs/xdoc/mediators/enqueue.xml b/docs/xdoc/mediators/enqueue.xml new file mode 100644 index 0000000000..0af9015a5e --- /dev/null +++ b/docs/xdoc/mediators/enqueue.xml @@ -0,0 +1,52 @@ + + + + + + WSO2 ESB -Enqueue Mediator + + + + + +

Enqueue Mediator

+ +

Enqueue mediator works with priority mediation. It can be used to process a message
+ using a priority executor with a priority defined in priority executor. +

+ + +

Syntax

+
+<enqueue [executor="string"] [sequence="string"] [priority="integer"] > 
+</enqueue>
+
+ +

UI Configuration

+ +

Enqueue Mediator

+ +

Figure1: Enqueue Mediator

+ +

+ You have the following configuration under the Enqueue mediator. +

+ +
    +
  • + Executor: Name of the priority executor. +
  • +
  • + Priority: Level of the priority (Integer) that message will execute. Given priority level should be defined in the + priority executor. +
  • +
  • + Sequence: Name(Key) of the sequence that will process the message. Use registry browser to select a sequence + from registry. +
  • +
+ + + diff --git a/docs/xdoc/mediators/enrich.xml b/docs/xdoc/mediators/enrich.xml new file mode 100644 index 0000000000..69032f6b8b --- /dev/null +++ b/docs/xdoc/mediators/enrich.xml @@ -0,0 +1,107 @@ + + + + + + WSO2 ESB - Enrich Mediator + + + + + +

Enrich Mediator

+ +

Enrich Mediator can process a message based on a given source configuration +and then perform the specified action on the message by using the target configuration. +It basically gets an OMElement using the configuration specified in the source and +then modify the message by putting it on the current message using the configuration +in the target. +

+ +

+ +

Syntax

+
 <enrich>
+       <source [clone=true|false] [type=custom|envelope|body|property|inline] xpath="" property="" />
+       <target [action=replace|child|sibiling] [type=custom|envelope|body|property|inline] xpath="" property="" />
+ </enrich>
+ +

+ +

UI Configuration

+ +

+ +

Enrich Mediator Screenshot

+ +

You have the following configuration under the Enrich mediator.

+ +
    +
  • Source Configuration +
      +
    • Clone : By setting the clone configuration, the message can be cloned or + else use as a reference during the enriching. The default value for + clone is false. +
        +
      • True/False
      • +
      +
    • +
    • Type : Specifies that the type that the mediator use from the original message to enrich the modified + message that pass through the mediator. +
        +
      • Custom : Custom XPath value +

        If there are any namespaces involved in the XPath expression, you + can specify it in the Namespace Editor.

        + +

        Namespace Editor Screenshot

        +
      • +
      • Envelope : Envelope of the original message will be used for enriching. +
      • +
      • Body : Body of the original message will be used for enriching.
      • +
      • Property : Specifies a property.
      • +
      • Inline : Specifies an inline XML value
      • +
      +
    • +
    +
  • +
  • Target Configuration +
      +
    • Action : By specifying the action type the relevant action can be applied to outgoing message. +
        +
      • Replace : Replace the xml message based on the target type specified on the target configuration.
      • +
      • Child : Adding as a child of specified target type.
      • +
      • Sibling : Adding as a sibling of specified target type.
      • +
      +
    • +
    • Type : Specifies that the type of enriching the outgoing message. +
        +
      • Custom : Custom XPath value. +

        If there are any namespaces involved in the XPath expression, you + can specify it in the Namespace Editor as in the Source Configuration.

        +
      • +
      • Envelope : Envelope of the original message will be used for enriching. +
      • +
      • Body : Body of the original message will be used for enriching.
      • +
      • Property : Specifies a property.
      • +
      +
    • +
    +
  • +
+ +

Example

+
 <enrich> xmlns="http://ws.apache.org/ns/synapse"
+           <source clone="false" type="envelope" xpath="" property="" />
+           <target action="replace" type="body" xpath="" property="" />
+ </enrich>
+ + +

In this example we are setting the property symbol and later we are logging +it using the log mediator.

+ +

+ + diff --git a/docs/xdoc/mediators/entitlement.xml b/docs/xdoc/mediators/entitlement.xml new file mode 100644 index 0000000000..905e779af1 --- /dev/null +++ b/docs/xdoc/mediators/entitlement.xml @@ -0,0 +1,49 @@ + + + + + + WSO2 ESB - Entitlement Mediator + + + + + +

Entitlement Mediator

+ +

The Entitlement Mediator by passes the requests and evaluates the actions performed by the user against the XACML + policy defined at the Policy Decision Point [WSO2 Identity Server] +

+ +

Syntax

+
+<entitlementService remoteServiceUrl="" remoteServiceUserName="" remoteServicePassword="" />
+
+ + +

UI Configuration

+ +

+ +

Figure 1: Entitlement Mediator Options

+ +

You have the following configurations under the Entitlement Mediator.

+
    +
  • Entitlement Server: Server url of the WSO2 Identity Server which acts as the PDP [e.g.:https://localhost:9443/services]
  • +
  • User Name: This user should have login and manage configuration permissions in the Identity Server
  • +
  • Password: The password corresponding to the user name.
  • +
+

Example

+ +

+
+<entitlementService xmlns="http://ws.apache.org/ns/synapse"
+    remoteServiceUrl="https://localhost:9443/services"
+    remoteServiceUserName="user1" remoteServicePassword="L#k56@" />
+
+

+ + diff --git a/docs/xdoc/mediators/event.xml b/docs/xdoc/mediators/event.xml new file mode 100644 index 0000000000..1ec92004a4 --- /dev/null +++ b/docs/xdoc/mediators/event.xml @@ -0,0 +1,54 @@ + + + + + + WSO2 ESB - Drop Mediator + + + + + +

Event Mediator

+ +

Event mediator publishes events to the given event source. Thus, the +presence of defined event sources are necessary prior to the usage of this +mediator. User can apply any mediation before sending the message to the event +source. This allows features like transformation, logging, filtering to be +applied to a message coming to an Event Source.

+ +

Syntax

+
<event xmlns="http://ws.apache.org/ns/synapse" topic="" [expression=""] />
+ +

UI Configuration

+ +

+
    +
  • Event Source: Select a source from currently available event sources. You + can define event sources from the "Event Sources" panel which can be + accessed from Configure-> Event Sources menu of the right hand side menu + bar.
  • +
+ +

Usage Scenario

+
<!-- Simple Eventing configuration -->
+ <definitions xmlns="http://ws.apache.org/ns/synapse">
+
+     <sequence name="PublicEventSource" >
+            <log level="full"/>
+            <event topic="SampleEventSource"/>
+     </sequence>
+
+     <proxy name="EventingProxy">
+         <target inSequence="PublicEventSource" />
+     </proxy>
+ </definitions>
+ +

In this scenario user has defined an event topic called SampleEventSource. +When a event notification comes to the EventingProxy proxy service, the +messages will be logged and then sent to the event topic.

+ + diff --git a/docs/xdoc/mediators/fault.xml b/docs/xdoc/mediators/fault.xml new file mode 100644 index 0000000000..15ce30c7bb --- /dev/null +++ b/docs/xdoc/mediators/fault.xml @@ -0,0 +1,106 @@ + + + + + + WSO2 ESB - Fault Mediator + + + + + +

Fault Mediator

+ +

The fault mediator transforms the current message into a fault message, but +does NOT send it. The <send> mediator needs to be invoked to send a fault +message created this way. The fault message "To" header is set to the +"Fault-To" of the original message if such a header exists on the original +message. If a 'version' attribute is specified, the created fault message will +be created as a selected SOAP 1.1, SOAP 1.2 or POX fault.

+ +

Syntax

+
 <makefault [version="soap11|soap12|pox"]>
+   <code (value="literal" | expression="xpath")/>
+   <reason (value="literal" | expression="xpath")>
+   <node>?
+   <role>?
+   <detail>?
+ </makefault>
+ +

+ +

UI Configuration

+ +

Fault Mediator +

+ +

Figure1: Fault Mediator

+ +

Version

+ +

You can select the version of the SOAP fault message that you want to +create. Options are SOAP 1.1 and SOAP 1.2.

+ +

Fault Code

+ +

You can specify a fault code

+
    +
  • versionMismatch: SOAP version mismatch error
  • +
  • mustUnderstand: A soap error regarding must understand error
  • +
  • Client: Client side error
  • +
  • Server: Server side error
  • +
+ +

Fault String

+ +

The detailed fault string of the fault code can specify here. It can be give +either as a string value or as an expression. NSEditor: You can click this link +to add namespaces if you are providing an expression. You will be provided +another panel named 'Namespace Editor' where you can provide any number of +namespace prefixes and url that you have used in the xpath expression. Here is +an example of the use of namespaces in an expression.

+ +

Fault Actor

+ +

SOAP 1.1 fault actor(if you select SOAP 1.1)

+ +

SOAP 11 fault mediator

+ +

Figure2: SOAP 1.1 with fault expression selected

+ +

Detail

+ +

Some information about the fault can be added here

+ +

If you select SOAP 1.2, you can see the followings

+ +

SOAP 12 fault meditor

+ +

Figure2: SOAP 1.2 with fault expression selected

+ +

Reason

+ +

Reason is the fault reason describing the fault code

+ +

Role

+ +

SOAP 1.2 role names

+ +

Node

+ +

SOAP 1.2 node name

+ +

Example

+
+<makefault xmlns="http://ws.apache.org/ns/synapse" version="soap11">
+   <code xmlns:soap11Env="http://schemas.xmlsoap.org/soap/envelope/" value="soap11Env:VersionMismatch" />
+   <reason value="test message " />
+   <role></role>
+</makefault>
+
+ + diff --git a/docs/xdoc/mediators/filter.xml b/docs/xdoc/mediators/filter.xml new file mode 100644 index 0000000000..10fe5f6c6e --- /dev/null +++ b/docs/xdoc/mediators/filter.xml @@ -0,0 +1,87 @@ + + + + + + WSO2 ESB - Filter Mediator + + + + + +

Filter Mediator

+ +

Filter mediator can be used for XPath filtering of messages. There are two +modes of operation.

+
    +
  1. If user only specifies the XPath it will be evaluated for true or + false.
  2. +
  3. If user specifies a regular expression as well, the string returned from + evaluating the xpath will be matched against the regular expression.
  4. +
+ +

In both modes if evaluation of expression returns true child mediators will +be executed.

+ +

Filter mediator closely resembles the If/else control structure.

+ +

Syntax

+
 <filter (source="xpath" regex="string") | xpath="xpath">
+   mediator+
+ </filter>
+ +

The <filter> mediator either test the given xpath expression as a +Boolean expression, or match the evaluation result of a source xpath expression +as a String against the given regular expression. If the test succeeds, the +filter mediator will execute the enclosed mediators in sequence.

+ +

One could also use this mediator to handle the failure case as well, in +which case the configuration would be as follows

+
 <filter (source="xpath" regex="string") | xpath="xpath">
+   <then [sequence="string"]>
+     mediator+
+   </then>
+   <else [sequence="string"]>
+     mediator+
+   </else>
+ </filter>
+ +

In this case the filter condition remains as earlier and the succeeded +messages will be mediated using the the set of mediators enclosed in the 'then' +element in sequence, while failed messages will be mediated using the set of +mediators enclosed in the else element in sequence

+ +

UI Configuration

+ +

+ +

Here are the configuration options related to Filter Mediator.

+
    +
  • Specify As: Specify whether you give the condition as an XPath or a + Regular expression.
  • +
  • XPath: XPath expression if you selected the "Specify As" option to + "XPath". Note that you can define the namespaces used in the xpath by + clicking the "Namespaces" link
  • +
  • Source: XPath expression to locate the value which is going match with + the reguilar expression that you can define below.
  • +
  • Regex: Regular expression to match with the source value.
  • +
+ +

Example

+
  <filter source="get-property('To')" regex=".*/StockQuote.*">
+      <then>
+          <send/>                    
+      </then>
+      <else>
+          <drop/>
+      </else>
+  </filter>     
+ +

In this example, filter will get the To header value and match it against +the given regular expression. If this evaluation returns true, it will send the +message. If the evaluation returns false it will drop the message.

+ + diff --git a/docs/xdoc/mediators/header.xml b/docs/xdoc/mediators/header.xml new file mode 100644 index 0000000000..6511ee593e --- /dev/null +++ b/docs/xdoc/mediators/header.xml @@ -0,0 +1,73 @@ + + + + + + WSO2 ESB - Header Mediator + + + + + +

Header Mediator

+ +

The header mediator sets or removes a specified header from the current soap +info-set. At the moment set header only supports simple valued headers.

+ +

Syntax

+
 <header name="qname" (value="literal" | expression="xpath") [action="set"]/>
+ <header name="qname" action="remove"/>
+ +

The optional action attribute specifies whether the mediator should set or +remove the header. If omitted, it defaults to a set-header.

+ +

UI Configuration

+ +

+ +

Figure1: Header Mediator

+ +

Here are the option you have in configuring the header mediator.

+
    +
  • Name: Name of the header element, You can declare the namespace used in + the header element by clicking the Namespace link right to the text field. +
  • +
  • Action: (Set/Remove), Specify whether you want to remove this header from + the incomming message or set a new header, Default to Set.
  • +
  • Value/Expression: A static value or an xpath expression that will be + executed on the message to set the header value.
  • +
+ +

Example

+
  <in>
+      <RMSequence single="true" version="1.0"/>
+      <send>
+         <endpoint name="reliable">
+            <address uri="http://localhost:9000/services/ReliableStockQuoteService">
+               <enableRM/>
+               <enableAddressing/>
+            </address>
+         </endpoint>
+      </send>
+  </in>
+  <out>
+      <header name="wsrm:SequenceAcknowledgement" action="remove"
+              xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm"/>
+      <header name="wsrm:Sequence" action="remove"
+              xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm"/>
+      <header name="wsrm:AckRequested" action="remove"
+              xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm"/>
+      <send/>
+  </out>
+ +

ESB receives a non reliable message and it forward it to an endpoint that +supports reliable messaging. In this example when ESB recieves a message we +send it using Reliable messaging. So the response ESB receives is having +Reliable messaging headers. We don't want to send these headers to the client +who doesn't support reliable messaging. So we remove the reliable messaging +headers before sending the reponse to the client.

+ + diff --git a/docs/xdoc/mediators/in-out.xml b/docs/xdoc/mediators/in-out.xml new file mode 100644 index 0000000000..d1c7960e0c --- /dev/null +++ b/docs/xdoc/mediators/in-out.xml @@ -0,0 +1,60 @@ + + + + + + WSO2 ESB - In/Out Mediators + + + + + +

In/Out Mediators

+ +

These mediators act as predefined filters. Messages which are in the in path +of the ESB will traverse through the child mediators of the in mediator. +Messages which are in the out path of ESB will traverse through the child +mediators of out mediator.

+ +

Syntax

+ +

In

+
  <in>
+      mediator+
+  </in>
+  
+ +

Out

+
  <out>
+      mediator+
+  </out>
+  
+ +

UI Configuration

+ +

None.

+ +

Usage Scenario

+
  <syn:sequence name="main" xmlns:syn="http://ws.apache.org/ns/synapse">
+      <syn:in>
+          <syn:log level="full"/>
+          <syn:filter source="get-property('To')" regex="http://localhost:9000.*">
+              <syn:send/>
+          </syn:filter>
+      </syn:in>
+      <syn:out>
+          <syn:send/>
+      </syn:out>
+  </syn:sequence>
+ +

Main sequence with in and out mediators. Messages coming to the ESB will be +sent using wsa:to address and responses will be sent back to the requester.

+ +

Remarks

+ +

These mediators are pointless to be used in proxy service sequences. Proxy +services has predefined sequences for in messages and out message.

+ + diff --git a/docs/xdoc/mediators/iterate.xml b/docs/xdoc/mediators/iterate.xml new file mode 100644 index 0000000000..c45d33f639 --- /dev/null +++ b/docs/xdoc/mediators/iterate.xml @@ -0,0 +1,98 @@ + + + + + + WSO2 ESB - Iterate Mediator + + + + + +

Iterate Mediator

+ +

The iterate mediator implements another EIP and will split the message into +number of different messages derived from the parent message by finding +matching elements for the XPath expression specified. New messages will be +created for each and every matching element and processed in parallel (default behavior) using +either the specified sequence or endpoint. +Created messages can also be set to process sequentially by setting the optional 'sequential' +attribute to 'true'. Parent message can be continued or +dropped in the same way as in the clone mediator. The 'preservePayload' +attribute specifies if the original message should be used as a template when +creating the splitted messages, and defaults to 'false', in which case the +splitted messages would contain the split elements as the SOAP body. +The optional 'id' attribute can be used to identify the iterator which created a particular +splitted message when nested iterate mediators are used. This is particularly useful when +aggregating responses of messages that are created using nested iterate mediators. +

+ +

Syntax

+
 <iterate [id="id"] [continueParent=(true | false)] [preservePayload=(true | false)] [sequential=(true | false)] (attachPath="xpath")? expression="xpath">
+   <target [to="uri"] [soapAction="qname"] [sequence="sequence_ref"] [endpoint="endpoint_ref"]>
+     <sequence>
+       (mediator)+
+     </sequence>?
+     <endpoint>
+       endpoint
+     </endpoint>?
+   </target>+
+ </iterate>
+ +

UI Configuration

+ +

+ +

Figure1: Iterate Mediator

+ +

Iterate Mediator can be configured with the following options.

+
    +
  • Iterate ID: (Optional) This can be used identify messages created by this iterate mediator, useful + when nested iterate mediators are used. +
  • +
  • Sequential Mediation: (True/False), Specify whether splitted messages should be processed sequentially + or in parallel. Default value is 'false' (parallel processing). +
  • +
  • Continue Parent: (True/False), Specify whether the original message + should be continued or dropped, this is default to 'false'.
  • +
  • Preserve Payload: (True/False), Specify whether the original message + should be used as a template when creating the splitted messages or not, + this is default to 'false'.
  • +
  • Iterate Expression: Xpath expression that matches the elements which you + want to split the message from. You can specify the namespaces that you + used in the xpath expression by clicking the namespace link in the right + hand side.
  • +
  • Attach Path: (Optional), You can specify an xpath expression for elements + that the splitted elements (as expressed in Iterate expression) are + attached to, to form new messages
  • +
+ +

For more information about target please refer Target.

+ +

Example

+
+<iterate expression="//m0:getQuote/m0:request" preservePayload="true"
+         attachPath="//m0:getQuote"
+         xmlns:m0="http://services.samples">
+    <target>
+        <sequence>
+            <send>
+                <endpoint>
+                    <address
+                        uri="http://localhost:9000/services/SimpleStockQuoteService"/>
+                </endpoint>
+            </send>
+        </sequence>
+    </target>
+</iterate>
+
+ +

In this scenario the Iterate mediator splits the messages in to parts and process them asynchronously.

+ + +

+ + diff --git a/docs/xdoc/mediators/log.xml b/docs/xdoc/mediators/log.xml new file mode 100644 index 0000000000..f00fb1d792 --- /dev/null +++ b/docs/xdoc/mediators/log.xml @@ -0,0 +1,137 @@ + + + + + + WSO2 ESB - Log Mediator + + + + + +

Log Mediator

+ +

With the log mediator, you can log messages being mediated.

+ +

Log Category

+

Log Mediator supports following log categories.Log messages will be logged in log4j with +selected log category. The default log category is INFO

+
    +
  • TRACE
  • +
  • DEBUG
  • +
  • INFO
  • +
  • WARN
  • +
  • ERROR
  • +
  • FATAL
  • +
+ + +

Log Levels

+

Log mediator has four log levels

+
    +
  1. simple = To, From, WSAction, SOAPAction, ReplyTo, MessageID and any + properties
  2. +
  3. headers = All SOAP header blocks and any properties
  4. +
  5. full = all attributes included in log level 'simple' and the SOAP + envelope and any properties
  6. +
  7. custom = Only properties specified to the Log mediator
  8. +
+ +

Log Separator

+ +

A separator if defined will be used to separate the attributes being logged. +The default separator is the ',' comma

+ +

Log Properties

+

With properties, user can choose any other attributes that they want to log. +Imagine there is an element carrying the transaction id in the SOAP body. User +can use a XPath expression to extract out this transaction id element and log +it using the log mediator. It is possible to define several such properties to +be logged.

+ +

If properties are specified with any of the first three log levels, custom +properties will be logged along with the default ones.

+ +

Syntax

+
 <log [level="string"] [separator="string"]>
+   <property name="string" (value="literal" | expression="xpath")/>*
+ </log>
+ +

UI Configuration

+ +

Log Mediator

+ +

Figure1: Log Mediator

+ +

Log Category

+

You can select the log category to be one of following values.

+
    +
  • TRACE
  • +
  • DEBUG
  • +
  • INFO
  • +
  • WARN
  • +
  • ERROR
  • +
  • FATAL
  • +
+ +

Log Level

+

You can select the log level to be one of following values.

+
    +
  • Simple: To, From, WSAction, SOAPAction, ReplyTo, MessageID and any + properties
  • +
  • Headers: All SOAP header blocks and any properties
  • +
  • Full: All attributes included in log level 'simple' and the SOAP envelope + and any properties
  • +
  • Custom: Only properties specified to the Log mediator
  • +
+ +

Log Separator

+ +

The log separator is used to separate the attributes being logged. The +default separator is ',' (comma).

+ +

Adding Properties

+ +

You can add custom messages to log as the messages mediate thorough the log +mediator.

+ +

Log Mediator Properties

+ +

Figure2: Log Mediator Properties

+
    +
  • Property Name: Name for the property
  • +
  • Property Value: The type of the property value, possible candidates are + Value/Expression +
      +
    • Value - A static text message
    • +
    • Expression - An xpath expression executed on each mediating message +
    • +
    +
  • +
  • Value: The text or an expression you want to log
  • +
  • NSEditor: You can click this link to add namespaces if you are providing + an expression. You will be provided another panel named 'Namespace Editor' + where you can provide any number of namespace prefixes and url that you + have used in the xpath expression. Here is an example of the use of + namespaces in an expression.
  • +
  • Action: Delete the property
  • +
+ +

Example

+
  <log level="custom" xmlns="http://ws.apache.org/ns/synapse">
+      <property name="text"
+                expression="fn:concat('Stock price - ',get-property('stock_price'))"/>
+  </log>
+ +

In this example log level is set to custom. It logs the property stock_price +that is set previously in the message mediation.

+
 
+  <log level="full" xmlns="http://ws.apache.org/ns/synapse"/>
+ +

In the previous example it logs evething including the full SOAP message.

+ + diff --git a/docs/xdoc/mediators/oauth.xml b/docs/xdoc/mediators/oauth.xml new file mode 100644 index 0000000000..1a4f1a8273 --- /dev/null +++ b/docs/xdoc/mediators/oauth.xml @@ -0,0 +1,45 @@ + + + + + + WSO2 ESB - OAuth Mediator + + + + + +

OAuth Mediator

+ +

The OAuth Mediator supports 2-legged OAuth. This by passes the RESTFull requests and authenticate users against WSO2 Identity Server. +

+ +

Syntax

+
+<oauthService remoteServiceUrl="" />
+
+ + +

UI Configuration

+ +

+ +

Figure 1: OAuth Mediator Options

+ +

You have the following configurations under the OAuth Mediator.

+
    +
  • OAuth Server: Server url of the WSO2 Identity Server[e.g.:https://localhost:9443/services]
  • + +
+

Example

+ +

+
+<oauthService xmlns="http://ws.apache.org/ns/synapse" remoteServiceUrl="https://localhost:9443/service" />
+
+

+ + diff --git a/docs/xdoc/mediators/pojo-command.xml b/docs/xdoc/mediators/pojo-command.xml new file mode 100644 index 0000000000..60e75f4bac --- /dev/null +++ b/docs/xdoc/mediators/pojo-command.xml @@ -0,0 +1,97 @@ + + + + + + WSO2 ESB - PojoCommand Mediator + + + + + +

PojoCommand Mediator

+ +

This mediator implements the popular command pattern.

+ +

The pojoCommand(or command) mediator creates an instance of the specified command class - which may implement the + org.apache.synapse.Command interface or should have a public void method "public void execute()". If any + properties are specified, the corresponding setter methods are invoked on the class before each message is + executed. It should be noted that a new instance of the POJO Command class is created to process each + message processed. After execution of the POJO Command mediator, depending on the 'action' attribute of + the property, the new value returned by a call to the corresponding getter method is stored back to the + message or to the context. The 'action' attribute may specify whether this behaviour is expected or not via + the Read, Update and ReadAndUpdate properties.

+ +

Syntax

+
 <pojoCommand name="class-name">
+   (
+   <property name="string" value="string"/> |
+   <property name="string" context-name="literal" [action=(ReadContext | UpdateContext | ReadAndUpdateContext)]>
+    (either literal or XML child)
+   </property> |
+   <property name="string" expression="xpath" [action=(ReadMessage | UpdateMessage | ReadAndUpdateMessage)]/>
+   ) *
+ </pojoCommand>
+ +

UI Configuration

+
+ +

+ Figure 1: Adding a PojoCommand mediator +

+
+

+ Clicking on the command mediator created as shown in figure 1 will open + up the command mediator specific options. You can specify the command mediator implementaion class and load it by + clicking LoadClass button. Once you load the pojo command class you'll see the command mediator configuration options + as in figure2.

+
+ +

+ Figure 2: Command mediator configuration options +

+
+

+ Command mediator configuration descriptions +

+
    +
  • + Class Name: The class name of the Pojo class. You have to give the fully qualified name of the class and click + "Load Class" button. +
  • +
  • + Properties of the POJOCommand mediator: After you click the "Load Class" and if it is a valid Pojo Class + you will see the properties in the POJO class in a table with following fields. +
      +
    • + Property Name - Name of the property. This will be automatically loaded from the class. +
    • +
    • + Read Info - The value to set for the property. You can choose the value from eaither of following sources +
        +
      • Value - A Static value
      • +
      • Message - Read a value from the incomming message. You can provide the xpath expression to + execute on the message in the 'Value' text field.
      • +
      • Context - Read a value from the Message context properties. You can provide the property key + in the 'Value' text field.
      • +
      +
    • +
    • + Update Info - Specify the action to do with reading the property value. You can choose following actions. +
        +
      • NONE - No activitly
      • +
      • Message - Update the message. You can provide the xpath expression of the element you want to + update in the "Value" text field.
      • +
      • Context - Update the properties (Message context). You can give the property key in the 'Value' text field.
      • +
      +
    • +
    +
  • +
+ + + + + diff --git a/docs/xdoc/mediators/property.xml b/docs/xdoc/mediators/property.xml new file mode 100644 index 0000000000..c05360762a --- /dev/null +++ b/docs/xdoc/mediators/property.xml @@ -0,0 +1,313 @@ + + + + + + WSO2 ESB - Property Mediator + + + + + +

Property Mediator

+ +

Properties are name value pairs. Properties are a way to convey information +across different processing units. For example user may need to set a transport +property from the message mediation. Or user may need to remove a property +which is set by the transport. This mediator sets or removes properties for a +particular message.

+ +

Property mediator has no direct impact on the message but rather on the +message context flowing through Synapse. The properties set on a message can be +later retrieved through the synapse:get-property(prop-name) XPath extension +function. If a scope is specified for a property, the property could be set as +a transport header property or an (underlying) Axis2 message context property, +or as a Axis2 client option. If a scope is not specified, it will default to +the Synapse message context scope. Using the property element with action +specified as "remove" you can remove any existing message context properties. +

+ +

There are some well-defined properties that you can get/set on the Synapse +message context scope:

+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameValuesMeaning
RESPONSEtrue'true' means the message is to be marked as a response message
OUT_ONLYtrue'true' means the message is to be marked as an out-only message that + does not expect a response
ERROR_CODEStringthis is set to any error message code encountered during a fault
ERROR_MESSAGEStringthis is set to any error message text encountered during a fault
ERROR_DETAILStringthis is set to any error message detail text encountered during a + fault
ERROR_EXCEPTIONStringthis is set to any Java Exception encountered during a fault
+ +

+ +

There are some Axis2 and module properties that are useful which are set at +scope="axis2"

+ + + + + + + + + + + + + + + + + + + + + + + +
NameValuesMeaning
MercurySequenceKeyintegercan be an identifier specifying an Mercury internal sequence key, + and
MercuryLastMessagetrue'true' will make this the last message and terminate the sequence
+ +

+ +

There are some Axis2 client side properties/options that are useful which +are set at scope="axis2-client"

+ + + + + + + + + + + + + + + + + + +
NameValuesMeaning
FORCE_HTTP_1.0trueforces outgoing http/s messages to use HTTP 1.0 (instead of the + default 1.1)
+ +

+ +

The synapse:get-property() XPath extension +function

+ +

The get-property() function allows any XPath expression used in a +configuration to look-up information from the current message context. It is +possible to retrieve properties previously set with the property mediator, +and/or information from the Synapse or Axis2 message contexts or transport +header. The function accepts the scope as an optional parameter as shown +below:

+ +

synapse:get-property( [(axis2 | axis2-client | transport),] +<property_name> [,<dateformat>] )

+ +

+ +

Some useful properties from the Synapse message context follows:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameMeaning
SYSTEM_DATE Returns the current date as a String. Optionally a date format as per + standard date format may be supplied. e.g. + synapse:get-property("SYSTEM_DATE", "yyyy.MM.dd G 'at' HH:mm:ss z") or + get-property('SYSTEM_DATE')
SYSTEM_TIME Returns the current time in milliseconds. (i.e. the difference, + measured in milliseconds, between the current time and midnight, + January 1, 1970 UTC)
To, From, Action, FaultTo, ReplyTo, MessageIDthe message To and Action and WS-Addressing propertie
MESSAGE_FORMATreturns the message format - i.e. returns pox, get, soap11 or + soap12
OperationNamereturns the operation name for the message
+ +

+ +

In addition to the above, one may use the get-property() function to +retrieve Axis2 message context properties or transport headers. e.g. +synapse:get-property('transport', 'USER_AGENT')

+ +

+ +

SynapseXpath variables

+ +

There are a set of predefined XPath variables when writing XPaths in the +Synapse Configuration. Those are as follows;

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameMeaning
bodyThe SOAP 1.1 or 1.2 body element For example; + expression="$body/getQuote" refers to the first getQuote element in the + SOAP body regardless of whether the message is SOAP-11 or SOAP-12
headerThe SOAP 1.1 or 1.2 header element For example; + expression="$header/wsa:To" refers to the addressing To header + regardless of whether this message is SOAP-11 or SOAP-12Further there + are some variable prefixes defined in Synapse XPaths which can be + usefull in writing the configurations;
ctxPrefix for Synapse MessageContext properties For example; + expression="$ctx:RESPONSE" gives the value of the Synapse message + context property with name 'RESPONSE'
axis2Prefix for Axis2 MessageContext properties For example; + expression="$axis2:messageType" gives the value of the axis2 message + context property with name 'messageType'
trpPrefix for the transport headers For example; + expression="$trp:Content-Type" gives the value of the 'Content-Type' + transport header, which is going to be the Content-Type of the current + message
+ +

+ +

Syntax

+
 <property name="string" [action=set|remove] (value="literal" | expression="xpath") [scope=transport|axis2|axis2-client]/>
+ +

+ +

UI Configuration

+ +

+ +

Property Mediator Screenshot

+ +

You have the following configuration under the property mediator.

+
    +
  • Name: A name for the property. You can return the value of the property + by calling get-property(property-name) xpath extension function.
  • +
  • Action: The action to do. Possible values are +
      +
    • Add: Add a new property
    • +
    • Remove: Remove the property with the given name
    • +
    +
  • +
  • Set Action As: Specify which type of value to store. Possible values are +
      +
    • Value : A static text value
    • +
    • Expression: XPath expression to evaluate +

      If there are any namespaces involved in the XPath expression, you + can specify it in the Namespace Editor.

      + +

      Namespace Editor Screenshot

      +
    • +
    +
  • +
  • Scope : Specify the scope the property is valid. Possible values are +
      +
    • Synapse
    • +
    • Transport
    • +
    • Axis2
    • +
    +
  • +
+ +

Example

+
  <property name="symbol"
+                    expression="fn:concat('Normal Stock - ', //m0:getQuote/m0:request/m0:symbol)"
+                    xmlns:m0="http://services.samples/xsd"/>
+
+  <log level="custom">
+      <property name="symbol" expression="get-property('symbol')"/>        
+  </log>    
+ +

In this example we are setting the property symbol and later we are logging +it using the log mediator.

+ +

+ + diff --git a/docs/xdoc/mediators/relaytransformer.xml b/docs/xdoc/mediators/relaytransformer.xml new file mode 100644 index 0000000000..e0fbc84d80 --- /dev/null +++ b/docs/xdoc/mediators/relaytransformer.xml @@ -0,0 +1,122 @@ + + + + + + WSO2 ESB - Relay Transformer Mediator + + + + + +

Relay Transformer Mediator

+ +

The relayTransformer mediator applies the specified XSLT transformation +to the selected element of the current message payload. The source +attribute specifies which element to be selected to apply +the given XSLT transfomation. In the case where the +source element is not specified, it uses the first child of the soap body as the +selected element. Optionally parameters could be passed into +the transformations through the 'property' elements. These +properties are corresponding to the XSL parameters and can be accessed during +transformation by <xsl:param name="{the name of the property}" +/>. The 'feature' element defines any features +which should be explicitly set to the TransformerFactory. The +feature +'http://ws.apache.org/ns/synapse/transform/feature/dom' turns +on DOM based transformations instead of serializing elements into Byte streams +and/or temporary files. Though this would be better in performance than using +byte streams, sometimes it may not work for all transformations.

+ +

Finally, the 'resource' element can be used to resolve +XSLT imports and includes from the repository. It works in +exactly the same way as the corresponding element in a <proxy> definition +(Proxy Service).

+ +

The Relay Transformer Mediator supports all the features provided by the XSLT +mediator. In addition to those features, it supports streaming transformation, +where the incoming stream is given directly to the underlying XSLT processor to +do the XSLT transformation. When using the Relay Transformer mediator in streaming +mode, the ESB should be started in Message Relay mode. This will give high +performance numbers.

+ +

Syntax

+
 <relayTransformer key="string" [input="xml|stream"]  [source="xpath"]>
+   <property name="string" (value="literal" | expression="xpath")/>*
+   <feature name="string" value="true| false" />*
+   <resource location="string" key="string"/>*
+ </relayTransformer>
+ +

UI Configuration

+ +

+ +

Figure 1. Relay Transformer Mediator

+ +

Relay Transformer Mediator

+
    +
  • Key : The registry key to refer the xslt. This supports static and dynamic keys. For + more information refer + Sample 16
  • +
  • Source: Specify in which part of message (specified in xpath) the xslt + should be applied. Default is the SOAP body of the message.
  • +
+ +

Properties of the Relay Transformer mediator

+ +

Manage the properties which would be referred from the xslt in +transformation (using get-property(prop-name) xpath extension function).

+ +

+ +

Figure 2. Add Properties

+ +

+
    +
  • Property Name: Name of the property.
  • +
  • Property Type: Whether it is a static value or an xpath expression.
  • +
  • Value/ Expression: The static value or the xpath expression.
  • +
  • NSEditor: Specify the namespaces that are used in the xpath expression. +
  • +
  • Action: Delete the property.
  • +
+ +

Features of the Relay Transformer mediator

+ +

Specify the features to be enabled in the XSLT transformation. Read the +introduction paragraph of this guide for an example feature.

+ +

+ +

Figure 3. Add Features

+ +

Relay Transformer Mediator - Add Features

+
    +
  • Feature Name: Name of the feature.
  • +
  • Feature Value: Specify whether the feature is turn on (True) or Not + (False).
  • +
  • Action: Delete the feature.
  • +
+ +

+ +

Example

+
+<relayTransformer xmlns="http://ws.apache.org/ns/synapse" key="transform/example.xslt" source="s11:Body/child" />
+
+ +

In this scenario the xslt can be picked by the key transform/example.xslt and the XSLT would be applied +to a part of the message that is specified as a XPath expression.In this case it is applied to s11:Body/child +the message

+ +

+ + +

+ + diff --git a/docs/xdoc/mediators/rewrite.xml b/docs/xdoc/mediators/rewrite.xml new file mode 100644 index 0000000000..d72ee87aae --- /dev/null +++ b/docs/xdoc/mediators/rewrite.xml @@ -0,0 +1,118 @@ + + + + + + WSO2 ESB - URL Rewrite Mediator + + + + + +

Rewrite Mediator

+ +

URL rewrite mediator is used to modify and transform the URL values available in the message

+ +

Properties

+

By default the mediator will take the 'To' header of the message and apply the provided rewrite rules on it. + Alternatively one can specify a property name in the 'inProperty' attribute, in which case the mediator will take the value of + the specified property as the input URL. Similarly the mediator by default sets the transformed URL as the 'To' header of the message. + Alternatively you can use the 'outProperty' attribute to instruct the mediator to set the resulting URL as a property.

+
    +
  • In Property
  • +
  • >Out Property
  • +
+ + +

Rules

+

The rewrite mediator applies URL transformations by evaluating a set of rules on the message. +Rules are specified using the 'rewriterule' element. Rules are evaluated in the order they are specified. +A rule can consist of an optional condition and one or more rewrite actions. If the condition is provided +it will be evaluated first. If it evaluates to 'true' all the specified rewrite actions will be executed. + Otherwise the set of actions will be skipped. If no condition is specified, the provided rewrite actions will be always executed. + The condition should be wrapped in a 'condition' element within the 'rule' element. + Rewrite actions are specified using 'action' elements.

+
    +
  1. Condition:- A rule can consist of an optional condition. If the condition is provided it will be evaluated first
  2. +
  3. Action:- It states which type of action should be executed on the URL. This defaults to 'set' value
  4. +
  5. Fragment:- This attribute can be used to specify the URL fragment on which the action should be executed. + If not specified this will be taken as 'full' URL, which is the complete URL
  6. +
  7. Value/Expression:- The value to 'set', 'append' or 'prepend' must be specified using either the 'value' attribute or the 'xpath' attribute. + One of these two attributes are always needed unless the value of the 'type' attribute is set to 'remove'
  8. +
  9. Regex:- When user set action to 'replace' an additional 'regex' + attribute must be specified which indicates the portion that should be replaced with the given value.
  10. +
+ + +

Syntax

+
+<rewrite [inProperty="string"] [outProperty="string"]>
+  <rewriterule>
+      <condition>
+         ...
+      </condition>?
+      <action [type="append|prepend|replace|remove|set"] [value="string"]
+          [xpath="xpath"] [fragment="protocol|host|port|path|query|ref|user|full"] [regex="regex"]>+
+   </rewriterule>+
+</rewrite>
+
+ +

UI Configuration

+ +

Rewrite Mediator

+ +

Figure1: Rewrite Mediator

+ +

Properties

+
    +
  • In Property :
  • + +

    + By default 'rewrite' mediator will take the 'To' header of the message and will apply the provided rewrite rules on it. + If user specify a 'inProperty' attribute, the mediator will take the value of the specified property as the input URL. +

    + +
  • Out Property :
  • +

    + Similarly the mediator by default sets the transformed URL as the 'To' header of the message. + Alternatively user can use the 'outProperty' attribute to instruct the mediator to set the resulting URL as a property. +

    + +
+ +

Rules

+

The rewrite mediator applies URL transformations by evaluating a set of rules on the message

+Rewriterule Mediator +

Figure2: Rules

+
    +
  • Condition:- A rule can consist of an optional condition. If the condition is provided it will be evaluated first
  • +
  • Action:- It states which type of action should be executed on the URL. This defaults to 'set' value
  • +
  • Fragment:- This attribute can be used to specify the URL fragment on which the action should be executed
  • +
  • Value/Expression:- The value to 'set', 'append' or 'prepend' must be specified using either the 'value' attribute or the 'xpath' attribute. + One of these two attributes are always needed unless the value of the 'type' attribute is set to 'remove'
  • +
  • Regex:- When user set action to 'replace' an additional 'regex' + attribute must be specified which indicates the portion that should be replaced with the given value.
  • +
+ + + +

Example

+
 <rewrite>
+	<rewriterule>
+		<action type="replace" regex="soap" value="services" fragment="path" />
+	</rewriterule>
+</rewrite>
+ +

+For instance; if our request is as follows, +

+

"ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy1"

+

the address URL of the request contains the context 'soap'. +In ESB server all the services are deployed under a context named 'services' by default. So,'To' header will be re written by replacing the 'soap' context with 'services'. + Hence the requests will be delivered to the server successfully. +

+ + + diff --git a/docs/xdoc/mediators/rmsequence.xml b/docs/xdoc/mediators/rmsequence.xml new file mode 100644 index 0000000000..4907af37d8 --- /dev/null +++ b/docs/xdoc/mediators/rmsequence.xml @@ -0,0 +1,84 @@ + + + + + + WSO2 ESB - RMSequence Mediator + + + + + +

RMSequence

+ +

The <RMSequence> mediator can be used to create a sequence of messages +to communicate via WS-Reliable Messaging with an WS-RM enabled endpoint +(<enableRM>). The simple use case of this mediator is to specify a +single="true" property, because this means that only one message is involved in +the same sequence. However if multiple messages should be sent in the same +sequence, the correlation property should be used with a XPath expression that +selects an unique element value from the incoming message. With the result of +the XPath expression, Synapse can group messages together that belong to the +same sequence. To close the sequence neatly, for the last message of the +sequence also an XPath expression should be specified. With the version +attribute the WS-RM specification version to be used can be specified, 1.0 or +1.1.

+ +

Syntax

+
 <RMSequence (correlation="xpath" [last-message="xpath"]) | single="true" [version="1.0|1.1"]/>
+ +

UI Configuration

+ +

+
    +
  • WS-RM Spec Version: Reliable Messaging Specification version: possible + values 1.0 /1.1
  • +
  • Message Sequence: Whether to use a single message or a multiple + correlated messages +
      +
    • Single Message - Making single message reliable.
    • +
    • Correlated Sequence - Make multiple correlated message reliable. When + you select this option you have to provide the following two fields + appears in the panel. +
        +
      • Sequence XPath: The xpath expression that selects an unique + element value from the incoming message
      • +
      • Last Message XPath: The xpath expression that identify the last + message
      • +
      + NOTE: You can define prefixes for the namespaces used in these + expression from the right hand side link named "Namespaces".
    • +
    +
  • +
+
+ +
+

Specifying Correlated Sequences

+ +

Example

+
+<in>
+    <RMSequence single="true" version="1.0"/>
+    <send>
+       <endpoint name="reliable">
+          <address uri="http://localhost:9000/services/ReliableStockQuoteService">
+             <enableRM/>
+             <enableAddressing/>
+          </address>
+       </endpoint>
+    </send>
+</in>
+
+ +

In the above scenario, WS-RM is engaged to the endpoint using the <enableRM/> + tag. It is possible to engage WS-RM to both Address and WSDL endpoints using this tag. In addition + to the RM enabled endpoint, RMSequence mediator is specified before the send mediator. This mediator is + used to specify the set of messages to be sent using a single RM sequence. In this sample it is specified as + single message per sequence. It also specifies the version of the WS-RM to be used.

+ +

+ diff --git a/docs/xdoc/mediators/router.xml b/docs/xdoc/mediators/router.xml new file mode 100644 index 0000000000..840d3bb169 --- /dev/null +++ b/docs/xdoc/mediators/router.xml @@ -0,0 +1,101 @@ + + + + + + WSO2 ESB - Router Mediator + + + + + +

Router Mediator

+ +

Router is specifically designed for what it name suggests. Routing +messages.

+ +

Router mediator can contain any number of routes. Router mediator can be +configured to continue or to stop the mediation after the routing by setting +the 'continueAfter' attribute value to be 'true' and 'false' respectively. Each +and every route must contain an 'expression' attribute which is to specify the +XPath over which the roting condition is evaluated. Apart from that there can +be an optional 'match' attribute as well. If both expression and the match +attributes are specified in a particular route, the evaluated string value of +the XPath over the current message will be compared with the regular expression +provided as the value of the match attribute to see whether this route is +matching for the current message. Where as if only the expression is specified, +presence of the element specified by this XPath is considered as the routing +condition.

+ +

One can configure a route to break routing or continue evaluating further +routes to see any further matching by setting the 'breakRoute' attribute to +'true' or 'false' respectively. For all the routes there has to be a 'target' +element which contains the information about the routing path as a sequence or +an endpoint both can be inline as well as referred. If both an endpoint and a +sequence is specified message will be first mediated through the sequence and +sent to the endpoint after mediation. Particular target cannot contain an +inline sequence and a referred sequence at the same time. The same applies to +endpoint of the target as well.

+ +

Syntax

+
<router [continueAfter=(true | false)]>
+  <route expression="xpath" [match="regEx"] [breakRouter=(true | false)]>
+    <target [sequence="string"] [endpoint="string"]>
+      <sequence ....../>?
+      <endpoint ....../>?
+    </target>
+  </route>+
+</router>
+ +

UI Configuration

+ +

Router

+ +

+ +

Figure 1: Router Mediator

+ +

The router mediator has the following configuration options.

+
    +
  • Continue after routing: (Yes/No), Whether to continue the routing if any + of the child routes are executed. The default value is No.
  • +
  • Number of clones: Show you the number of child routes that router + mediator has. You can add child routes by clicking the 'Add Route' link in + the right hand side of the text field.
  • +
+ +

Route

+ +

+ +

Route Mediator

+ +

Here are the options available in the Route mediator configurations.

+
    +
  • Break After Route: (Yes/No) Specify whether to continue with the sibling + routes or stop from the current route, if the routing condition is + successful.
  • +
  • Route Expression: An xpath expression to execute on the message
  • +
  • Route Pattern: A regular expression to compare with the value retrieved + from the above xpath expression.
  • +
+ +

Example

+
+<router>
+    <route xmlns="http://ws.apache.org/ns/synapse" xmlns:ns1="http://org.apache.synapse/xsd" xmlns:ns="http://org.apache.synapse/xsd" expression="header/sourcefile/@name" match="esb*">
+    <target>
+      <endpoint name="endpoint_urn_uuid_867AD5A624748DD63619739416601328-2078896617">
+         <default />
+      </endpoint>
+   </target>
+    </route>
+</router>    
+
+

+ + diff --git a/docs/xdoc/mediators/rule.xml b/docs/xdoc/mediators/rule.xml new file mode 100644 index 0000000000..9e0aa2f67e --- /dev/null +++ b/docs/xdoc/mediators/rule.xml @@ -0,0 +1,225 @@ + + + + + + WSO2 ESB - Rule Mediator + + + + + +

Rule Mediator

+ +

Rule mediator is to integrate the WSO2 Rules component to the WSO2 ESB in +order to define dynamic integration decisions in terms of rules.

+ +

Syntax

+
  <rule>
+
+    <ruleset>
+        <source [ key="xs:string" ]>
+            [ in-Lined ]
+        </source>
+        <creation>
+            <property name="xs:string" value="xs:string"/>*
+        </creation>
+    </ruleset>
+
+    <session type="[stateless|stateful]"/>*
+
+    <facts>
+        <fact name="xs:string" type="xs:string" expression="xs:string" value="xs:string"/>+
+    </facts>
+
+    <results>
+        <result name="xs:string" type="xs:string" expression="xs:string" value="xs:string"/>*
+    </results>
+
+    [ <childMediators>
+        <mediator/>*
+      </childMediators> ]
+
+  </rule>
+        
+ +

RuleSet

+ +

The source is the only mandatory element of the ruleset. However, the +properties required for the creation of the ruleset can also be specified +within ruleset. The key attribute is a registry key, which is to lookup the +rule script from the registry if the rule script is in the registry. The rule +set can be given as a child node of source elemenent. If the rule set is +non-XML, you may need to wrap it with a CDATA section inside a XML tag ex: +<X><![CDATA[ native code]]></X>

+ +

Note : The key or in-lined rule script must be defined. Otherwise, the rule +mediator configuration is invalid.

+ +

RuleSession

+ +

Rule Session specify the stateful or stateless behavior of the rule engine. +If this has value 'stateful', then the rule engine will execute rules in a +stateful manner, for any other value, it assumes as stateless. There are +optional properties, which are used when creating the rule session. Rule +session is optional and the default one is stateful.

+ +

Facts / Results

+
    +
  • name - the unique name
  • +
  • value - Represents any static value
  • +
  • expression - XPath expression for extracting data from the message being + passed between ESB components. The default value is the first child of the + SOAP Body.
  • +
  • type - Defines the type of the input data. There are a few built in types + such as Message, Context, Map, POJO and Mediator and there are samples + using these. Using the rule-component.conf, you can register new types + along with adapters, which are responsible for formulating specified types + from the data. If there is no registered adapter for a given type, then, we + assume the given type as a valid java class name and uses POJO adapter to + formulate the POJO instance whose class is the given type.
  • +
+ +

Facts specify the facts being used in rule set. It also defines how to +formulate facts from the message, etc. Results define how to handle results +from the rule set execution. Usually, results adapters enrich the message with +results. For example, If you are using POJO adapter (i.e. a java class as the +type; the class name of a result), then we transform POJO into an XML and +attached to the SOAP message.

+ +

UI Configuration

+ +

Rule +

+ +

Figure1: Rule Mediator

+ +

Each of configuration elements is described in following section

+ +

RuleSource

+ +

Rule script can be given as a registry key or an in-lined script. To give +rule script as in-lined, you can use editor.

+ +

The format (language) of the rule script . If it is a XML, then this +attribute should be 'xml'. Any other value, rule mediator assumes that the rule +script is in native format. If the rule script is in native format, it should +be given by wrapping as a CDATA section inside a XML tag ex: +<X><![CDATA[ native code]]></X>.

+ +

Note: The key or in-lined rule script must be defined. Otherwise, rule +mediator is invalid.

+ +

RuleSession

+ +

Session Type - Indicates the stateful or stateless behavior of the rule +engine. If this has value ' stateful ' , then rule engine will executes rules +in a state full manner , for any other value , it assumes as stateless.

+ +

property - Those are used when creating rule session.

+ +

RuleSet

+ +

It is possible to exists properties for rules set creation, registration, +deregistration and there are add property options for each.

+ +

Example Usage: When using Drool native language (.drl) for rule script, it +is needed to provide .dsl file .This can be done using attribute named 'source' +and value 'drl'.

+ +

<ruleSet>

+ +

<creation>

+ +

<property name="source" value="drl"/>

+ +

</creation>

+ +

</ruleSet>

+ +

Facts / Results

+ +

Input defines what are the facts that should injected to Rule Engine in +order to fire rules whereas Output describes what should do with return value +form rule engine.

+ +

Adding Facts / Results

+ +

Figure 2 shows a one senario of addting input

+ +

Rule Mediator Inputs width="1319" +height="122">

+ +

Figure 2 Inputs of the Rule Mediator

+ +

Type : According to current implementation valid types are +as bellow.

+ +

Name : Value Type Static Value or XPath expression

+ +

Value / Expression : value - Represents any static +value. expression- XPath expression is used to extract data from +either external XML source or SOAP envelope. There is no default value.

+ +

Registry Key : The registry or Message context key .This is +used for getting data from either registry or message context

+ +

Registry Browser : If the key is registry resource, the +browser to select the resource.

+ +

NS Editor : You can click this link to add namespaces if +you are providing an expression. You will be provided another panel named +'Namespace Editor' where you can provide any number of namespace prefixes and +url

+ +

Action : Delete the input out put

+ +

Adding Properties

+ +

Adding properties option is in RuleServiceProvider , RuleSet and +RuleSession. Figure 3 shows UI on adding property.

+ +

Property Adding

+ +

Figure3: Rule Mediator Properties

+ +

Name: Name for the property

+ +

Value: The type of the property value.

+ +

Action: Delete the property

+ +

Example

+
    +
  1.  <rule>
    +        <ruleset>
    +        <source key="rule/sample.xml"/>
    +        </ruleset>
    +        <facts>
    +            <fact name="symbol" type="java.lang.String"
    +                  expression="//m0:getQuote/m0:request/m0:symbol/child::text()"
    +                  xmlns:m0="http://services.samples"/>
    +        </facts>
    +        <childMediators>
    +            <send>
    +                <endpoint>
    +                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                </endpoint>
    +                </send>
    +                <drop/>
    +        </childMediators>
    +
    +    </rule>
    +
    + In the above configuration, Rule script is picked from the registry with + key rule/sample.xml. There is a one fact + and it is a string variable. Its value is calculated from the current SOAP + message using an expression. Rule engine uses these facts to decide what + rules should fire.
  2. +
+ + diff --git a/docs/xdoc/mediators/script.xml b/docs/xdoc/mediators/script.xml new file mode 100644 index 0000000000..53a10c5d77 --- /dev/null +++ b/docs/xdoc/mediators/script.xml @@ -0,0 +1,152 @@ + + + + + + WSO2 ESB - Script Mediator + + + + + +

Script Mediator

+ +

Synapse supports Mediators implemented in a variety of scripting languages +such as JavaScript, Python or Ruby. There are two ways of defining script +mediators, either with the script program statements stored in a separate file +which is referenced via the local or remote registry entry, or with the script +program statements embedded in-line within the Synapse configuration. Synapse +uses the Apache Bean Scripting +Framework for the scripting language support, any script language +supported by BSF may be used to implement a Synapse Mediator. With the script +mediator, you can invoke a function in the corresponding script. With in these +functions, it is possible to access the Synapse predefined in a script variable +named 'mc’. This ‘mc’ represents an +implementation of the MessageContext, named +ScriptMessageContext.java. That contains following additional +methods that can be accessed within the script by +mc.methodName.

+
    +
  • public Object getPayloadXML() - getting the XML representation of + SOAP Body payload
  • +
  • public void setPayloadXML(Object payload) - Set the SOAP body payload + from XML
  • +
  • public void addHeader(boolean mustUnderstand, Object content) - Add a + new SOAP header to the message.
  • +
  • public Object getEnvelopeXML() - Get the XML representation of the + complete SOAP envelope
  • +
  • public void setTo(String reference)
  • +
  • public void setFaultTo(String reference)
  • +
  • public void setFrom(String reference)
  • +
  • public void setReplyTo(String reference)
  • +
+ +

Implementing a Mediator with a script language can have advantages over +using the built in Synapse Mediator types or implementing a custom Java class +Mediator. Script Mediators have all the flexibility of a class Mediator with +access to the Synapse MessageContext and SynapseEnvironment APIs, and the ease +of use and dynamic nature of scripting languages allows rapid development and +prototyping of custom mediators. An additional benefit of some scripting +languages is that they have very simple and elegant XML manipulation +capabilities, for example JavaScript E4X or Ruby REXML, so this makes them well +suited for use in the Synapse mediation environment. For both types of script +mediator definition the MessageContext passed into the script has additional +methods over the standard Synapse MessageContext to enable working with the XML +in a way natural to the scripting language. For example when using JavaScript +getPayloadXML and setPayloadXML, E4X XML objects, and when using Ruby, REXML +documents.

+ +

+ +

Syntax

+
    +
  • Script mediator using a script off the registry +

    +
    <script key="string" language="string" [function="script-function-name"]/>
    +    
    +

    The attribute key is the registry key to load the + script. The language attribute specifies the scripting + language of the script code (e.g. "js" for Javascript, "rb" for ruby, + "groovy" for Groovy, "py" for Python..). The function is + an optional attribute defining the name of the script function to invoke, + if not specified it defaults to a function named + 'mediate'. The function is passed a single parameter - + which is the Synapse MessageContext. The function may + return a boolean, if it does not, then true is assumed, and the script + mediator returns this value.

    +
  • +
  • Script mediator using a In-lined script +

    +
    <script language="string">...script source code...<script/>
    +
  • +
+ +

UI Configuration

+ +

Script Type

+
    +
  • Inline: Specify the script inline
  • +
  • Registry: Store the script in registry and refer it using the key
  • +
+ +

If Inline Selected

+ +

Script Mediator with Inlinded Source

+ +

Language

+ +

Choose from variety of scripting languages supported

+ +

Source

+ +

If inline selected as the Script type, specify the source

+ +

If Registry Selected

+ +

Script Mediator with Registry Source

+ +

Function

+ +

Function of the script language to execute

+ +

Key

+ +

Registry location of the source

+ +

Include Keys

+ +

Scripts sources to be included

+ +

Example

+
    +
  1. <script language="js">mc.getPayloadXML()..symbol != "IBM";<script/>
    +

    The above configuration is an example of an inline mediator using + JavaScript/E4X which returns false if the SOAP message body contains an + element named 'symbol' which has a value of 'IBM' would be:

    +
  2. +
  3. <script language="js"
    +    key="repository/samples/resources/script/test.js"
    +    function="testFunction"/>
    +    
    +

    In the above example, script is loaded from the registry by using the + key repository/conf/sample/resources/script/test.js. The + script is written in java script. The function to be invoked is + testFunction . As example for test.js shown in the bellow. +

    +
    function testFunction(mc) {
    +     var symbol = mc.getPayloadXML()..*::Code.toString();
    +     mc.setPayloadXML(
    +        <m:getQuote xmlns:m="http://services.samples">
    +           <m:request>
    +              <m:symbol>{symbol}</m:symbol>
    +           </m:request>
    +        </m:getQuote>);
    +}
    +
  4. +
+ + diff --git a/docs/xdoc/mediators/send.xml b/docs/xdoc/mediators/send.xml new file mode 100644 index 0000000000..1e9308b2a3 --- /dev/null +++ b/docs/xdoc/mediators/send.xml @@ -0,0 +1,117 @@ + + + + + + WSO2 ESB - Send Mediator + + + + + +

Send Mediator

+ +

Send is considered as one of the most widely used mediators in ESB. It is +built in to the core of the ESB. It performs a fundamental task of any ESB. +This fundamental task is to send a message out from ESB.

+ +

There are two modes of operation in a send mediator.

+
    +
  1. Sending the message using message level information
  2. +
  3. Sending the message to a predefined endpoint
  4. +
+ +

If we don't provide an Endpoint it will try to send the message using the +wsa:to address of the message. Also if we use a send mediator in the out path +of the ESB, without specifying an Endpoint it will send the message as a +reply.

+ +

If we provide an Endpoint, it will send the message according to the +information in the Endpoint. Have a look at the endpoint guide for more +details.

+ +

Send mediator is the only way to send a message out from the ESB. If you +want to forward the message to an Endpoint or to send the reply back this +mediator must be used.

+ +

The send mediator copies any message context properties from the current +message context to the reply message received on the execution of the send +operation so that the response could be correlated back to the request. +Messages may be correlated by WS-A Message-ID, or even simple custom text +labels (see the property mediator and samples).

+ +

Note: A send operation may be blocking or non-blocking depending on the +actual transport implementation used. As the default NIO based http/s +implementation does not block on a send, care must be taken if the same message +must be sent and then further processed (e.g. transformed). In such a scenario, +it maybe required to first clone the message into two copies and then perform +processing to avoid conflicts.

+ +

Syntax

+
 <send/>
+ +

If the message is to be sent to one or more endpoints, then the following is +used:

+
 <send>
+   (endpointref | endpoint)+
+ </send>
+ +

where the endpointref token refers to the following:

+
 <endpoint key="name"/>
+ +

and the endpoint token refers to an anonymous endpoint definition.

+ +

If the response message is to be sent to a sequence, then the following is used:

+ +
 <send receive="recevingSequence">
+   (endpointref | endpoint)+
+ </send>
+ +

UI Configuration

+ +

+ +

Figure 1: Send Mediator Options

+ +

You can select the endpoint to be one of the following value.

+
    +
  • None
  • +
  • Anonymous
  • +
  • Pick from Registry
  • +
  • Import
  • +
  • Receiving Sequence, this can be a static sequence or can be calculated using a XPath
  • +
+Note: You can manage endpoints from the "Manage Endoint" panel which can be +accessed from the Manage-> Mediation-> Endpoints menu from the left hand +side bar. + +

Example

+ +

Send mediator used in in-path and out path

+
<definitions xmlns="http://ws.apache.org/ns/synapse">    
+    <in>
+        <send>
+            <endpoint>
+                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
+            </endpoint>
+        </send>
+        <drop/>
+    </in>
+    <out>
+        <send/>
+    </out>
+</definitions> 
+ +

In this configuration first send is used inside a in mediator. As I have +mentioned earlier, both request and response will go through the main sequence. +But only request messages will go through the child mediators of in and only +response messages will go through the out mediator. So the request will be +forward to the endpoint with the given address. Response will go through the +second send and this send mediator will send it back to the requester.

+ +

+ + diff --git a/docs/xdoc/mediators/sequence.xml b/docs/xdoc/mediators/sequence.xml new file mode 100644 index 0000000000..fa4ec59a2c --- /dev/null +++ b/docs/xdoc/mediators/sequence.xml @@ -0,0 +1,44 @@ + + + + + + WSO2 ESB - Validate Mediator + + + + +

Sequence Mediator

+ +

+ A sequence mediator refers to a predefined sequence element which is used to
+ invoke a named sequence of mediators. +

+ +

Syntax

+ +
 <sequence key="name"/>
+ +

UI Configuration

+ +

+ +

+ +

+ Figure 1: Sequence Mediator +

+ +

+ In the Sequence Mediator panel, there are two options available to select a sequence. +

+
    +
  • Static way :- In staic manner, User can provide a registry key which refers a predefined sequence
  • +
  • Dynamic way :- Where user can define a 'XPath' expression to point the exact sequence name, which
    + is present in the message. So, ESB will look into the system for that particular sequence and will do further processing.
  • +
+ + + \ No newline at end of file diff --git a/docs/xdoc/mediators/smooks.xml b/docs/xdoc/mediators/smooks.xml new file mode 100644 index 0000000000..90283b7c0e --- /dev/null +++ b/docs/xdoc/mediators/smooks.xml @@ -0,0 +1,90 @@ + + + + + + WSO2 ESB - Smooks Mediator + + + + + +

Smooks Mediator

+ +

Smooks mediator can be used to apply lightweight transformations on messages in an efficient manner. + Smooks is a powerful framework for processing, manipulating and transforming XML. More information + about Smooks can be obtained from the official Smooks website. +

+ +

Configurations

+

The Smooks mediator requires the transformation definition to be passed in as an external resource. + This transformation can be specified as a local entry or be stored in the registry. The mediator UI + enables you to point the mediator to an existing local entry or a registry resource. +

+ +
    +
  • Smooks transformation configuartion : Smooks mediator requires the transformation definition to be passed in as an external resource. +
  • + +
  • Input : User can define an 'input' as a 'Text' or 'XML' and need to provide a 'xpath' expression to pick exact + message block, else by default whole 'message body' will be selected by default.
  • +
  • Output : Same like in input, user can define how his output should be
  • + +
+ + +

Syntax

+ +
+		<smooks [config-key="string"]>
+			<input [type="|text|xml"]  [regex="regex"]/>
+			<output [type="|text|xml"]  [regex="regex"] [property="string"] [action="string"]/>
+		</smooks>
+	
+ +

UI Configuration

+ +

Smooks Mediator

+ +

Smooks Mediator Configuartion

+ +

Configurations

+
    +
  • Configuration Key:
  • + +

    + Smooks transformation definition to can be specified as a local entry or be stored in the registry. +

    + +
  • Input :
  • +

    + User can define an 'input' as a 'Text' or 'XML' and need to provide a 'xpath' expression to pick exact + message block, else by default whole 'message body' will be selected by default. +

    +
  • Output :
  • +

    + Same like in input, user can define how his output should be. When user defines an 'output' expression there are
    + additional operations can be performed. +

    + +
      +
    • + Add : Selected node will be added as a child to the message. +
    • +
    • + Replace : Selected node will be replaced in the message. +
    • +
    • + Sibling : Selected node will be added as a sibling. +
    • +
    + +

    + When user defines an 'output' as a 'Property', property will be saved in the messagecontext for the future uses. +

    +
+ + + diff --git a/docs/xdoc/mediators/spring.xml b/docs/xdoc/mediators/spring.xml new file mode 100644 index 0000000000..9c45462219 --- /dev/null +++ b/docs/xdoc/mediators/spring.xml @@ -0,0 +1,73 @@ + + + + + + WSO2 ESB - Spring Mediator + + + + + +

Spring Mediator

+ +

The Spring mediator exposes a spring bean as a mediator. The spring mediator +creates an instance of a mediator, which is managed by Spring. This Spring bean +must implement the Mediator interface for it to act as a Mediator.

+ +

Syntax

+
 <spring:spring bean="exampleBean" key="string"/> 
+ +

+ +

The key will reference the Spring +ApplicationContext/Configuration (i.e. spring configuration XML) used for the +bean. This key can be a registry key or local entry key. The +bean attribute is used for looking up a Spring bean from the +spring Application Context. Therefore, a bean with same name must be in the +given spring configuration. In additions, that bean must implement the Mediator +interface.

+ +

+ +

UI Configuration

+ +

+ +

Figure1: Spring Mediator

+
    +
  • Bean: The name of the bean
  • +
  • Key: The registry reference to the spring + Application-Context/Configuration used for the bean. You can select it by + clicking the "Registry Keys".
    +
  • +
+ +

Example

+ +

+
    +
  1. <spring:spring bean="springtest" key="conf/sample/resources/spring/springsample.xml"/>
    +    
    +

    In the above configuration, spring XML is in the registry and it can be + looked up using the registry key + conf/sample/resources/spring/springsample.xml . This + spring XML (i.e springsample.xml) must contain a bean with the name + springtest. The following figure shows an example can be + used as the registry resource - springsample.xml.

    +

    +
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
    +<beans>   
    +     <bean id="springtest" class="org.apache.synapse.mediators.spring.SpringTestBean" singleton="false">   
    +           <property name="testProperty" value="100"/>       
    +     </bean>
    +</beans>
    +
  2. +
+ +

+ + diff --git a/docs/xdoc/mediators/store.xml b/docs/xdoc/mediators/store.xml new file mode 100644 index 0000000000..7def6bb027 --- /dev/null +++ b/docs/xdoc/mediators/store.xml @@ -0,0 +1,50 @@ + + + + + + Message Store Mediator - User Guide + + + + +

Message Store Mediator

+ +

+ With the Message Store mediator, you can Store messages in a given Message Store. +

+ + Message Store Mediator + +

+ Figure1: Message Store Mediator +

+ +

Message Store

+

+ Name of the message store that Messages will be stored. +

+ +

On Store Sequence

+ +

+ The Sequence that will be called before message get stored. +

+ + diff --git a/docs/xdoc/mediators/switch.xml b/docs/xdoc/mediators/switch.xml new file mode 100644 index 0000000000..52ee4ce2f1 --- /dev/null +++ b/docs/xdoc/mediators/switch.xml @@ -0,0 +1,99 @@ + + + + + + WSO2 ESB - Switch Mediator + + + + + +

Switch Mediator

+ +

Switch mediator is another XPath filter. The XPath will be evaluated and +will return a string. This string is matched against the regular expression in +each of cases in the specified order. If a matchig case is found it will be +executed. Further proccessing of the case statements won't happen after a +matching is found. If none of the case statements are matching and default case +is specified, it will be executed.

+ +

Syntax

+
 <switch source="xpath">
+   <case regex="string">
+     mediator+
+   </case>+
+   <default>
+     mediator+
+   </default>?
+ </switch>
+ +

The <switch> mediator will evaluate the given source XPath expression +into its string value, and match it against the given regular expressions. If +the specified cases does not match and a default case exists, it will be +executed.

+ +

UI Configuration

+ +

Switch

+ +

+ +

Here are the options to configure the Switch Mediator.

+
    +
  • Source XPath: Here you can specify the source xpath to be evaluated.
  • +
  • Number of cases: The number of cases specified. You can add cases by + clicking the "Add Case" link.
  • +
  • Specify default case: The link to add the default case. (This case is to + execute when all the other cases are failed.)
  • +
+ +

Case

+ +

+ +

Switch Case Mediator

+ +

Here are the options to configure the Switch Case Mediator.

+
    +
  • Case Value (Regular Expression): A regular expression to match with + switching value.
  • +
+ +

Default

+ +

The Switch Default Mediator will be a child mediator for the Switch +Mediator. It is to define a defalut case for the current routing switch. If all +the cases were not matched with the switch value, the sequence defined as +children to the default mediator will be taken as the route of the message.

+ +

+ +

Example

+
  <switch source="//m0:getQuote/m0:request/m0:symbol" xmlns:m0="http://services.samples/xsd">
+      <case regex="IBM">
+          <!-- the property mediator sets a local property on the *current* message -->
+          <property name="symbol" value="Great stock - IBM"/>
+      </case>
+      <case regex="MSFT">
+          <property name="symbol" value="Are you sure? - MSFT"/>
+      </case>
+      <default>
+          <!-- it is possible to assign the result of an XPath expression as well -->
+          <property name="symbol"
+                expression="fn:concat('Normal Stock - ', //m0:getQuote/m0:request/m0:symbol)"
+                xmlns:m0="http://services.samples/xsd"/>
+      </default>
+  </switch>
+    
+ +

In this scenario it will get the text of symbol element and match it against +values MSFT and IBM.

+ +

+ + diff --git a/docs/xdoc/mediators/target.xml b/docs/xdoc/mediators/target.xml new file mode 100644 index 0000000000..8cc16a6371 --- /dev/null +++ b/docs/xdoc/mediators/target.xml @@ -0,0 +1,53 @@ + + + + + + WSO2 ESB - Target + + + + + +

Target

+ +

Target is a common configuration used across many ESB conofugrations. Some +mediators that uses this configuration are Clone, Iterate and Router.

+ +

A target specifies a mediation sequence, and endpoint or both. If a sequnce +is specified it will be executed. If a endpoint is specified message will be +sent to the endpoint. If both sequence and endpoint are specified, first +sequence will be executed and then endpoint will be executed.

+ +

Syntax

+
  <target [sequence="string"] [endpoint="string"]>
+    <sequence ....../>?
+    <endpoint ....../>?
+  </target>  
+ +

UI Configuration

+ +

+ +

Here you can prepare a message to send to an endpoint or mediate through +some more sequences.

+
    +
  • SOAP Action: The SOAP action of the message.
  • +
  • To Address: Then target endpoint address.
  • +
  • Sequence: Mediate the message through a sequence. You can either pick a + named sequence from the registry or define an anonymous sequence by adding + mediators to the current Target mediator as children.
  • +
  • Endpoint: Send the message to an endpoint. Here you can pick a named + endpoint from the registry (which you can add in the Endpoint panel that + can be accessed from the Manage-> Mediation-> Endpoints menu in the + left hand side menu bar.) or keep the endpoint as anonymous.
  • +
+ +

Example

+ +

Please go to the specific mediators for examples.

+ + diff --git a/docs/xdoc/mediators/throttle.xml b/docs/xdoc/mediators/throttle.xml new file mode 100644 index 0000000000..d4035675d3 --- /dev/null +++ b/docs/xdoc/mediators/throttle.xml @@ -0,0 +1,106 @@ + + + + + + WSO2 ESB - Throttle Mediator + + + + +

Throttle Mediator

+

+ The Throttle mediator can be used for rate limiting as well as concurrency + based limiting. A WS-Policy dictates the throttling configuration and may be + specified inline or loaded from the registry. Please refer to the samples + document for sample throttling policies. The Throttle mediator could be added + in the request path for rate limiting and concurrent access limitation. When + using for concurrent access limitation, the same throttle mediator 'id' must be + triggered on the response flow so that completed responses are deducted from + the available limit. (i.e. two instances of the throttle mediator with the same + 'id' attribute in the request and response flows). The 'onReject' and + 'onAccept' sequence references or inline sequences define how accepted and + rejected messages are to be handled. +

+

Syntax

+
+  <throttle [onReject="string"] [onAccept="string"] id="string">
+    (<policy key="string"/> | <policy>..</policy>)
+    <onReject>..</onReject>?
+    <onAccept>..</onAccept>?
+  </throttle>
+

UI Configuration

+

+ +

+
    +
  • + Throttle Group ID: The id for the throttle group. Note you would have two throttle mediator configuration in + request and response paths with the same group id. +
  • +
  • + Referring Policy: The policy for the throttling. You can specify it inline or refer from the regsitry +
  • +
  • + On Acceptance Referring Sequence: The sequence to act on accpetance +
  • +
  • + On Rejection Referring Sequence: The sequence to act on rejection +
  • +
+ +

Example

+
+
+ <in>
+    <throttle id="A">
+        <policy>
+            <!-- define throttle policy -->
+            <wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
+                        xmlns:throttle="http://www.wso2.org/products/wso2commons/throttle">
+                <throttle:ThrottleAssertion>
+                    <throttle:MaximumConcurrentAccess>10</throttle:MaximumConcurrentAccess>
+                </throttle:ThrottleAssertion>
+            </wsp:Policy>
+        </policy>
+        <onAccept>
+            <log level="custom">
+                <property name="text" value="**Access Accept**"/>
+            </log>
+            <send>
+                <endpoint>
+                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
+                </endpoint>
+            </send>
+        </onAccept>
+        <onReject>
+            <log level="custom">
+                <property name="text" value="**Access Denied**"/>
+            </log>
+            <makefault>
+                <code value="tns:Receiver"
+                      xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
+                <reason value="**Access Denied**"/>
+            </makefault>
+            <property name="RESPONSE" value="true"/>
+            <header name="To" action="remove"/>
+            <send/>
+            <drop/>
+        </onReject>
+    </throttle>
+</in>
+     
+

+ Above example specifies a throttle mediator inside the in mediator. Therefore, all request messages + directed to the main sequence will be subjected to throttling. Throttle mediator has 'policy', 'onAccept' and + 'onReject' tags at top level. The 'policy' tag specifies the throttling policy for throttling messages. This + sample policy only contains a component called "MaximumConcurrentAccess" .This indicates the maximum number of + concurrent requests that can pass through Synapse on a single unit of time. +

+ +

+ + + diff --git a/docs/xdoc/mediators/transaction.xml b/docs/xdoc/mediators/transaction.xml new file mode 100644 index 0000000000..558624aae7 --- /dev/null +++ b/docs/xdoc/mediators/transaction.xml @@ -0,0 +1,42 @@ + + + + + + WSO2 ESB - Transaction Mediator + + + + + +

Transaction Mediator

+

+ Transaction mediator can provide transaction facility for a set of mediators + defined as its child mediators. A transaction mediator with the action "new" + indicates the entry point for the transaction. A transaction is marked + completed by a transaction mediator with the action "commit". The suspend and + resume actions are used to pause a transaction at some point and start it again + later. Additionally, the transaction mediator supports three other actions, + i.e. use-existing-or-new, fault-if-no-tx, rollback. +

+

Syntax

+
 <syn:transaction action="commit|fault-if-no-tx|new|resume|suspend|rollback|use-existing-or-new" />
+

UI Configuration

+

+ Transaction Mediator +

+

Action

+
    +
  • Commit transaction: End the transaction
  • +
  • Fault if no transaction: Go to error handler if no transaction
  • +
  • Initiate new transaction: Entry point for new transaction
  • +
  • Resume transaction: Resume a puased transaction
  • +
  • Suspend transaction: Puase a transaction
  • +
  • Rollback transaction: Rollback a transaction
  • +
  • Use existing or initiate transaction: If a transaction already exists continue it or create a new transaction
  • +
+

+ + diff --git a/docs/xdoc/mediators/validate.xml b/docs/xdoc/mediators/validate.xml new file mode 100644 index 0000000000..9375ce173a --- /dev/null +++ b/docs/xdoc/mediators/validate.xml @@ -0,0 +1,103 @@ + + + + + + WSO2 ESB - Validate Mediator + + + + + +

Validate Mediator

+ +

This mediator is used for schema validation of messages.

+ +

The portion of the message that needs to be validated is chooses by +evaluating the XPath expression. Then this message is validated against the +schema spcecified. User can specify a sequence to be executed in case of a +validation failure. This mediator provide an extension point by providing +properties to configure the underline validation engine.

+ +

Syntax

+
 <validate [source="xpath"]>
+   <property name="validation-feature-id" value="true|false"/>*
+   <schema key="string"/>+
+   <resource location="string" key="string"/> +
+   <on-fail>
+     mediator+
+   </on-fail>
+ </validate>
+ +

+ +

The validate mediator validates the result of the evaluation of the source +xpath expression, against the schema specified. If the source attribute is not +specified, the validation is performed against the first child of the SOAP body +of the current message. If the validation fails, the on-fail sequence of +mediators is executed. Properties could be used to turn on/off some of the +underlying features of the validator (See +http://xerces.apache.org/xerces2-j/features.html)

+

+ The <resource> can be used to specify external schema resources, which can be used to + validate the messages. External schema resources can be defined as localentries and with <resource> + user could point the specified localentries. +

+

UI Configuration

+ +

Validate Mediator

+ +

Key

+ +

Schema location

+ +

Source

+ +

XPath expression to extract the XML that need to be validated. If not +specified validation is performed against the first child of the SOAP body

+ +

Features

+ +

Here is the only mandatory feature supported by the validator, "http://javax.xml.XMLConstants/feature/secure-processing". + For more information please refer this. +

+

Example

+
    +
  1. <validate>
    +    <schema key="schema\sample.xsd"/>
    +         <on-fail>
    +                <makefault>
    +                    <code value="tns:Receiver"
    +                            xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +                    <reason value="Invalid Request!!!"/>
    +                </makefault>
    +                <property name="RESPONSE" value="true"/>
    +                <header name="To" expression="get-property('ReplyTo')"/>
    +         </on-fail>
    +</validate>
    +    
    + In the above validate mediator configuration, the required schema for + validating message going through the validate mediator has been given as a + registry key, schema\sample.xsd. In this sample + configuration, there is no source attribute. Therefore, in + this case, validate mediator takes source as the first child of SOAP Body. + Within on-fail, it is possible to specify mediation logic + that should to be happened if the validation is failed. In the above + configuration, it creates a SOAP fault using makefault + mediator and send back that to requested party.
  2. +
+

Note: If user configure WSO2 ESB with WSO2 Governance Registry and if he uploads all the required files as *.gar file (described in WSO2 GREG documentation), + uer can provide only the base schema when he provides schemas. +There is no need to provide all required imported schemas since ESB is able to resolve the imported resources using only the base schema. +Please note that for the above function user needs to uncomment the following lines @ synapse.properties file which is avilable in ESB_HOME/lib/core/WEB_INF/classes folder. +

+

+synapse.schema.resolver=org.wso2.carbon.mediation.initializer.RegistryXmlSchemaURIResolver + +

+ + + diff --git a/docs/xdoc/mediators/xquery.xml b/docs/xdoc/mediators/xquery.xml new file mode 100644 index 0000000000..ed1c85de02 --- /dev/null +++ b/docs/xdoc/mediators/xquery.xml @@ -0,0 +1,123 @@ + + + + + + WSO2 ESB - XQuery Mediator + + + + + +

XQuery Mediator

+ +

The XQuery mediator can be used to perform an XQuery transformation. The +'key' attribute specifies the registry key for looking up +XQuery script that going to be used for define transformation. The optional +'target' attribute specifies the node of the SOAP message that +should be transformed. In case where the target value is not specified, then +the first child of the SOAP body is selected. The 'variable' +elements define a variable that could be bound to the dynamic context of the +XQuery engine in order to access those +variables during the XQuery script invocation .

+ +

In the variable definition , it is possible to specify just a +literal value, or an XPath expression over +the payload, or even specify a registry key or a registry key +combined with an XPath expression that selects the value of the variable.Using +key attribute of the variable, it is possible to bind an XML +document located in the registry so that in the transformation that too can be +used.The name of the variable corresponds to the name of variable declaration +in the XQuery script. The type of the variable must be a valid +type defined by the JSR-000225 (XQJ API).

+ +

Supported Types

+
    +
  • XQItemType.XQBASETYPE_INT -> INT
  • +
  • XQItemType.XQBASETYPE_INTEGER -> INTEGER
  • +
  • XQItemType.XQBASETYPE_BOOLEAN -> BOOLEAN
  • +
  • XQItemType.XQBASETYPE_BYTE - > BYTE
  • +
  • XQItemType.XQBASETYPE_DOUBLE -> DOUBLE
  • +
  • XQItemType.XQBASETYPE_SHORT -> SHORT
  • +
  • XQItemType.XQBASETYPE_LONG -> LONG
  • +
  • XQItemType.XQBASETYPE_FLOAT -> FLOAT
  • +
  • XQItemType.XQBASETYPE_STRING -> STRING
  • +
  • XQItemType.XQITEMKIND_DOCUMENT -> DOCUMENT
  • +
  • XQItemType.XQITEMKIND_DOCUMENT_ELEMENT -> DOCUMENT_ELEMENT
  • +
  • XQItemType.XQITEMKIND_ELEMENT -> ELEMENT
  • +
+ +

Syntax

+
<xquery key="string" [target="xpath"]>
+    <variable name="string" type="string" [key="string"] [expression="xpath"] [value="string"]/>?
+</xquery> 
+ +

UI Configuration

+ +

+ +

Figure1: XQuery Mediator

+
    +
  • Key: The key that represent the xquery transformation.
  • +
  • Target: (optional) Specify the node of the message that should be + transformed using an xpath expression. ( default to the first child of the + SOAP body ) The namespace prefixes used in the expression can be defined by + clicking the namespaces link in front of the 'Target' input field.
  • +
+ +

Variables for the XQuery Mediator: Defines values/expressions that could be +bound to the dynamic context of the XQuery engine in order to access those +variables through the XQuery script.

+ +

+ +

Figure2: XQuery Mediator - Adding Variables

+You have the following option in a variable. +
    +
  • Variable Type: The 'type' of the variable must be a valid type defined by + the JSR-000225 (XQJ API). +

    The supported types are defined in the Supported Types + section

    +
  • +
  • Variable Name: The name of the variable should correspond to the name of + variable declaration in the XQuery script.
  • +
  • Value Type: Whether the value of the variable is a static value or an + expession.
  • +
  • Value/Expression: Static value or the expression.
  • +
  • Registry Key: Key, if the value is retrieved from the registry.
  • +
  • NSEditor: Defines the namespaces for the prefixes used in the xpath + query.
  • +
  • Action: Delete the variable.
  • +
+ +

Examples

+
    +
  1. <xquery key="xquery\example.xq">
    +      <variable name="payload" type="ELEMENT"/>
    +</xquery>
    +

    In the above configuration, XQuery script is in the registry and that + script can be picked by key xquery\example.xq. There is a + one variable name payload and type as + ELEMENT. As there is no expression in the variable + definitions, default value - the first child of SOAP Body is used as the + value of variable payload. . Within XQuery script, you can + access this variable by defining declare variable $payload as + document-node() external; . Refer sample 390 and 391 for more + information.

    +
  2. +
  3. <variable name="commission" type="ELEMENT" key="misc/commission.xml"></variable>
    +

    A variable definitions that pick a XML resource from the registry using + key misc/commission.xml and bind in to XQuery Runtime so that it can be + accessed with in XQuery script. Refer sample 391 for more information.

    +
  4. +
  5. <variable name="price" type="DOUBLE" expression="self::node()//m0:return/m0:last/child::text()" xmlns:m0="http://services.samples/xsd"/>
    +

    A variable whose value is calculated from current message SOAP Payload + using an expression. Here , value is a type of double.

    +
  6. +
+ + diff --git a/docs/xdoc/mediators/xslt.xml b/docs/xdoc/mediators/xslt.xml new file mode 100644 index 0000000000..b443261b99 --- /dev/null +++ b/docs/xdoc/mediators/xslt.xml @@ -0,0 +1,115 @@ + + + + + + WSO2 ESB - XSLT Mediator + + + + + +

XSLT Mediator

+ +

The xslt mediator applies the specified XSLT transformation +to the selected element of the current message payload. The source +attribute specifies which element to be selected to apply +the given XSLT transfomation. In the case where the +source element is not specified, it uses the first child of the soap body as the +selected element. Optionally parameters could be passed into +the transformations through the 'property' elements. These +properties are corresponding to the XSL parameters and can be accessed during +transformation by <xsl:param name="{the name of the property}" +/>. The 'feature' element defines any features +which should be explicitly set to the TransformerFactory. The +feature +'http://ws.apache.org/ns/synapse/transform/feature/dom' turns +on DOM based transformations instead of serializing elements into Byte streams +and/or temporary files. Though this would be better in performance than using +byte streams, sometimes it may not work for all transformations.

+ +

Finally, the 'resource' element can be used to resolve +XSLT imports and includes from the repository. It works in +exactly the same way as the corresponding element in a <proxy> definition +(Proxy Service).

+ +

Syntax

+
 <xslt key="string" [source="xpath"]>
+   <property name="string" (value="literal" | expression="xpath")/>*
+   <feature name="string" value="true| false" />*
+   <resource location="string" key="string"/>*
+ </xslt>
+ +

UI Configuration

+ +

+ +

Figure 1. XSLT Mediator

+ +

XSLT Mediator

+
    +
  • Key : The registry key to refer the xslt. This supports static and dynamic keys. For + more information refer + Sample 16
  • +
  • Source: Specify in which part of message (specified in xpath) the xslt + should be applied. Default is the SOAP body of the message.
  • +
+ +

Properties of the XSLT mediator

+ +

Manage the properties which would be referred from the xslt in +transformation (using get-property(prop-name) xpath extension function).

+ +

+ +

Figure 2. Add Properties

+ +

+
    +
  • Property Name: Name of the property.
  • +
  • Property Type: Whether it is a static value or an xpath expression.
  • +
  • Value/ Expression: The static value or the xpath expression.
  • +
  • NSEditor: Specify the namespaces that are used in the xpath expression. +
  • +
  • Action: Delete the property.
  • +
+ +

Features of the XSLT mediator

+ +

Specify the features to be enabled in the XSLT transformation. Read the +introduction paragraph of this guide for an example feature.

+ +

+ +

Figure 3. Add Features

+ +

XSLT Mediator - Add Features

+
    +
  • Feature Name: Name of the feature.
  • +
  • Feature Value: Specify whether the feature is turn on (True) or Not + (False).
  • +
  • Action: Delete the feature.
  • +
+ +

+ +

Example

+
 
+<xslt xmlns="http://ws.apache.org/ns/synapse" key="transform/example.xslt" source="s11:Body/child" />
+
+ +

In this scenario the xslt can be picked by the key transform/example.xslt and the XSLT would be applied +to a part of the message that is specified as a XPath expression.In this case it is applied to s11:Body/child +the message

+ +

+ + +

+ + diff --git a/docs/xdoc/message_processor.xml b/docs/xdoc/message_processor.xml new file mode 100644 index 0000000000..51dc773277 --- /dev/null +++ b/docs/xdoc/message_processor.xml @@ -0,0 +1,226 @@ + + + + + + + + + WSO2 ESB - Message Processors + + + + + + [ Documentation Index ] +

WSO2 ESB Message Processors

+

Contents

+ +

Introduction

+

+ Message processors can be used to implement different messaging and integration patters along with message stores.

+

+ Message processors can consume the messages in message stores and perform some processing on them. +

+

For example think of a scenario where we have a back-end service that can only accept messages at a given rate and incoming traffic to the ESB has + a different message rate. So to serve that inbound traffic using the available back-end services we can have a message store that + temporarily stores the messages and a message processor that will consume those messages and send to the back end service at a predefined rate.

+

+ Users can write their own message processor implementations and plug them using the Synapse configuration. WSO2 ESB ships two message processors implementations + that can be used out of the box. +

+
    +
  1. + Message Forwarding processor +
  2. +
  3. + Message Sampling Processor +
  4. +
+

Message Processor Configuration

+
+            <messageProcessor name="string" class="classname" messageStore="classname" >
+                <parameter name="string" > "string" </parameter>*
+            </messageProcessor>
+        
+

+ Message processor is a top level ESB configuration element where it should be given a unique name. +

+

+ The 'class' attribute value is the fully qualified class name of the underlying message processor implementation.

+

+ There can be many message processor implementations. Users can write their own message processor implementations and use them too.

+

+ Parameters section is used to configure the parameters that is needed by underlying message processor implementation

+ +

Message Forwarding Processor

+

Message Forwarding Processor consumes messages in a given message store and sends them to an predefined address endpoint.

+

If a message is successfully delivered to the endpoint, the processor will delete the message from the message store.

+

In case of a failure it will re-try after a configured interval.

+

Message processor can be activated or deactivated from the UI.

+

When its in the deactivated state users can manually delete/resend messages from the management console.

+

Message forwarding processor is useful when it comes to implementing reliable delivery channels, dead letter channels and store-and-forward channels.

+ +
+ + + + +

Figure 1: Messages ProcessorOperations

+
+ +

Message Forwarding Processor Parameters

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Parameter NameValueRequired
intervalMessage retry interval in milli secondsNo default is value is 1000ms
max.deliver.attemptsMaximum re delivery attempts before deactivating the processorNO
axis2.repoAxis2 Client repository to be use to send messagesNO
axis2.configAxis2 Configuration to be use to send messagesNO
message.processor.reply.sequenceName of the Sequence that reply of the message should be sent toNO
message.processor.fault.sequenceName of the sequence that fault message should be sent to in case of a SOAP + fault + NO
quartz.confQuartz configuration file pathNO
cronExpressionCron Expression to be used to configure the re try patternNO
+ +

Message Context properties to be used with Message Forwarding Processor

+ + + + + + + + + + + + + + + + + + + + + +
Property NameValueRequired
target.endpointName of the Address Endpoint which message should be delivered toYES.
OUT_ONLYtrue if this is a out only messageRequired for out only scenarios
+ +

Message Sampling Processor

+

Message Sampling Processor consumes messages in message store and send it to a configured sequence.

+

This process happens in a pre-configured interval. Therefore this message processor implementation is useful in implementing delivery channels with fixed delivery rate.

+ +

Message Sampling Processor Parameters

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Parameter NameValueRequired
sequenceSequenceID, which defines mediation flowYES
intervalMessage retry interval in milli secondsDefault value is 1000ms
quartz.confQuartz configuration file pathNO
cronExpressionCron Expression to be used to configure the re try patternNO
+ +

Note: When using the "SamplingProcessor" as a Message processor implementation, we must provide the "sequence" parameter (which contains 'endpoint' URI).

+ + diff --git a/docs/xdoc/message_relay.xml b/docs/xdoc/message_relay.xml new file mode 100644 index 0000000000..6214a48832 --- /dev/null +++ b/docs/xdoc/message_relay.xml @@ -0,0 +1,260 @@ + + + + + + + + + WSO2 ESB - Message Relay + + + + + + [ Documentation Index ] +

WSO2 Enterprise Service Bus (ESB) Message Relay

+

Contents

+ +

Introduction

+

+ Message Relay is a Message Pass through mechanism for ESB. Message relay enables ESB to pass the messages + without building or processing the message. +

+

+ When message relay is configured incoming requests to the ESB are not built and processed unless + specifically requested to do so. A incoming message is wrapped inside a default SOAP envelope as + binary content and sent through the ESB. +

+

+ Some of the ESB scenarios doesn't require the full message to be built. Instead ESB can work on other + message properties like request URLs or transport headers. +

+

+ With message relay ESB can achieve a very high throughput. +

+
+

+ Message Relay Building blocks +

+

+ Message relay has two main parts. +

+
    +
  • Axis2 Message Builder
  • +
  • Axis2 Message Formatter
  • +
+

A message builder is used to build an incoming message to the ESB. A message formatter is used to build the + out going stream from the message inside ESB.

+

+ So in a typical ESB routing scenario here is the flow +

+

+ Client <---- Outgoing Message ----> Message Formatter <---- ESB <---- Message Builder <---- Incoming Message <---- Service Provider +

+

+ Client <---- Outgoing Message ----> Message Formatter <---- ESB <---- Message Builder <---- Incoming Message <---- Service Provider +

+

+ When Relay Message builder and formatter are specified for a content type, message + coming with that content type will not be built by the ESB. Instead they will pass + through the ESB as it is. +

+

+ Message builders and formatters are specified in the axis2.xml under messageBuilders + and messageFormatters configuration section. Message builders and formatters are + chosen based on the content type of the message. +

+

+ ESB has few default Message message builders. Even if the user doesn't specify them + in the axis2.xml they will take effect. These can be overridden using the message + builder configurations in the axis2.xml. +

+

+ ESB doesn't have default Message formatters. So it is important to specify all of + them in the axis2.xml configuration. +

+

+ Here are the default message builders. +

+ + + + + + + + + + + + + + + + + + + + + + + + + +
application/soap+xmlorg.apache.axis2.builder.SOAPBuilder
multipart/relatedorg.apache.axis2.builder.MIMEBuilder
text/xmlorg.apache.axis2.builder.SOAPBuilder
application/xop+xmlorg.apache.axis2.builder.MTOMBuilder
application/xmlorg.apache.axis2.builder.ApplicationXMLBuilder
application/x-www-form-urlencodedorg.apache.axis2.builder.XFormURLEncodedBuilder
+

+ Configuring the message relay +

+

In the axis2.xml file there are two configuration sections called messageBuilders and + messageFormatters. User can replace the expected content types with the relay message + builder and formattter to pass these messages through the ESB without building them. +

+

Message relay builder and formatter class names.

+
+        builder : org.wso2.carbon.relay.BinaryRelayBuilder
+        formatter : org.wso2.carbon.relay.ExpandingMessageFormatter
+        
+

Sample configuration for message relay

+
+	<messageBuilders>
+        <messageBuilder contentType="application/xml"
+                        class="org.wso2.carbon.relay.BinaryRelayBuilder"/>
+        <messageBuilder contentType="application/x-www-form-urlencoded"
+                        class="org.wso2.carbon.relay.BinaryRelayBuilder"/>
+        <messageBuilder contentType="multipart/form-data"
+                        class="org.wso2.carbon.relay.BinaryRelayBuilder"/>
+        <messageBuilder contentType="text/plain"
+                         class="org.wso2.carbon.relay.BinaryRelayBuilder"/>
+        <messageBuilder contentType="text/xml"
+                         class="org.wso2.carbon.relay.BinaryRelayBuilder"/>
+    </messageBuilders>        
+        
+
+    <messageFormatters>
+        <messageFormatter contentType="application/x-www-form-urlencoded"
+                          class="org.wso2.carbon.relay.ExpandingMessageFormatter"/>
+        <messageFormatter contentType="multipart/form-data"
+                          class="org.wso2.carbon.relay.ExpandingMessageFormatter"/>
+        <messageFormatter contentType="application/xml"
+                          class="org.wso2.carbon.relay.ExpandingMessageFormatter"/>
+        <messageFormatter contentType="text/xml"
+                         class="org.wso2.carbon.relay.ExpandingMessageFormatter"/>
+        <!--<messageFormatter contentType="text/plain"
+                         class="org.apache.axis2.format.PlainTextBuilder"/>-->
+        <messageFormatter contentType="application/soap+xml"
+                         class="org.wso2.carbon.relay.ExpandingMessageFormatter"/>
+    </messageFormatters>
+        
+
+

Builder mediator

+

Builder mediator can be used to build the actual SOAP message from a message coming in + to ESB through the message relay. One usage is to use this before trying to log the + actual message in case of a error. Also with the builder mediator ESB can be configured + to build some of the messages while passing the others along.

+

Syntax of builder mediator

+
+    <syn:builder xmlns:syn="http://ws.apache.org/ns/synapse">
+        <syn:messageBuilder contentType="" class="" [formatterClass=""]/>
+    </syn:builder>
+        
+

+ By default builder mediator uses the axis2 default message builders for the content types + specified in Table 1. User can override those by using the optional messageBuilder configuration.

+

+ Like in axis2.xml user has to specify the content type and the implementation class of + the message builder. Also user can specify the message formatter for this content type. This is used by the + ExpandingMessageFormatter to format the message before sending to the destination. +

+

Message Relay Module

+

Now message relay has a axis2 module as well. This is an optional feature. This module can be used + to build the actual SOAP message from the messages that went through the Message relay.

+

+ To enable this module user has to enable the relay module globally in the axis2.xml

+
<module ref="relay"/>
+

Also user has to put the following phase in to the InFlow of axis2.

+
<phase name="BuildingPhase"/>
+

This module is designed to be used by Admin Services that runs inside the ESB. + All the admin services are running with content type: application/soap+xml. So if + a user wants to use admin console and use the ESB for receiving message with content + type application/soap+xml, this module should be used. +

+ User can configure the module by going to the modules section in admin console and then + going to the relay module. The module configuration is specified as a module policy. + After changing the policy user has to restart the ESB for changes to take effect.

+

Message Relay Module Policy

+
+<wsp:Policy wsu:Id="MessageRelayPolicy" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
+                xmlns:wsmr="http://www.wso2.org/ns/2010/01/carbon/message-relay"
+                xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
+        <wsmr:RelayAssertion>
+            <wsp:Policy>
+                <wsp:All>
+                    <wsmr:includeHiddenServices>false | false</wsmr:includeHiddenServices>
+                    <wsmr:services>
+                        <wsmr:service>Name of the service</wsmr:service>*
+                    </wsmr:services>
+                    <wsmr:builders>
+                        <wsmr:messageBuilder contentType="content type of the message" class="message builder implementation class" class="message formatter implementation class"/>
+                    </wsmr:builders>
+                </wsp:All>
+            </wsp:Policy>
+        </wsmr:RelayAssertion>
+</wsp:Policy>
+        
+

+ These are the assestions:

+

+ includeHiddenServices: If this is true message going to the services with hiddenService parameter will be built

+

wsmr:services: Messages going to these services will be built

+

wsmr:service: Name of the service

+ +

wsmr:builders: Message builders to be used for building the message

+

wsmr:builder: A message builder to be used for a content type

+ +

Message Relay Limitations

+

+ If the message relay is enabled for particular content type, there cannot be Services with + security enabled for that content type. This applies to services with reliable messaging as well. +

+ + diff --git a/docs/xdoc/message_store.xml b/docs/xdoc/message_store.xml new file mode 100644 index 0000000000..3825adfc24 --- /dev/null +++ b/docs/xdoc/message_store.xml @@ -0,0 +1,186 @@ + + + + + + + + + WSO2 ESB - Message Stores + + + + + + [ Documentation Index ] +

WSO2 ESB Message Stores

+

Contents

+ +

Introduction

+

+ An ESB can be used to implement different kind of messaging and integration patterns. To support these patters sometimes we need a storage to store messages.

+

+ Message Store is the storage for ESB messages. +

+

For Example In a scenario where we have a back end service that can only accept messages at a given rate and incoming traffic to ESB will have + different message rates. + So to serve that traffic utilizing the backend services there should be a temporary storage for messages. + + Message Store can be used as this temporary storage.

+

+ Incoming message traffic can be stored using the store mediator. + And Message processors associated with message store can be used to deliver messages to the backend services at a give rate.

+ + +

Users can implement their own message store by implementing the MessageStore interface and plug them using the configuration.ESB ships two message store implementations.

+
    +
  1. + In-Memory Message Store +
  2. +
  3. + JMS Message Store +
  4. +
+

Message Store Configuration

+
+            <messageStore name="string" class="classname" >
+                <parameter name="string" > "string" </parameter>*
+            </messageStore>
+        
+

+ Message Store is a top level ESB configuration element where it should have a unique name. +

+

+ class attribute value is the fully qualified class name of the underlying message store implementation.

+

+ There can be many message store implementations.Users can write their own message store implementation and use it.

+

+ Parameters section is used to configure the parameters that is needed by underlying message store implementation

+ +

Message Store Operations

+
    +
  1. When you click on Message Store section of Manage/Service Bus.It will direct you to + a page + where Listed + Messages appears. You can view and delete messages from that page. +
  2. + + +
    + + + + +

    Figure 1: Messages List

    +
    + +
    + + + + +

    Figure 2: View Message

    +
    +
+

In Memory Message Store

+

This is the default Message Store that will be created if user does not specify any implementation from the configuration. + Messages will be stored in an In-memory queue.So in case of a ESB restart all the messages stored will be lost.

+

In Memory message store is lot more faster than any persistence message store implementations.

+

So it can be used as a temporary storage of messages for use cases such as implementation of + high speed store and forwarded patterns where message persistence is not a requirement.

+ +

JMS Message Store

+

JMS Message Store can be configured using configuration by giving class value as org.wso2.carbon.message.store.persistence.jms.JMSMessageStore + and messages will be stored in a configured JMS queue in the underlying JMS Broker

+

Since this will persistent messages in a JMS queue in a ordered way, JMS message store can be used to implement store and forward patters that have QoS parameters like in order delivery and reliability

+

Configuration to connect to a broker is provided as parameter values

+

JMS Message Store parameters

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Parameter NameValueRequired
java.naming.factory.initialInitial Context Factory to use to connect to the JMS brokerYES
java.naming.provider.urlUrl of the naming provider to be used by the context factoryYES
store.jms.destinationJNDI Name of the Queue Name that message store is connectingNO but for some JMS clients this will be needed
store.jms.connection.factoryJNDI name of the Connection factory which is used to create jms connectionsNO but for some JMS clients this will be needed
store.jms.usernameUser Name that is used to create the connection with the brokerNO
store.jms.passwordPassword that is used to create the connection with the brokerNO
store.jms.JMSSpecVersion1.1 or 1.0 JMS API specification to be used (Default 1.1)NO
store.jms.cache.connectiontrue/false Enable Connection cachingNO
+ + diff --git a/docs/xdoc/monitoring.xml b/docs/xdoc/monitoring.xml new file mode 100644 index 0000000000..44df001c4d --- /dev/null +++ b/docs/xdoc/monitoring.xml @@ -0,0 +1,532 @@ + + + + + + + + + + Monitoring WSO2 ESB + + + + + + [ + Documentation Index + ] +

+ Monitoring WSO2 Enterprise Service Bus (ESB) +

+

+ This guide describes how to monitor WSO2 ESB using Mediation Statistics component and + Java Management Extensions (JMX). WSO2 ESB provides convenient, yet powerful mechanisms for + monitoring an ESB deployment. Results provided by ESB Monitoring can be used to tune up + message flows, detect mediation faults and track usage patterns. +

+

Contents

+ +

+

+ Introduction +

+

+ WSO2 ESB provides variety of options to monitor and manage the server runtime. While it + provides number of monitoring tools through the Web-based Management Console, WSO2 ESB also + supports Java Management Extensions (JMX) way of monitoring. +

+

+

+

+ Mediation Statistics +

+

+ Out of monitoring capabilities of WSO2 ESB, the Mediation Statistics feature stands out as + one of the most useful and widely used features. From functional components of the ESB, + sequences, proxy services and endpoints directly get involved in processing messages. The + Mediation Statistics feature enables a server administrator to collect runtime statistical + information on these three types of functional components and view them through the + Management Console. This feature provides a simple but effective way of determining the + runtime performance of the ESB. The collected statistical data can be used to analyze network + traffic patterns and draw rough estimates on how the service bus will be used in the future. + Perhaps the most enticing attribute of the mediation statistics feature is that it can be + configured in a fine grained manner. In other words, it allows a user to collect data on only + a specified set of sequences, proxy services and endpoints. +

+

+ Mediation Statistics component of WSO2 ESB uses an in-memory data store to keep the + collected data. The memory usage of the data store is restricted by the total number of + statistics collecting proxy services, sequences and endpoints. If the number of proxy + services, sequences and endpoints is constant, the memory usage of the mediation statistics + component stays constant. + + Mediation Statistics component also supports persistence as an optional feature. That is, + one may configure the ESB to save statistics to the WSO2 Governance Registry instance that + comes embedded with the ESB. Mediation Statistics API allows easy sharing of collected + data, among Carbon components. Currently WSO2 Business Activity Monitor (BAM) makes use of + this API to access data collected by the service bus. Users can also develop custom data + consumers to retrieve mediation statistics from the in-memory data store and process them + further, using this API. +

+ +

+ Enabling Mediation Statistics +

+

+ Mediation Statistics feature is available with WSO2 ESB out of the box. You do not have to + configure anything to use this feature. Simply sign-in to the Management Console and enable + statistics on the sequences, proxy services and endpoints you want to monitor, and the service + bus will start collecting data on them. For an example, in order to enable statistics for a + sequence, click on Service Bus > Sequences in the left menu and simply click + on the Enable Statistics icon corresponding to that sequence. +

+

+ +

+ Enabling Mediation Statistics +

+

Figure 1: Enabling mediation statistics for a sequence

+

+ +

+ To enable statistics for a mediation component using the Synapse configuration language, set + the value of the "statistics" attribute to "enabled" on the sequence, proxy or endpoint + configuration. +

+ +

+ Viewing Mediation Statistics +

+

+ To view the gathered statistics, click Monitor > Mediation Statistics. + You will be shown a graphical summary of all collected statistics. +

+ +

+ Viewing Mediation Statistics +

+

Figure 2: Viewing mediation statistics

+

+ +

+ Starting from this view, you can drill down to see more fine grained data such as statistics + pertaining to a single sequence or a proxy service. You can even get statistics for different + operations on the same endpoint. Click Proxy Service Statistics link in the + upper right corner box of the UI shown in Figure 2 to view a summary of Proxy Service Statistics + (Figure 3) +

+ +

+ Viewing Mediation Statistics +

+

Figure 3: Mediation statistics of all proxy services

+

+ +

+ Select a proxy service from the "Proxy Services" list shown above to view statistics of that + proxy service. +

+ +

+ Viewing Mediation Statistics +

+

Figure 4: Mediation statistics of a proxy service

+

+

+

Transport Statistics, System Statistics and System Logs

+

+ WSO2 ESB Management Console provides ways to monitor + + System Statistics, Transport Statistics and + System Logs. +

+

+ SOAP Tracer and + Mediation Tracer are some additional + monitoring tools provided by WSO2 ESB. +

+

+

+ JMX Monitoring +

+

+ WSO2 ESB exposes number of management resources as JMX MBeans that can be used for managing + and monitoring the running server. These MBeans can be accessed remotely using a JMX client + such as JConsole. When WSO2 ESB is starting up, it will display the JMX Service URL in the + console as follows. +

+
+    INFO - JMXServerManager JMX Service URL :         service:jmx:rmi://localhost:11111/jndi/rmi://localhost:9999/jmxrmi
+    
+

+ This URL can be used to remotely access the JMX Service exposed by WSO2 ESB. In this guide, + we will use JConsole as the JMX client to access this service. +

+

+ Using JConsole for JMX Monitoring +

+

+ Start JConsole and enter the above URL as the JMX Service URL. Type "admin" in both + username and password fields and click "Connect". +

+

+ JConsole Login +

+

Figure 5: Connecting to the JMX service using JConsole

+

+ +

+ After successfully connecting to the JMX service, click on "MBeans" tab of JConsole to view + MBeans exposed by the ESB. As shown in Figure 6, these are listed under org.apache.axis2 + and org.apache.synapse nodes. The following section summarizes the attributes and operations + available in MBeans exposed by the WSO2 ESB. +

+

+ JConsole Login +

+

Figure 6: Viewing MBeans exposed by WSO2 ESB

+

+

+ Attributes and Operations of MBeans +

+ +
    +
  • Transport related MBeans: For each transport listener and sender enabled in the + ESB, there will be an MBean under org.apache.axis2/Transport node which has following + attributes and operations. For example, when http and https transports are enabled following + MBeans will be exposed. +
      +
    • org.apache.axis2/Transport/nio-http-listener
    • +
    • org.apache.axis2/Transport/nio-http-sender
    • +
    • org.apache.axis2/Transport/nio-https-listener
    • +
    • org.apache.axis2/Transport/nio-https-sender
    • +
    +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + Attribute/Operation Name + + Description +
    ActiveThreadCountThreads active in this transport listener/sender.
    AvgSizeReceivedAverage size of received messages.
    AvgSizeSentAverage size of sent messages.
    MaxSizeReceivedMaximum message size of received messages.
    MaxSizeSentMaximum message size of sent messages.
    MinSizeReceivedMinimum message size of received messages.
    MinSizeSentMinimum message size of sent messages.
    MessagesReceivedTotal number of messages received through this transport.
    MessagesSentTotal number of messages sent through this transport.
    FaultsReceivingNumber of faults encountered while receiving.
    FaultsSendingNumber of faults encountered while sending.
    BytesReceivedNumber of bytes received through this transport.
    BytesSentNumber of bytes sent through this transport.
    QueueSizeNumber of messages currently queued. Messages get queued if all the worker threads + in this transport thread pool are busy. +
    ResponseCodeTableNumber of messages sent against their response codes. +
    TimeoutsReceivingMessage receiving timeout.
    TimeoutsSendingMessage sending timeout.
    LastResetTimeLast time transport listener/sender statistic recording was reset. +
    MetricsWindowTime difference between current time and last reset time in milliseconds.
    resetStatistics()Clear recorded transport listener/sender statistics and restart recording.
    start()Start this transport listener/sender.
    stop()Stop this transport listener/sender.
    pause()Pause this transport listener/sender which has been started.
    resume()Resume this transport listener/sender which is currently paused.
    maintenenceShutdown(long gracePeriod)Stop processing new messages, and wait the specified maximum time for in-flight + requests to complete before a controlled shutdown for maintenence.
    +

    +

    +

  • +
  • Latency related MBeans: +

    +

      +
    • org.apache.synapse/NHTTPLatencyView/nio-http
    • +
    • org.apache.synapse/NHTTPLatencyView/nio-https
    • +
    • org.apache.synapse/NHTTPS2SLatencyView/nio-http
    • +
    • org.apache.synapse/NHTTPS2SLatencyView/nio-https
    • +
    +

    + + + + + + + + + + + + + + + + + + + + + + + + + +
    + Attribute/Operation Name + + Description +
    AllTimeAvgLatencyAverage latency since latency recording was last reset.
    LastXxxAvgLatencyAverage latency for last Xxx time period. For example, + LastHourAvgLatency return the average latency for last hour. +
    LastResetTimeLast time latency statistic recording was reset.
    reset()Clear recorded latency statistics and restart recording.
    +

    +

    +

  • +
  • + NttpConnections related MBeans: +

    +

      +
    • org.apache.synapse/NhttpConnections/http-listener
    • +
    • org.apache.synapse/NhttpConnections/http-sender
    • +
    • org.apache.synapse/NhttpConnections/https-listener
    • +
    • org.apache.synapse/NhttpConnections/https-sender
    • +
    +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + Attribute/Operation Name + + Description +
    ActiveConnectionsNumber of currently active connections.
    ActiveConnectionsPerHostsA map of number of connections against hosts.
    LastXxxConnectionsNumber of connections created during last Xxx time period.
    RequestSizesMapA map of number of requests against their sizes.
    ResponseSizesMapA map of number of responses against their sizes.
    LastResetTimeLast time connection statistic recordings was reset.
    reset()Clear recorded connection statistics and restart recording.
    +

    +

    +

  • + +
  • + Threading related MBeans: +

    +

      +
    • org.apache.synapse/Threading/HttpClientWorker
    • +
    • org.apache.synapse/Threading/HttpServerWorker
    • +
    +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + Attribute/Operation Name + + Description +
    TotalWorkerCountTotal worker threads related to this server/client.
    AvgUnblockedWorkerPercentageTime-averaged unblocked worker thread percentage.
    AvgBlockedWorkerPercentageTime-averaged blocked worker thread percentage.
    LastXxxBlockedWorkerPercentageBlocked worker thread percentage averaged for last Xxx time period.
    DeadLockedWorkersNumber of deadlocked worker threads since last statistics reset.
    LastResetTimeLast time thread statistic recordings was reset.
    reset()Clear recorded thread statistic and restart recording.
    +

  • + +
+ + + diff --git a/docs/xdoc/priority_mediation.xml b/docs/xdoc/priority_mediation.xml new file mode 100644 index 0000000000..b71ce68457 --- /dev/null +++ b/docs/xdoc/priority_mediation.xml @@ -0,0 +1,176 @@ + + + + + + + + + WSO2 ESB - Priority Mediation + + + + + + [ Documentation Index ] +

WSO2 Enterprise Service Bus (ESB) Priority Mediation

+

Contents

+ +

Introduction

+

+ An ESB can be deployed as a front end for various services with a very high load passing through it. The traffic passing through it may be of different priorities and can have different load charasterisitcs. Also in some situations load of different types of messages can vary dramatically over time.

+

+ The goal is to serve high priority traffic when there are resources available in the system regardless of the low priority traffic. The serving of different priority messages should be independent as much as possible. For example an ESB can be bombarded with very high volume of low priority traffic. Even in this case ESB should obey its contract to serve high priority traffic.

+

Usually a person deploying an ESB expects a certain guarantee of message deliverance from the ESB. ESB should be able to honor that.

+

+ Here is a possible scenario with a high volume of traffic.

+

+ Lets assume ESB is configured to serve two types of messages with different priorities. Message type m1 has the priority p1 and message type m2 has priority p2. p1 is about ten times the priority of p2. In a very high volume traffic scenario the services can afford to loose some amount of m2 messages. But it cannot afford to loose any of m1 messages.

+

+ In normal operation mode, volume of m2 is about twice as m1. But in some situations m1 can be higher and m2 can be low.

+

+ The expectation is to serve the m1 traffic no matter what the volume of m2 traffic is.

+

Priority Based Mediation Configuration Model

+ +

Priority based mediation can be configured at two levels.

+
    +
  • HTTP transport level
  • +
  • Mediation level
  • +
+

+ At both configuration levels priority-executor configuration is present.

+

Priority Executor

+
<priority-executor name="priority-executor">
+    <queues isFixed="true|false" nextQueue="class implementing NextQueueAlgorithm">
+        <queue [size="size of the queue"] priority="priority of the messages put in to this queue"/>*
+    </queues>
+    <threads core="core number of threads" max="max number of threads' keep-alive="keep alive time"/>
+</priority-executor>
+       
+

+ An executor is a Thread Pool Executor with separate queues for different priorities. +

+

+ The queues can have a fixed depths or they can be un-bounded queues. This is controlled by the isFixed attribute.

+

+ A executor should have at least two or more queues. If only one queue is used there is no point in using a priority executor. It only adds some overhead.

+

+ A Queue can have a size and a priority. If the queues has unlimited length, no more than core threads will be used.

+

+ A Priority Executor has a core number of threads. When ESB is started with the priority executor, this number of threads will be created. Max is the maximum number of threads this executor will have. If the number of threads in the executor exceeds the core threads, they will be in active for the keep-alive time only. After the keep-alive time those threads will be be removed from the system. +

+

HTTP Level Configuration

+

+ HTTP level configuration is done by using a separate xml configuration file.

+

+ This configuration file should be referred from the Nhttp transport receiver configuration in the axis2.xml.

+
<parameter name="priorityConfigFile">file path</parameter>
+

Here is the syntax of the priority configuration at the HTTP level.

+
<Priority-Configuration>
+    <priority-executor name="priority-executor">
+        <queues isFixed="true|false">
+            <queue [size=""] priority=""/>*
+        </queues>
+        <threads core="core number of threads" max="max number of threads' keep-alive="keep alive time"/>
+    </priority-executor>
+
+    <!-- conditions for calculating the priorities based on HTTP message -->
+    <conditions defaultPriority="default priority as an integer">
+        <condition priority="priority value as an integer">
+            one evaluator, this evaluator can contain other evaluators
+        </condition>
+    </conditions>
+</Priority-Configuration>
+

+ Priority executor configuration is explained in the previous section.

+

+ A priority configuration can have multiple conditions. A condition is evaluated over a HTTP message. A condition return true or false. If a condition evaluates to true, message will be executed with the priority associated with the condition.

+

+ A condition can have a single boolean expression. Here are the supported boolean operators and expressions.

+
    +
  • equal
  • +
  • match
  • +
  • not
  • +
  • and
  • +
  • or
  • +
+

+ eqaul and match are leaf level expressions. 'not', 'and' and 'or' can contain other expressions.

+

equal

+
<equal type="header | param | url" source="" value=""/>
+

Equal fetch the value specified by the source from a HTTP header, parameter. Then it equals it against the value attribute. For example

+
<eqaul type="header" source="priority" value="10"/>
+

+ This gets the HTTP header named priority and equals it to 10. If the values are equal it return true.

+

match

+
<match type="header | param | url" source="" regex=""/>
+

Match is similar to equal. Only difference is instead of just trying to see weather the two values are equal, it uses a regular expression to match the source. If the regular expression matches the source it will return true

+

not

+
<not>
+    any boolean operator or boolean expression
+</not>
+
+

Not can have another boolean expression inside of it. Not negates the boolean value returned by the boolean expression inside.

+

and

+
<and>
+    two or more boolean boolean expressions
+</and>
+

And can have two or more boolean expressions. It does the boolean and for the enclosing expressions.

+

or

+
<or>
+    any boolean operator or boolean expression
+</or>
+        
+

"or" is same as "and" configuration except it gets the boolean 'or' for the enclosing expressions.

+

Mediation level Configurations

+

+ At mediation level multiple priority executors can be defined at the top level of the sypase configuration. These executors should have a unique name.

+
<priority-executor name="priority-executor">
+     <queues isFixed="true|false">
+        <queue [size=""] priority=""/>*
+     </queues>
+    <threads core="core number of threads" max="max number of threads' keep-alive="keep alive time"/>
+</priority-executor>
+        
+

Executor configuration is same as the one described earlier.

+

+ To execute a sequence using a priority-executor enqueue mediator should be used. Here is the syntax of the enqueue mediator.

+

Enqueue Mediator

+
<enqueue priority="priority as an integer" executor="executor name to submit the responses" sequence="sequence name to be executed with the given priority"/>
+        
+

Enqueue mediator should be pointing to an priority-executor. Message coming in to the enqueue mediator will be executed using this priority-executor. Also it specifies a priority. This priority is applied to the messages. sequence attribute specifies the sequence to be executed with the given priority.

+ + diff --git a/docs/xdoc/properties_guide.xml b/docs/xdoc/properties_guide.xml new file mode 100644 index 0000000000..3cd73bd9b7 --- /dev/null +++ b/docs/xdoc/properties_guide.xml @@ -0,0 +1,1398 @@ + + + + + + ESB Properties and Parameters Catalog + + + + + + [ Documentation Index ] +

WSO2 Enterprise Service Bus (ESB) and Parameters Catalog

+

Contents

+ +

Introduction

+

Properties provide the means of accessing various information regarding a message + passing through the ESB. Also properties can be used to control the behaviour of the + ESB for a particular message as well.

+

Generic Properties

+

Property: synapse.isresponse

+ + + + + + + + + + + + + + + + + + + + + + + + + +
Namesynapse.isresponse
Possible Values"true", "false"
Default Behaviornone
Scopeaxis2
Description + Once this property is set to 'true' on a message, the ESB will start treating it + as a response message. It is generally used to route a request message back to its + source as the response. +
Example +
<property name="synapse.isresponse" value="true" scope="axis2"/>
+
+ +

Property: PRESERVE_WS_ADDRESSING

+ + + + + + + + + + + + + + + + + + + + + + + + + +
NamePRESERVE_WS_ADDRESSING
Possible Values"true", "false"
Default Behaviornone
Scopesynapse
Description + By default the ESB adds a new set of WS-Addressing headers to the messages forwarded + from the ESB. If this property is set to 'true' on a message the ESB will forward it + without altering its existing WS-Addressing headers. +
Example +
<property name="PRESERVE_WS_ADDRESSING" value="true"/>
+
+ +

Property: RESPONSE

+ + + + + + + + + + + + + + + + + + + + + + + + + +
NameRESPONSE
Possible Values"true", "false"
Default Behaviornone
Scopesynapse
Description + Same as synapse.isresponse property. It is recommended to use this property to flag + messages as responses instead of the synapse.isresponse property. +
Example +
<property name="RESPONSE" value="true"/>
+
+ +

Property: OUT_ONLY

+ + + + + + + + + + + + + + + + + + + + + + + + + +
NameOUT_ONLY
Possible Values"true", "false"
Default Behaviornone
Scopesynapse
Description + Set this property to 'true' on a message to indicate that no response message is + expected for it once it is forwarded from the ESB. In other words the ESB will do + an out-only invocation with such messages. It is very important to set this property + on messages that are involved in out-only invocations to prevent the ESB from registering + unnecessary callbacks for response handling and eventually running out of memory. +
Example +
<property name="OUT_ONLY" value="true"/>
+
+ +

Property: ERROR_CODE

+ + + + + + + + + + + + + + + + + + + + + + + + + +
NameERROR_CODE
Possible Valuesstring
Default Behaviornone
Scopesynapse
Description + Use this property to set a custom error code on a message which can be later processed + by a Synapse fault handler. If the Synapse encounters an error while mediation or + routing this property will be automatically populated. +
Example +
<property name="ERROR_CODE" value="100100"/>
+
+ +

Property: ERROR_MESSAGE

+ + + + + + + + + + + + + + + + + + + + + + + + + +
NameERROR_MESSAGE
Possible Valuesstring
Default Behaviornone
Scopesynapse
Description + Use this property to set a custom error message on a message which can be later + processed by a Synapse fault handler. If the Synapse encounters an error while + mediation or routing this property will be automatically populated. +
Example +
<log level="custom">
+                      <property name="Cause" value="get-property('ERROR_MESSAGE')"/>
+                  </log>
+
+ +

Property: ERROR_DETAIL

+ + + + + + + + + + + + + + + + + + + + + + + + + +
NameERROR_DETAIL
Possible Valuesstring
Default Behaviornone
Scopesynapse
Description + Use this property to set the exception stacktrace in case of an error. If the ESB + encounters an error while mediation or routing this property will be automatically + populated. +
Example +
<log level="custom">
+                          <property name="Trace" value="get-property('ERROR_DETAIL')"/>
+                      </log>
+
+ +

Property: ERROR_EXCEPTION

+ + + + + + + + + + + + + + + + + + + + + + + + + +
NameERROR_EXCEPTION
Possible Valuesjava.lang.Exception
Default Behaviornone
Scopesynapse
Description + Contains the actual exception thrown in case of a runtime error +
Example +
+
+ +

Property: TRANSPORT_HEADERS

+ + + + + + + + + + + + + + + + + + + + + + + + + +
NameTRANSPORT_HEADERS
Possible Valuesjava.util.Map
Default BehaviorPopulated with the transport headers of the incoming request
Scopeaxis2
Description + Contains the map of transport headers. Automatically populated. Individual + values of this map can be accessed using the property mediator in the transport + scope. +
Example +
<property name="TRANSPORT_HEADERS" action="remove" scope="axis2"/>
+
+ +

Property: messageType

+ + + + + + + + + + + + + + + + + + + + + + + + + +
NamemessageType
Possible Valuesstring
Default BehaviorContent type of incoming request
Scopeaxis2
Description + Message formatter is selected based on this property. This property should have the + content type i.e. text/xml, application/xml +
Example +
<property name="messageType" value="text/xml" scope="axis2"/>
+
+ +

Property: ContentType

+ + + + + + + + + + + + + + + + + + + + + + + + + +
NameContentType
Possible Valuesstring
Default BehaviorValue of the Content-type header of the incoming request
Scopeaxis2
Description + Message builder is selected based on this property. This property should specify + the content type. +
Example +
<property name="ContentType" value="text/xml" scope="axis2"/>
+
+ +

Property: disableAddressingForOutMessages

+ + + + + + + + + + + + + + + + + + + + + + + + + +
NamedisableAddressingForOutMessages
Possible Values"true", "false"
Default Behaviorfalse
Scopeaxis2
Description + Set this property to 'true' if you do not want the ESB to add WS-Addressing headers + to outgoing messages. This property can affect messages sent to backend services as + well as the responses routed back to clients. +
Example +
<property name="disableAddressingForOutMessages" value="true" scope="axis2"/>
+
+ +

Property: transportNonBlocking

+ + + + + + + + + + + + + + + + + + + + + + + + + +
NametransportNonBlocking
Possible Values"true", "false"
Default Behaviortrue
Scopeaxis2
Description + By default Axis2 will spawn a new thread to handle each outgoing message. To change + this behavior remove this property from the message. Removal of this property could + be vital when queuing transports like JMS are involved. +
Example +
<property name="transportNonBlocking" action="remove" scope="axis2" value="true"/>
+
+ +

Property: endpoint.operation

+ + + + + + + + + + + + + + + + + + + + + + + + + +
Nameendpoint.operation
Possible Valuesstring
Default Behaviornone
Scopesynapse
Description + If this property is set endpoint statistics will be calculated for the specified operation. +
Example +
<property name="endpoint.operation" scope="axis2" value="OperationName"/>
+
+

Property: SERVER_IP

+ + + + + + + + + + + + + + + + + +
+ Name + + SERVER_IP +
+ Possible Values + + IP address or hostname of the ESB host +
+ Default Behaviour + + Set automatically by the mediation engine upon startup +
+ Scope + + synapse +
+

Property: preserveProcessedHeaders

+ + + + + + + + + + + + + + + + + + + + + + + + + +
NamepreserveProcessedHeaders
Possible Valuestrue/false
Default BehaviorPreserving SOAP headers
Scopesynapse(default)
Description + If we set this property to 'true', synapse tries to preserve the SOAP header of incoming requests. + Else, by default synapse removes the soap headers. +
Example +
<property name="preserveProcessedHeaders" value="true" scope="default"/>
+
+

HTTP Transport Specific Properties

+

Property: POST_TO_URI

+ + + + + + + + + + + + + + + + + + + + + + + + + +
Name + POST_TO_URI +
Possible Values + "true", "false" +
Default Behaviour + false +
Scope + axis2 +
+ Description + + This property makes the outgoing URL of the ESB a complete URL. This is + important when we talk through a proxy server. +
+ Example + +
<property name="POST_TO_URI" scope="axis2" value="text/xml"/>
+
+

Property: DISABLE_CHUNKING

+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ Name + + DISABLE_CHUNKING +
+ Possible Values + + "true", "false" +
+ Default Behaviour + + false +
+ Scope + + axis2 +
+ Description + + Disables the HTTP chunking for outgoing messaging +
+ Example + +
<property name="POST_TO_URI" scope="axis2" value="text/xml"/>
+
+

Property: CONTENT_TYPE

+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ Name + + CONTENT_TYPE +
+ Possible Values + + string +
+ Default Behaviour + + none +
+ Scope + + axis2 +
+ Description + + In situations where the ESB is receiving HTTP response messages without the + Content-type header, this property can be used to specify a default content type + to be used. If no such content type is specified for responses the ESB will + default to 'application/octet-stream'. +
+ Example + +
<property name="CONTENT_TYPE" value="text/xml" scope="axis2"/>
+
+

Property: NO_ENTITY_BODY

+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ Name + + NO_ENTITY_BODY +
+ Possible Values + + none +
+ Default Behaviour + + In case of GET and DELETE requests this property is set to true +
+ Scope + + axis2 +
+ Description + + This property should be removed if a user want to generate a response from the + ESB to a request without an entity body. i.e. GET request +
+ Example + +
<property name="NO_ENTITY_BODY" action="remove" scope="axis2"/>
+
+

Property: FORCE_HTTP_1.0

+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ Name + + FORCE_HTTP_1.0 +
+ Possible Values + + "true", "false" +
+ Default Behaviour + + false +
+ Scope + + axis2 +
+ Description + + Force HTTP 1.0 for outgoing HTTP messages +
+ Example + +
<property name="FORCE_HTTP_1.0" value="true" scope="axis2"/>
+
+

Property: HTTP_SC

+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ Name + + HTTP_SC +
+ Possible Values + + HTTP status code number +
+ Default Behaviour + + none +
+ Scope + + axis2 +
+ Description + + Set the HTTP status code +
+ Example + +
<property name="HTTP_SC" value="true"
+                        scope="axis2"/>
+
+

Property: FAULTS_AS_HTTP_200

+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ Name + + FAULTS_AS_HTTP_200 +
+ Possible Values + + "true", "false" +
+ Default Behaviour + + false +
+ Scope + + axis2 +
+ Description + + When ESB receives a soap fault as a HTTP 500 message ESB will forward this fault + to client with status code 200 +
+ Example + +
<property name="FAULTS_AS_HTTP_200" value="true"
+                        scope="axis2"/>
+
+

Property: NO_KEEPALIVE

+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ Name + + NO_KEEPALIVE +
+ Possible Values + + "true", "false" +
+ Default Behaviour + + false +
+ Scope + + axis2 +
+ Description + + Disables HTTP keep alive for outgoing requests +
+ Example + +
<property name="NO_KEEPALIVE" value="true"
+                        scope="axis2"/>
+
+

Property: REST_URL_POSTFIX

+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ Name + + REST_URL_POSTFIX +
+ Possible Values + + A URL fragment starting with "/" +
+ Default Behaviour + + In Case of GET requests this contains the query string +
+ Scope + + axis2 +
+ Description + + The value of this property will be appended to the target URL when sending + messages out in RESTful manner. Useful when it is required to append a context + to the target URL in case of RESTful invocations. +
+ Example + +
<property name="REST_URL_POSTFIX" value="/context"
+                        scope="axis2"/>
+
+

Property: REMOTE_HOST

+ + + + + + + + + + + + + + + + + +
+ Name + + REMOTE_HOST +
+ Possible Values + + IP address or hostname of the remote client +
+ Default Behaviour + + Set automatically by the NHTTP transport upon receiving a request +
+ Scope + + axis2 +
+

Property: HTTP_METHOD

+ + + + + + + + + + + + + + + + + +
+ Name + + HTTP_METHOD +
+ Possible Values + + GET, POST, PUT, DELETE, HEAD or any other valid HTTP method +
+ Default Behaviour + + Set automatically by the NHTTP transport upon receiving a request +
+ Scope + + axis2 +
+

Property: REMOTE_ADDR

+ + + + + + + + + + + + + + + + + +
+ Name + + REMOTE_ADDR +
+ Possible Values + + IP address or hostname of the remote client +
+ Default Behaviour + + Set automatically by the NHTTP transport upon receiving a request +
+ Scope + + axis2 +
+ +

SOAP Headers

+

Header Name: To

+ + + + + + + + + + + + + + + + + +
+ Header Name + + To +
+ Possible Values + + Any URI +
+ Description + + The To header of the message +
+ Example + + get-property('To') +
+

Header Name: From

+ + + + + + + + + + + + + + + + + +
+ Header Name + + From +
+ Possible Values + + Any URI +
+ Description + + The From header of the message +
+ Example + + get-property('From') +
+

Header Name: Action

+ + + + + + + + + + + + + + + + + +
+ Header Name + + Action +
+ Possible Values + + Any URI +
+ Description + + The SOAPAction header of the message +
+ Example + + get-property('Action') +
+

Header Name: ReplyTo

+ + + + + + + + + + + + + + + + + +
+ Header Name + + ReplyTo +
+ Possible Values + + Any URI +
+ Description + + The ReplyTo header of the message +
+ Example + + <header name="ReplyTo" action="remove"/> +
+

Header Name: MessageID

+ + + + + + + + + + + + + + + + + +
+ Header Name + + MessageID +
+ Possible Values + + UUID +
+ Description + + The unique message ID of the message. It's not recommended to make alterations + to this property of a message. +
+ Example + + get-property('MessageID') +
+

Header Name: RelatesTo

+ + + + + + + + + + + + + + + + + +
+ Header Name + + RelatesTo +
+ Possible Values + + UUID +
+ Description + + The unique ID of the request to which the current message is related. Not + recommended to make changes. +
+ Example + + get-property('RelatesTo') +
+

Header Name

+ + + + + + + + + + + + + + + + + +
+ Header Name + + FaultTo +
+ Possible Values + + Any URI +
+ Description + + The FaultTo header of the message +
+ Example + +
<header name="FaultTo" value="http://localhost:9000"/>
+
+ + diff --git a/docs/xdoc/quickstart_guide.xml b/docs/xdoc/quickstart_guide.xml new file mode 100644 index 0000000000..d1f7681ec3 --- /dev/null +++ b/docs/xdoc/quickstart_guide.xml @@ -0,0 +1,698 @@ + + + + + + + + + + WSO2 ESB - Quick Start Guide + + + + + + [ Documentation Index ] +

+ WSO2 Enterprise Service Bus (ESB) Quick Start Guide +

+

+ This guide demonstrates two sample applications covering the basic and the + most common usage scenarios of WSO2 ESB, namely Message Mediation + and Service Mediation (using Proxy Services). You will be guided through a + series of steps to create, execute, and analyze these mediation + configurations using the ESB Management Console. +

+

Contents

+ +

+ Prerequisites +

+

+ You should have the following prerequisites installed on your system to + follow this guide. +

+
    +
  • + Java SE - JDK or JRE version 1.6.x or higher +
  • +
  • + Apache Ant version 1.7.0 or higher +
  • +
+

+

+ Message Mediation +

+

+

+ In this example, ESB will be used to filter and log the messages passing + through it. Although this simple scenario only performs simple filtering + and logging, it demonstrates the basics of message mediation, where this + simple functionality could be replaced with any combination of advanced + mediations such as transformations, and content based routing as well as + bridging between different communication protocols. Let's start with + the basics. +

+

+ Download +

+

+ Our first task is to download WSO2 ESB. Open a Web browser and access + + http://wso2.org/downloads/esb. You will then + see the list of available releases. Click on the latest release version, + and you will be directed to the WSO2 ESB latest release download page. Now + download the binary distribution as a ZIP archive. +

+

+ Installation +

+

+ WSO2 ESB can be installed by simply extracting the downloaded binary archive. A + directory named wso2esb with the version number will be created in the + current working directory, containing all the files required by the ESB. + We will refer to this directory as <esb-home> from now on. +

+

+ Running the Sample Scenario +

+

+ WSO2 ESB acts as the intermediary between the client and the server. + Hence, you will need to run three programs to get an idea of message + mediation. The destination server that hosts the backend service that has + to be invoked to service the client, the client itself, and the WSO2 ESB, + which sits in between to perform the mediation. +

+

+

+

+ Starting WSO2 ESB + +

+

+

+ Let's first start the WSO2 ESB. Set the log level of org.apache.synapse + to DEBUG by editing the + <esb-home>/lib/log4j.properties file. This will cause the ESB + to output debug messages for the actions it is performing. We can inspect + these logs later using the Management Console. Then go to the <esb-home>/bin + folder and execute the following command. +

+
Linux: ./wso2server.sh
+Windows: wso2server.bat
+

+ You will see the following message on the console to indicate that the + ESB started successfully. +

+
+[2011-05-23 13:57:03,248]  INFO - StartupFinalizerServiceComponent WSO2 Carbon started in 20 sec
+
+

+

+ Configuring the ESB to Perform Message Mediation + +

+

+

+ After starting the ESB, we have to configure it to perform the required + message mediation. WSO2 ESB starts with a default configuration, which is + sufficient for our first scenario. Later on, we will change this + configuration using the management console to build different mediations. + Now examine the default configuration using the ESB console. Open a Web + browser and point it to + + https://localhost:9443/carbon. You will be + directed to the login screen of the Management Console shown below. +

+

+

+ Login screen +

+

+

+ The Management Console ships with a default username and password + combination: "admin", "admin". + Type "admin" in both the username and password fields and click + Sign In. You will be directed to the main page of the ESB Management + Console, which displays information about the ESB as well as brief + descriptions about its environment. Click on + Monitor > System Logs in the left-hand side navigation pane + to display log messages of the system. You will see the same + set of log messages displayed in the command line, when starting the ESB. + Now click Monitor > System Statistics + to view runtime statistics of the + system. You will notice that currently there are no runtime statistics as + no message mediation has happened. +

+

+

+ Now it is time to examine the mediation configuration visually. Click on + the Sequences link on the left panel. In the + Defined Sequences tab you will see that two sequences + named "fault" and "main" are currently available. These two sequences are + generated automatically by the ESB at start up. We can add any number of + sequences using this page to suit our mediation requirements. However these + pre-defined sequences are sufficient for this sample application. Let's + analyze what happens to the messages inside the main sequence by clicking + on the Edit link of the "main" sequence. You will see a + set of mediators listed for the main sequence as shown below. +

+

+

+ Main sequence +

+

+

+

+ You will see there are two mediators named "In" and "Out" at the top + level. These two mediators handle request messages + and response messages respectively. Inside the In Mediator, two mediators + named Log Mediator and Filter Mediator are listed as children. Therefore, + incoming messages will flow through these two mediators. +

+

+ You will notice that Log Mediator is configured to log all the details of + the messages (i.e. full log level) and Filter Mediator is configured only + to pass through messages containing "http://localhost:9000" in the + WS-Addressing header. You can change this default configuration by + clicking on the corresponding mediator icon and modifying the parameter values + in the form which appears below. A Send Mediator is listed as + the child of the Filter Mediator. Therefore, filtered messages will be + sent to the specified WS-Addressing destination. That's all we do for the + request messages. Now let's look at the Out Mediator. There is only a Send + Mediator defined in the Out Mediator by default. This will just send + response messages back to the client. +

+

+ Now we have a basic understanding about the message flow inside the ESB. + We are going to make a small modification to the main sequence to enable + statistics monitoring and tracing. Just click on the "Sequences" + link in the left menu to display all the available sequences. +

+

+ Now click on the first two icons under the Actions heading of the "main" + sequence, namely Enable Statistics and + Enable Tracing. +

+

+ Now we are done with the ESB configuration. It's time to continue the rest + of the steps and see it in action. +

+

+

+ +

+ Starting the Sample Apache Axis2 Server + +

+

+

+ Here we are using a standalone Apache Axis2 Web services engine as the + server. You don't have to get it now, as it is already bundled with your + ESB distribution. We have to deploy a sample service to which the client + can send requests. Go to <esb-home>/samples/axis2Server/src/SimpleStockQuoteService + directory. Run "ant" to build and deploy this service to the sample Axis2 + server. +

+
user@host:~/wso2esb/samples/axis2Server/src/SimpleStockQuoteService$ ant
+Buildfile: build.xml
+
+clean:
+
+init:
+    [mkdir] Created dir: /home/user/wso2esb/samples/axis2Server/src/SimpleStockQuoteService/temp
+    [mkdir] Created dir: /home/user/wso2esb/samples/axis2Server/src/SimpleStockQuoteService/temp/classes
+    [mkdir] Created dir: /home/user/wso2esb/samples/axis2Server/repository/services
+
+compile-all:
+    [javac] Compiling 9 source files to /home/user/wso2esb/samples/axis2Server/src/SimpleStockQuoteService/temp/classes
+
+build-service:
+    [mkdir] Created dir: /home/user/wso2esb/samples/axis2Server/src/SimpleStockQuoteService/temp/SimpleStockQuote
+    [mkdir] Created dir: /home/user/wso2esb/samples/axis2Server/src/SimpleStockQuoteService/temp/SimpleStockQuote/META-INF
+     [copy] Copying 1 file to /home/user/wso2esb/samples/axis2Server/src/SimpleStockQuoteService/temp/SimpleStockQuote/META-INF
+     [copy] Copying 1 file to /home/user/wso2esb/samples/axis2Server/src/SimpleStockQuoteService/temp/SimpleStockQuote/META-INF
+     [copy] Copying 9 files to /home/user/wso2esb/samples/axis2Server/src/SimpleStockQuoteService/temp/SimpleStockQuote
+      [jar] Building jar: /home/user/wso2esb/samples/axis2Server/repository/services/SimpleStockQuoteService.aar
+
+BUILD SUCCESSFUL
+Total time: 1 second
+

+ Now go to <esb-home>/samples/axis2Server directory and start the + server using the following command. This will start Axis2 server on port + 9000 (HTTP). +

+
+ Linux / Unix: ./axis2server.sh
Windows: axis2server.bat +
+

+ You will see the following messages on the console. +

+
user@host:~/wso2esb/samples/axis2Server$ ./axis2server.sh
+ Using JAVA_HOME:   /usr/java
+ Using AXIS2 Repository :   /home/user/wso2esb/samples/axis2Server/repository
+ Using AXIS2 Configuration :   /home/user/wso2esb/samples/axis2Server/repository/conf/axis2.xml
+2007-11-08 18:00:54,283 [-] [main]  INFO SimpleHTTPServer [SimpleAxisServer] Starting
+[SimpleAxisServer] Using the Axis2 Repository : /home/user/wso2esb/samples/axis2Server/repository
+[SimpleAxisServer] Using the Axis2 Configuration File : /home/user/wso2esb/samples/axis2Server/repository/conf/axis2.xml
+2007-11-08 18:00:55,494 [-] [main]  INFO HttpCoreNIOSender HTTPS Sender starting
+2007-11-08 18:00:55,495 [-] [main]  INFO HttpCoreNIOSender HTTP Sender starting
+2007-11-08 18:00:55,798 [-] [main]  INFO HttpCoreNIOListener HTTPS Listener starting on port : 9002
+2007-11-08 18:00:55,804 [-] [main]  INFO HttpCoreNIOListener HTTP Listener starting on port : 9000
+2007-11-08 18:00:55,805 [-] [main]  INFO SimpleHTTPServer [SimpleAxisServer] Started
+

+

+

+ Running the Client + +

+

+

+ The final step is running the client. Go to <esb-home>/samples/axis2Client + directory and type the following command. +

+
ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280 -Dsymbol=IBM -Dmode=quote
+

+ You can see the following output with the quote price sent by the server. +

+
user@host:~/wso2esb/samples/axis2Client$ ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280 -Dsymbol=IBM -Dmode=quote
+Buildfile: build.xml
+
+init:
+    [mkdir] Created dir: /home/user/wso2esb/samples/axis2Client/target/classes
+
+compile:
+    [javac] Compiling 10 source files to /home/user/wso2esb/samples/axis2Client/target/classes
+
+stockquote:
+     [java] Standard :: Stock price = $82.19300717003419
+
+BUILD SUCCESSFUL
+Total time: 4 seconds
+

+ This sends a request for a stock quote for the symbol IBM, sets the + transport URL to the ESB (http://localhost:8280), and the WS-Addressing + EPR set to the actual server + (http://localhost:9000/services/SimpleStockQuoteService). The actual wire + level HTTP message sent by the client is as follows, and is sent over port + 8280 to the ESB instance on the localhost. +

+
POST / HTTP/1.1
+Content-Type: text/xml; charset=UTF-8
+SOAPAction: "urn:getQuote"
+User-Agent: Axis2
+Host: 127.0.0.1
+Transfer-Encoding: chunked
+
+218
+<?xml version='1.0' encoding='UTF-8'?>
+   <soapenv:Envelope xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
+      <soapenv:Header>
+         <wsa:To>http://localhost:9000/services/SimpleStockQuoteService</wsa:To>
+         <wsa:MessageID>urn:uuid:D538B21E30B32BB8291177589283717</wsa:MessageID>
+         <wsa:Action>urn:getQuote</wsa:Action>
+      </soapenv:Header>
+      <soapenv:Body>
+         <m0:getQuote xmlns:m0="http://services.samples">
+            <m0:request>
+               <m0:symbol>IBM</m0:symbol>
+            </m0:request>
+         </m0:getQuote>
+      </soapenv:Body>
+   </soapenv:Envelope>0
+

+

+

+ Monitoring the Mediation + +

+

+

+ We have just performed a message mediation using the WSO2 ESB. Now let's + analyze how ESB has behaved by looking at the various visual monitoring + tools provided by the ESB. First click on Monitor > System Logs + to see the log + messages produced by the ESB. You will see a log messages view as shown + below, displaying the actions performed by the ESB in the mediation + process. +

+

+

+ System logs +

+

+ Now click on Monitor > Mediation Tracer to view the + trace messages emitted by the ESB. + You will see trace messages as shown in the following image. +

+

+

+ Trace messages +

+

+

+ Now let's move on to viewing mediation statistics. Click + Monitor > Mediation Statistics to view the overall + runtime statistics graphically. You will see the updated statistics + reflecting the message mediation we have just performed. +

+

+

+ Overall statistics +

+

+ Top left box displays the mediated messages per server. Bottom right box + displays the mediated messages per sequence. +

+

+

+ Now let's go deeper into the statistics console and get more information + about the runtime statistics. First click on the + Server Statistics + in the top left box. You will be presented with a summary of the + server statistics containing total messages, average response time, etc. + In the same way, you will be able to view summarized statistics for + sequences by clicking on Sequence Statistics in the + bottom right box. +

+

+ You have successfully completed the first part of this + guide. Now let's look at the next scenario, Proxy Services. +

+

+

+ Proxy Services +

+

+

+ As the name implies, a proxy service acts as a service hosted in the WSO2 + ESB, and typically fronts an existing service endpoint. A proxy service + can be created and exposed on a different transport, schema, WSDL, or QoS + (such as WS-Security, WS-Reliable Messaging) aspect than the real service, + and can mediate the messages before being delivered to the actual + endpoint, and the responses before they reach the client. +

+

+ Clients can send requests for proxy services directly to the ESB, as the + client sees it as being hosted on it. For example it can perform ?wsdl and + view the WSDL of the virtual proxy service. In the ESB configuration, such + requests can be handled in anyway you like. The most obvious thing would + be to process the message and send it to the actual service, probably + running on a different computer, but it is not necessary to always send + the message to the actual service. You may list any combination of tasks + to be performed on the messages received for the proxy service and + terminate the flow or send some message back to the client even without + sending it to an actual service. Let's explore a simple proxy services + scenario to get a better understanding. As you have downloaded and + installed the WSO2 ESB in the previous section, now you can start directly + on the sample application. +

+

+

+ Running the Sample Scenario +

+

+ As in the previous section, there should be three entities running to + demonstrate proxy services, the server, client, and the ESB. Let's start + with configuring the ESB with a proxy service to suit our scenario. +

+

+

+

+ Configuring WSO2 ESB + +

+

+

+ Start the ESB as the previous section and log in to the Management + Console. Click Web Services > List on the left panel. + You will see that currently no proxy services have been defined. + Let's add a new proxy + service by clicking Web Services > Add > Proxy Service + on left panel. You will be shown a list of + standard proxy service templates to choose from. +

+

+

+ Proxy Service Templates +

+

+

+ Select the Custom Proxy template from the list and you + will be directed to the proxy service creation wizard as shown below. +

+

+

+ Proxy service creation wizard +

+

+

+ First give a name to the new proxy service. In this sample type + "StockQuoteProxy" as the name of the proxy service. +

+

+ Next we are going to specify a WSDL for this proxy service. It can be + displayed using the ?wsdl operation with an actual service. Select + 'Specify Source URL' in the 'Publishing WSDL' drop down list under 'General Settings'. + You will be prompted with a text box to enter the URL of the WSDL. Type + file:repository/samples/resources/proxy/sample_proxy_1.wsdl as the WSDL + URL and click on 'Test URI' button to instantly validate the path. +

+

+ Next, select the transports that you need to expose the proxy service. By default proxy + service will available in both HTTP and HTTPS transports. Also you can add service parameters to proxy service. + During ESB startup process, it will start all proxy services and that may need to fetch WSDLs associated + with proxy services. If ESB cannot locate those WSDLs during statup, it + will ignore such services and continue with the startup process. +

+

+ Then click Next at the bottom of the page to proceed to the next step of the + proxy service creation wizard. As the next step of the wizard we will add a + target endpoint to handle request messages and a target in sequence to + handle request messages. To add a target endpoint, select the option 'Define Inline' + under 'Define Endpoint' and click on Create button that appears. + In the next sub menu select Address Endpoint. A web form + will be displayed to configure the new endpoint. +

+

+

+ Create Address Endpoint +

+

+

+ Type the EPR of the target endpoint in the Address field. In this case it is + "http://localhost:9000/services/SimpleStockQuoteService". Address endpoint + editor is shown above. Keep other fields unchanged and + click Save to add the endpoint to the proxy service. +

+

+ As for the In Sequence, we will leave it empty for this sample. So click on + Next to proceed to the next step of the wizard. +

+

+

+ Proxy Service Wizard - Final Step +

+

+ The next step is to add an out sequence to the proxy service. We just want + to send the response messages back to the client in this out sequence. + Select 'Define Inline' under 'Define Out Sequence' and click + Create. You will be presented with a + sequence editor. Click on the 'Add Child' icon and select 'Core' and then + 'Send', from the sub menu. A send mediator with default configuration will + be added. Click Save to save the out sequence + configuration. Finally on the wizard click Finish to save + and quit the wizard. +

+

+

+ Now on the services listing page you will be able to see the newly created + proxy service. Click on the service name link to enter the service dashboard. + On the service dashboard page you will see the actions that can be + performed on our new proxy service. Enable the statistics and tracing for + the proxy service by clicking on the appropriate icons. +

+

+

+ Service Dashboard +

+

+

+ We have finished configuring the proxy service for our sample. Now let's + continue the rest of the sample. +

+

+

+

+ Starting the Sample Apache Axis2 Server + +

+

+

+ As you have built and deployed the SimpleStockQuote service in the + previous section, you can simply start the server by switching to the <esb-home>/samples/axis2Server + directory and running the following command. +

+
+

+ Linux / Unix: ./axis2server.sh +

+

+ Windows: axis2server.bat +

+
+

+ You can see the console messages as in the previous section. +

+

+

+

+ Running the Client + +

+

+ +

+ Go to the <esb-home>/samples/axis2Clients directory and type the + following command: +

+
+ ant stockquote -Dtrpurl=http://localhost:8280/services/StockQuoteProxy + -Dmode=quote -Dsymbol=IBM +
+

+ The above command sends a stockquote request directly to the provided + transport endpoint at: http://localhost:8280/services/StockQuoteProxy. You + will see the response from the server displayed on the console as follows: +

+
+ Standard :: Stock price = $165.32687331383468 +
+

+

+

+ Monitoring the Mediation + +

+

+

+ As with the previous message mediation sample, you will be able to monitor + log messages, trace messages, and statistics for the proxy services based + mediation. We will look only at the statistics section, which is going to + be different from the previous sample. Click + Monitor > Mediation Statistics. You will be + directed to the overall statistics page. +

+

+ To get more information about proxy service statistics, click on + Proxy Service Statistics in the top right box. You will + see the summarized + statistics for the StockQuoteProxy service, we have created in this + example. +

+

+

+ Proxy Service Statistics +

+

+ This quick guide illustrates the visual construction of a proxy service + and a simple use case. Please refer to samples #150 and above in the + Samples guide, for in-depth coverage of more advanced use cases. You don't + have to worry about the configuration language too much when reading the + samples. You can build all those samples visually using the ESB management + console without editing any file at all. +

+

+

+ Yes, you are done with a quick look at the WSO2 ESB. Now it is time to go + deeper and reveal the advanced features of it. You can browse through the + samples of interested areas. If you have any issue regarding the ESB as a + user, feel free to let us know through the WSO2 ESB user mailing list + (esb-java-user@wso2.org). +

+ + diff --git a/docs/xdoc/release-notes.xml b/docs/xdoc/release-notes.xml new file mode 100644 index 0000000000..7c9c4c8a5a --- /dev/null +++ b/docs/xdoc/release-notes.xml @@ -0,0 +1,942 @@ + + + + + + + + WSO2 API Manager v1.7.0 - 23rd May 2014 + + +
+

The WSO2 API Manager 1.7.0 Released!

+ +

+ The WSO2 API Manager team is pleased to announce the release of version 1.7.0 of + the Open Source API Manager. +

+ +

+ WSO2 API Manager is a platform for creating, managing, consuming and monitoring + APIs. It employs proven SOA best practices to solve a wide range of API + management challenges such as API provisioning, API governance, API security + and API monitoring. It combines some of the most powerful and mature components + of the WSO2's state-of-the-art Carbon platform to deliver a smooth and end-to-end + API management experience while catering to both API publisher and API consumer + requirements. +

+ +

+ WSO2 API Manager is comprised of several modules. +

+
    +
  • API Provider: Define new APIs and manage them
  • +
  • API Store: Browse published APIs and subscribe to them
  • +
  • API Gateway: The underlying API runtime based on WSO2 ESB
  • +
  • API Key Manager: Performs Key Generation and Key Validation functionalities
  • +
+ +

+ WSO2 API Manager is developed on top of the revolutionary + WSO2 Carbon platform + (Middleware a' la carte), + an OSGi based framework that provides seamless modularity to your SOA via + componentization. This release also contains many new features and a range of + optional components (add-ons) that can be installed to customize the behavior + of the API Manager. Further, any existing features of the product which are not + required in your environment can be easily removed using the underlying + provisioning framework of Carbon. In brief, WSO2 API Manager can be fully + customized and tailored to meet your exact API management needs. +

+ +

+ For more information on WSO2 API Manager please visit + http://wso2.com/products/api-manager. Also take a look at the online product + documentation. +

+ +

How to Run

+
    +
  1. Extract the downloaded zip
  2. +
  3. Go to the bin directory in the extracted folder
  4. +
  5. Run the wso2server.sh or wso2server.bat as appropriate
  6. +
  7. Launch a web browser and navigate to https://localhost:9443/publisher + to access the API provider webapp +
  8. +
  9. Navigate to https://localhost:9443/store to access the API store
  10. +
  11. Navigate to https://localhost:9443/admin-dashboard to access Admin dashboard
  12. +
  13. Use "admin", "admin" as the username and password to login as an admin
  14. +
+ +

New Features in WSO2 API Manager 1.7.0

+
  • API Design Wizard
  • +
  • Support for OAuth2 Scopes
  • +
  • Statistics Dashboard for developers
  • +
  • Workflow integration for token generation
  • +
  • URL templating support for API definition
  • +
  • Customisable Store themes for tenants
  • +
  • Forum Support - API Store
  • +
  • Visibility Control for Documentation
  • +
  • Statistics dashboard for southbound API calls
  • +
  • Using Windows Authentication for OAuth2 Token generation
  • +
  • Ability to plugin reusable fault handling logic to APIs
  • +
  • Multi tenancy support for defining external stores, workflows & Google Analytics
  • +
  • Improvements to prevent Cross Site Scripting
  • + + + + +

    Bug Fixes +

    +
      +
    • [APIMANAGER-1775] - Add api fails with a registry error - during a volume test +
    • +
    • [APIMANAGER-1790] - Install Keymanager feature on top of WSO2 IS failed +
    • +
    • [APIMANAGER-1862] - User Token is still generated even when an additional character is appended at the end of the base 64 encoded value +
    • +
    • [APIMANAGER-1864] - Access token generation fails when username and password are similar +
    • +
    • [APIMANAGER-1870] - Jag Exception for API Created with metadata +
    • +
    • [APIMANAGER-1873] - Minor UI issue in Token Validity configuration in store +
    • +
    • [APIMANAGER-1886] - API Can be invoked after removing subscription +
    • +
    • [APIMANAGER-1901] - API-M 1.6.0 start up time is high +
    • +
    • [APIMANAGER-1910] - [Failover endpoint] When production endpoint is down, api invocation fails +
    • +
    • [APIMANAGER-1917] - [KeyManager] [Intermittent] While running a load test get 'ERROR {AUDIT_LOG} - Illegal access attempt' in keyManager +
    • +
    • [APIMANAGER-1925] - [Tenant store] APIs are shown only in recently added section, it does not show up in api list +
    • +
    • [APIMANAGER-1932] - wsdl validation does not validate whether the input is a wsdl or a URI +
    • +
    • [APIMANAGER-1940] - Even if the API fails to get published the state is mentioned as 'Published' +
    • +
    • [APIMANAGER-1957] - Observed error when starting IS after installing key manager feature +
    • +
    • [APIMANAGER-1958] - ResourceNotFoundException observed in key manager nodes +
    • +
    • [APIMANAGER-1967] - [Intermittent] [KeyM] System failed to authorize.null +
    • +
    • [APIMANAGER-1990] - The APIMgtFaultHandler mediator is content aware +
    • +
    • [APIMANAGER-1993] - API Store CSS does not render in IE 8 +
    • +
    • [APIMANAGER-2002] - Updating an API is not possible due to WSDL rewrites +
    • +
    • [APIMANAGER-2003] - Could not subscribe to API's - when a user role/(s) are revoked and trying to subscribe again +
    • +
    • [APIMANAGER-2006] - Re-written WSDL has only the IP:PORT of gateway endpoint +
    • +
    • [APIMANAGER-2013] - Issues in CORS headers management +
    • +
    • [APIMANAGER-2014] - Tryit now feature sends null key, later causes insert error in BAM +
    • +
    • [APIMANAGER-2020] - APIM Tier Permission page not loading +
    • +
    • [APIMANAGER-2028] - Cannot provide a registry resource as the wsdl url and create an API +
    • +
    • [APIMANAGER-2030] - Unable to add an API to external store once it was deleted +
    • +
    • [APIMANAGER-2031] - Exception on first log in attempt to key manager/gateway on a distributed setup +
    • +
    • [APIMANAGER-2037] - When adding an API, and when the API name contains special characters, the API addition fails, but the appeared UI message is not descriptive enough for the user to identify what went wrong. +
    • +
    • [APIMANAGER-2038] - Fix "alg" attribute +
    • +
    • [APIMANAGER-2041] - Workflow admin web application login.jag not loaded for the http url +
    • +
    • [APIMANAGER-2043] - User Sign up(Store) workflow : Rejected/Pending users are not removed +
    • +
    • [APIMANAGER-2045] - Any user with a camel case user name can't see generated sand box key. +
    • +
    • [APIMANAGER-2047] - Warning + Exception in the backend while listing Sequences from the Carbon Management Console +
    • +
    • [APIMANAGER-2048] - Cannot view any sequence in the Main -> Manage -> Sequences page in the Carbon Management Console +
    • +
    • [APIMANAGER-2049] - Task not updated/removed when user is deleted +
    • +
    • [APIMANAGER-2050] - Workflow admin web app does not load Application creation Approval tasks +
    • +
    • [APIMANAGER-2051] - Missing column in PostgreSQL db script +
    • +
    • [APIMANAGER-2052] - API gray-scaling for unapproved subscriptions does not work on firefox +
    • +
    • [APIMANAGER-2053] - User sign up is enabled in API store for read only external primary user stores. +
    • +
    • [APIMANAGER-2054] - Tenant user sign up through store is not restricted when sign up work flow is enabled +
    • +
    • [APIMANAGER-2057] - Cannot log in to publisher, store when a <WebContextRoot> is used +
    • +
    • [APIMANAGER-2059] - Error when invoking APIs with WSDL endpoints +
    • +
    • [APIMANAGER-2061] - Correct the spelling mistake in "API Usage from Destination" - statistics table title +
    • +
    • [APIMANAGER-2064] - Statistics update issue in API invocations with load balanced endpoints ( when an endpoint is not available) +
    • +
    • [APIMANAGER-2065] - API Invocation fails intermittently with Unclassified Authentication Failure. +
    • +
    • [APIMANAGER-2066] - Issues with faulty invocation statistics update +
    • +
    • [APIMANAGER-2067] - API stat publishing : Total duration does not show the usage for the entire period in API usage by user table +
    • +
    • [APIMANAGER-2068] - Error in storing OAuth2 token which is from SAML assertion in h2 database for the users who has capital letters in their name. +
    • +
    • [APIMANAGER-2069] - Cannot generate access tokens for the users who have capital letters in their username in h2 database +
    • +
    • [APIMANAGER-2071] - The traverse link add for APIStore and Publisher not working in sso mode +
    • +
    • [APIMANAGER-2076] - Embed solr indexing to APIStore search and add search by API description +
    • +
    • [APIMANAGER-2077] - Tenant support not available for Application grant type restriction +
    • +
    • [APIMANAGER-2081] - External API stores which are configured for the super tenant can be viewed by other tenants, in Publisher +
    • +
    • [APIMANAGER-2082] - External API stores which are configured for tenants cannot be seen in publisher +
    • +
    • [APIMANAGER-2083] - APIs which are not even in published state can be made visible to external stores +
    • +
    • [APIMANAGER-2084] - Once an API is published to an external store there is no way of removing it from that external store other than deleting the API +
    • +
    • [APIMANAGER-2086] - APIs published to external stores shows incorrect original publisher in Recently added API list +
    • +
    • [APIMANAGER-2087] - 'Test Endpoint button' says valid for some invalid endpoints +
    • +
    • [APIMANAGER-2088] - NPE when invoking the /token API for the first time with tenant user credentials +
    • +
    • [APIMANAGER-2091] - Cannot create an API with secured endpoints using Failover endpoints +
    • +
    • [APIMANAGER-2092] - Never Ending loop of retries with secured endpoints when using Loadbalanced endpoints +
    • +
    • [APIMANAGER-2094] - Application Token regeneration is broken in Store +
    • +
    • [APIMANAGER-2095] - Swagger doc gets overridden if two publishers create two APIs with the same name +
    • +
    • [APIMANAGER-2098] - Edit a published API throwing exception +
    • +
    • [APIMANAGER-2099] - workflow-admin application dosn't work when it accessed from management console url due to redirection issue. +
    • +
    • [APIMANAGER-2100] - New API resource definition UI wizard in publisher, is not visible in IE +
    • +
    • [APIMANAGER-2101] - [UI] 'Add new resource' button in API creation wizard is not working with IE +
    • +
    • [APIMANAGER-2102] - When a scope is added to a resource path in API creation wizard it does not get saved +
    • +
    • [APIMANAGER-2104] - Removing the doc type called 'API message format',which is not useful In Publisher documentation view +
    • +
    • [APIMANAGER-2105] - Cannot add callback URLs with 'localhost' +
    • +
    • [APIMANAGER-2108] - Access token generation based on grant types Authorization code/ Implicit fails for API-M 1.7.0 +
    • +
    • [APIMANAGER-2109] - SSO fails for work flow admin +
    • +
    • [APIMANAGER-2110] - SSO support is not available for tenants +
    • +
    • [APIMANAGER-2112] - SAML2 bearer token exchange with OAuth2 fails for APIM 1.7.0 +
    • +
    • [APIMANAGER-2114] - Typo in the apimgt/postgresql.sql script +
    • +
    • [APIMANAGER-2115] - NTLM grant type -Sample client is not working +
    • +
    • [APIMANAGER-2116] - Error when logging out of SSO enabled Management console +
    • +
    • [APIMANAGER-2118] - Error when loading web apps while SSO is enabled for management console + publisher store web apps +
    • +
    • [APIMANAGER-2119] - Key Validation fails for KeyValidatorClientType:WSClient (api-manager.xml) +
    • +
    • [APIMANAGER-2122] - Blocker for SSO configuration in a setup with Identity server as the key manager +
    • +
    • [APIMANAGER-2123] - APIs can only be editted once +
    • +
    • [APIMANAGER-2124] - API search by part of the name works only when the starting characters are given ( Store) +
    • +
    • [APIMANAGER-2125] - User Sign up(Store) workflow : Rejected/Pending users can generate access tokens +
    • +
    • [APIMANAGER-2127] - Add scopes button not functioning in edit page of APIPublisher +
    • +
    • [APIMANAGER-2128] - OPTIONS retrieves all methods regardless of those which are allowed for the resource path +
    • +
    • [APIMANAGER-2131] - APIManager samples [Youtube.,wikipedia] not working +
    • +
    • [APIMANAGER-2132] - Tenant wise theme uploading gets failed +
    • +
    • [APIMANAGER-2133] - Southbound stat publishing - Destination based usage tracking option no more available on publisher +
    • +
    • [APIMANAGER-2134] - Theme related error when the user store is shared +
    • +
    • [APIMANAGER-2138] - API Docs - Issues with updating /adding new documents +
    • +
    • [APIMANAGER-2139] - Issues with statistic display using Google Analytics +
    • +
    • [APIMANAGER-2140] - APIM version has not been updated in carbon.xml file +
    • +
    • [APIMANAGER-2143] - When an API is created with a "WSDL Endpoint" it does not show the link to the wsdl in store +
    • +
    • [APIMANAGER-2144] - Error when running API-Manager on Keymanager and Gateway profiles +
    • +
    • [APIMANAGER-2147] - Error when publishing to gateway in tenant mode in distributed setup +
    • +
    • [APIMANAGER-2148] - Error on first login attempt from a tenant in a distributed set up +
    • +
    • [APIMANAGER-2149] - [Intermittent] Get the below error when logging in to store as a tenant +
    • +
    • [APIMANAGER-2151] - [Intermittent] Error when logging in to publisher/store after logging into the other node (either publisher or store) +
    • +
    • [APIMANAGER-2152] - Error while publishing the first API of a tenant +
    • +
    • [APIMANAGER-2153] - APIs which are created as "visible to all tenants" are not visible to other tenants +
    • +
    • [APIMANAGER-2154] - NPE when accessing an API in tenant store with out logging in to it +
    • +
    • [APIMANAGER-2155] - Error on store for API changes on publisher +
    • +
    • [APIMANAGER-2162] - API Manager Consent page Deny Action doesn't work +
    • +
    • [APIMANAGER-2164] - Error while trying to validate access token when invoking APIs in tenant mode +
    • +
    • [APIMANAGER-2165] - When sending a multi-rooted JSON message as the payload, with an invalid token you get the payload back in the response converted to xml +
    • +
    • [APIMANAGER-2168] - Error when retrieving tasks to workflow admin when port offset takes a value other than 2 +
    • +
    • [APIMANAGER-2169] - Error when retrieving tasks to workflow admin when port offset takes a value other than 2 +
    • +
    • [APIMANAGER-2174] - Error on key manager start up +
    • +
    • [APIMANAGER-2182] - Exception when shutting down a node in a cluster +
    • +
    • [APIMANAGER-2187] - [Store] Statistics page redirecting to an error page in anonymous mode +
    • +
    • [APIMANAGER-2188] - Error on gateway node start up +
    • +
    • [APIMANAGER-2189] - Menu headers looks same as links in new 'publisher' theme +
    • +
    • [APIMANAGER-2192] - Error when invoking APIs in a cluster when fronted by an ELB +
    • +
    • [APIMANAGER-2193] - Function getPublishedAPIsByProvider ("api" module) returns only a maximum of 5 apis in its result +
    • +
    • [APIMANAGER-2195] - API Manager regenerate the same old token which is already time-out in the gateway +
    • +
    • [APIMANAGER-2198] - API Publisher Statistics - UI unresponsiveness on large amount of data +
    • +
    • [APIMANAGER-2199] - Table 'configDB.REG_LOG' doesn't exist when started with -Dsetup +
    • +
    • [APIMANAGER-2200] - [startup] Error in instantiating class : org.wso2.carbon.apimgt.usage.publisher.APIMgtFaultHandler +
    • +
    • [APIMANAGER-2201] - Error when logging in to publisher (when custom keystores are used instead of the default wso2carbon.jks) +
    • +
    • [APIMANAGER-2202] - Cannot access store in the distributed setup (when custom keystores are used instead of the default wso2carbon.jks) +
    • +
    • [APIMANAGER-2203] - Error setting up API-Manager with PostgreSQL +
    • +
    • [APIMANAGER-2205] - API status get updated even when an error occurs when publishing +
    • +
    • [APIMANAGER-2206] - [intermittent] ResourceNotFoundException +
    • +
    • [APIMANAGER-2207] - Error on first start up attempt of API-M after setting up with oracle +
    • +
    • [APIMANAGER-2208] - [Store] Token Validity period specified when 're-generating' Application token, does not have an effect +
    • +
    • [APIMANAGER-2209] - Different 'scope's set, when generating and regenerating Application tokens +
    • +
    • [APIMANAGER-2211] - Default application in store is missing in the oracle setup +
    • +
    • [APIMANAGER-2212] - SQL Exception when loading an API in the store (Oracle setup) +
    • +
    • [APIMANAGER-2213] - Cannot create applications in the store (Oracle set up) +
    • +
    • [APIMANAGER-2214] - [Usability] After subscribing to an API, page re-direction does not go to the exact subscribed application +
    • +
    • [APIMANAGER-2215] - [Store] Application Tokens does not re-generate after 2nd attempt +
    • +
    • [APIMANAGER-2216] - Destination Statistics table in publisher is not updated +
    • +
    • [APIMANAGER-2217] - NullPointerException on Publisher when loading statistics page +
    • +
    • [APIMANAGER-2219] - Tenant statistics mixup +
    • +
    • [APIMANAGER-2220] - java.lang.IllegalStateException: Trying to set the domain from 2 to 3 +
    • +
    • [APIMANAGER-2222] - Store statistics display per application is limited +
    • +
    • [APIMANAGER-2223] - [LoadTest] PersistenceException: Unable to handle new service addition. Service: wso2carbon-sts +
    • +
    • [APIMANAGER-2224] - Error when loading APIs in the store +
    • +
    • [APIMANAGER-2225] - Carbon server store key display issue +
    • +
    • [APIMANAGER-2228] - Error while updating wso2carbon-sts in STSDeploymentInterceptor +
    • +
    • [APIMANAGER-2229] - When there's a new keystore is used, it's looking for default wso2carbon.jks while the tenant is loaded first time in keymanager +
    • +
    • [APIMANAGER-2230] - Tenant loading issue on gateway (cluster setup) +
    • +
    • [APIMANAGER-2231] - [intermittent] [BAM] Published data does not get written in to database due to constraint violation exception +
    • +
    • [APIMANAGER-2232] - [Intermittent] API invocation count keeps continuously increasing in the cluster set up +
    • +
    • [APIMANAGER-2233] - Tenant user name format in publisher statistics pages +
    • +
    • [APIMANAGER-2234] - [Intermittent] API Usage by User graph is not updated initially +
    • +
    • [APIMANAGER-2236] - Cannot edit an API created with scope restrictions +
    • +
    • [APIMANAGER-2237] - Soap action is not set when logging into workflow admin +
    • +
    • [APIMANAGER-2242] - Gateway message tracing - EndPointURL=null +
    • +
    • [APIMANAGER-2243] - Message tracing does not function properly +
    • +
    • [APIMANAGER-2244] - "AM_API_DEFAULT_VERSION" table is not added in mysql script +
    • +
    • [APIMANAGER-2246] - Cannot add a 'scope' for an API +
    • +
    • [APIMANAGER-2247] - A not properly initiated thrift client will serve key validation requests,when the thrift client initialize during the key manager [thrift server down] +
    • +
    • [APIMANAGER-2248] - Message tracing on gateway does not occur when an API is invoked with an invalid key +
    • +
    • [APIMANAGER-2249] - [UI] Cannot specify advanced options for an endpoint +
    • +
    • [APIMANAGER-2251] - Cannot view the API-Dashboard of an API +
    • +
    • [APIMANAGER-2252] - API hot update fails on gateway +
    • +
    • [APIMANAGER-2255] - "There is no default version for the current API" +
    • +
    • [APIMANAGER-2256] - Issue with POST requests +
    • +
    • [APIMANAGER-2257] - Sends the request back as the response when response caching is enabled, and API moved back to created state +
    • +
    • [APIMANAGER-2258] - Cannot delete API with Subscriptions which is not the default version API +
    • +
    • [APIMANAGER-2260] - Remove JS alerts added to the Publisher/Store UIs +
    • +
    • [APIMANAGER-2262] - [Publisher] - UI issues +
    • +
    • [APIMANAGER-2264] - Cannot get API dashboard when using oracle as the database +
    • +
    • [APIMANAGER-2265] - Cannot view created APIs (Oracle setup) +
    • +
    • [APIMANAGER-2266] - "AM_API_DEFAULT_VERSION" table is not added to AM_DB Oracle script +
    • +
    • [APIMANAGER-2268] - 8 Tables are not getting created in AM_DB oracle script with -Dsetup +
    • +
    • [APIMANAGER-2271] - tiers.xml added values are shown incorrectly +
    • +
    • [APIMANAGER-2272] - NPE when invoking Token API with about 500 concurrency +
    • +
    • [APIMANAGER-2273] - Tier information mess up in API subscription page in Store, after denying certain tiers to some roles +
    • +
    • [APIMANAGER-2274] - Error message printed when statistics datasource is not properly configured +
    • +
    • [APIMANAGER-2275] - Cannot publish API statistics when BAM server is changed +
    • +
    • [APIMANAGER-2279] - Generic error message on publisher UI for several scenarios +
    • +
    • [APIMANAGER-2281] - Obsolete copyright in management UI +
    • +
    • [APIMANAGER-2282] - Publisher does not work in IE9 +
    • +
    • [APIMANAGER-2284] - Error when loading APIs containing documents with denied read permission for wso2.anonymous.role +
    • +
    • [APIMANAGER-2285] - HTTP 404 error returns when adding an application in IE (9 or 10) +
    • +
    • [APIMANAGER-2286] - Document read 'deny' permission of wso2.anonymous.role is applied to all documents of an API +
    • +
    • [APIMANAGER-2287] - Cannot add a tenant in MSSQL setup +
    • +
    • [APIMANAGER-2288] - AM_API_DEFAULT_VERSION table is missing in MSSQL script +
    • +
    • [APIMANAGER-2289] - Invalid column name 'TENANT_ID' error thrown continously when accessing carbon/idpmgt/idp-mgt-edit.jsp +
    • +
    • [APIMANAGER-2290] - Unable to regenerate access token +
    • +
    • [APIMANAGER-2291] - NPE thrown when generating tokens with external LDAP +
    • +
    • [APIMANAGER-2292] - Need migration scripts from AM 1.6.0 to 1.7.0 +
    • +
    • [APIMANAGER-2293] - Roles/Users created in primary store get created in other secondary stores as well +
    • +
    • [APIMANAGER-2294] - User mgt features are not updated with IS 5.0.0 +
    • +
    • [APIMANAGER-2295] - Cannot add identity providers +
    • +
    • [APIMANAGER-2296] - If you try to two documents with the same name for the same API there is no error/ warning message for the user +
    • +
    • [APIMANAGER-2297] - Tenant specific SSO does not work +
    • +
    • [APIMANAGER-2302] - Cannot generate tokens when AM_DB pointed to Oracle +
    • +
    • [APIMANAGER-2304] - [Intermittent] ORA-12516, TNS:listener could not find available handler with matching protocol stack +
    • +
    • [APIMANAGER-2306] - No response for MT API invocations - MT broken +
    • +
    • [APIMANAGER-2309] - Token re-generation fails when WebContextRoot is defined +
    • +
    • [APIMANAGER-2310] - Registry Browsing broken +
    • +
    • [APIMANAGER-2311] - Can log in to store and publisher from 2 different users in an SSO enabled set up when user permissions differ +
    • +
    • [APIMANAGER-2312] - Publisher login page loaded in an SSO enabled set up on attempts to log in with a user without publisher permission +
    • +
    • [APIMANAGER-2315] - Cannot create tenants in AM cluster setup [openLDAP, oracle] +
    • +
    • [APIMANAGER-2316] - Error when executing am_stats_analyzer in the oracle setup +
    • +
    • [APIMANAGER-2317] - Error when executing am_stats_analyzer in the oracle setup +
    • +
    • [APIMANAGER-2319] - AM_* tables are not created when running -Dsetup with MSSQL +
    • +
    • [APIMANAGER-2322] - [UI]APIM quick start dashbaord is wrong +
    • +
    • [APIMANAGER-2323] - Swagger console does not work in IE (10) +
    • +
    • [APIMANAGER-2325] - Document content is not shown in tenant's API store +
    • +
    • [APIMANAGER-2326] - Console URLs are not comprised with proxy ports, in cluster setup +
    • +
    • [APIMANAGER-2327] - Repetitive Error messages on server startup when APIUSageTracking enabled in store +
    • +
    • [APIMANAGER-2329] - [API Resource] Edit an existing API and provide a URL pattern not working +
    • +
    • [APIMANAGER-2330] - The same Access Token and User Token, for the Store user, gives a wrong Expiration time with the token API +
    • +
    • [APIMANAGER-2334] - Error when running Youtube API sample +
    • +
    • [APIMANAGER-2336] - 8th May 2014 pack reports syntax errors when executing MySQL db script +
    • +
    • [APIMANAGER-2337] - Sandbox keys are not generated for users who have capital letters in their user name +
    • +
    • [APIMANAGER-2338] - Please remove obsolete BPSWorkFlow sample from AM-1.7 distribution +
    • +
    • [APIMANAGER-2339] - [Intermittent] Issue with subscription confirmation pop up message +
    • +
    • [APIMANAGER-2340] - Store users can edit (change tiers) apps which are not ACTIVE +
    • +
    • [APIMANAGER-2344] - NPE thrown when pushing API to an external store +
    • +
    • [APIMANAGER-2346] - Error when starting API manager on gateway profile +
    • +
    • [APIMANAGER-2347] - Error when logging into workflow admin +
    • +
    • [APIMANAGER-2355] - Cannot assign a scope to an API resource [Oracle] +
    • +
    • [APIMANAGER-2358] - publisher/store is really slow to respond in cluster setup with Oracle +
    • +
    • [APIMANAGER-2359] - Subscriber role is not assinged to users created through user sign up work flow +
    • +
    • [APIMANAGER-2360] - Exceptions logged when approving/rejecting workflow tasks +
    • +
    • [APIMANAGER-2361] - Notification for pending approval is not displayed for Application Creation tasks on the Oracle setup +
    • +
    • [APIMANAGER-2362] - Invalid Subscription confirmation message shown +
    • +
    • [APIMANAGER-2364] - Application is added in "inactive" state even if the app creation workflow fails +
    • +
    • [APIMANAGER-2368] - Copy API feature does not work in IE +
    • +
    • [APIMANAGER-2369] - NPE when tenant unloading on gateway nodes +
    • +
    • [APIMANAGER-2370] - Auto subscribed new APIs can be invoked even if the subscription for the original API is not approved +
    • +
    • [APIMANAGER-2372] - Multiple tasks created for the same subscription +
    • +
    • [APIMANAGER-2373] - [Intermittent] 403: Resource forbidden error on gateway nodes when doing a load test +
    • +
    • [APIMANAGER-2374] - Sandbox application token generation not working for a subscriber having upper case username +
    • +
    • [APIMANAGER-2375] - Resource not found exception when tenant getting loaded on gateway node +
    • +
    • [APIMANAGER-2376] - Tenant loading fails in Gateway after restarting the server, due to 'Resource does not exist at path /_system/config/repository/transports/https/listener' +
    • +
    • [APIMANAGER-2378] - Cannot create APIs +
    • +
    • [APIMANAGER-2379] - [samples]Two statements failed in userPopulater.sql +
    • +
    • [APIMANAGER-2381] - Key validation fails when gateway caching is enabled (workflow related) +
    • +
    • [APIMANAGER-2382] - Sandbox Application-user token scope is stored as PRODUCTION in IDN_OAUTH2_ACCESS_TOKEN +
    • +
    • [APIMANAGER-2387] - Tenant API store loading when SSO is enabled +
    • +
    • [APIMANAGER-2391] - Visible to Role option is given as mandatory only when the API creaion time. Editing an existing API can be done without filling the Visible to Roles textbox +
    • +
    • [APIMANAGER-2393] - Publisher node trying to publish stats to the BAM +
    • +
    • [APIMANAGER-2394] - Too many INFO/ WARN logs when connecting registry mounts +
    • +
    • [APIMANAGER-2397] - [Intermittent] Resource not found exception at KeyManager node when tenant is logging in to Publisher node +
    • +
    • [APIMANAGER-2398] - Cannot publish to gateway while a mild load test happening (Connection timed out) +
    • +
    • [APIMANAGER-2399] - [intermittent] [loadtest] NPE when changing API status, while running a mild load test +
    • +
    • [APIMANAGER-2400] - [intermittent] ResourceNotFoundException on one tenat's resource while logged in to the store with some other tenant. +
    • +
    • [APIMANAGER-2402] - SQLException: ORA-02292 - After removing a scope restriction from a resource and saving the API +
    • +
    • [APIMANAGER-2403] - http 403 error response for POST requests sent inside a SOAP envelope but for GET requests response comes as a plain xml +
    • +
    • [APIMANAGER-2405] - Workflow admin multiple role log in issue (Intermittant) +
    • +
    • [APIMANAGER-2408] - when registry path is there as wsdl url test option will not work. +
    • +
    • [APIMANAGER-2409] - Cannot install APIM 1.7.0 Key manager feature in IS 5.0.0 +
    • +
    • [APIMANAGER-2411] - SOAPAction header is removed by the Gateway +
    • +
    • [APIMANAGER-2419] - Same token is regenerated when token encryption enabled +
    • +
    • [APIMANAGER-2420] - Subscription related usability issue +
    • +
    • [APIMANAGER-2421] - [Cluster] Session with the ELB breaks in 'store' when the redirection happens after creating a new application +
    • +
    • [APIMANAGER-2422] - [Publisher Stats] 'API Usage by User' displays super tenant information in tenant mode for All Statistics +
    • +
    • [APIMANAGER-2424] - Design Issue in <RevokeAPIURL> +
    • +
    • [APIMANAGER-2427] - [IS as KeyManager] http 500 error when regenerating APPLICATION tokens +
    • +
    • [APIMANAGER-2428] - Remove <GoogleAnalyticsTracking> from api-manager.xml +
    • +
    • [APIMANAGER-2430] - Error on gateway when invoking token API +
    • +
    • [APIMANAGER-2434] - CLONE - Add api fails with a registry error - during a volume test +
    • +
    • [APIMANAGER-2436] - When publishing to external API stores the context get appended with external tenants context in API console +
    • +
    • [APIMANAGER-2437] - Inappropriate error message when a tenant is not available in an external store +
    • +
    • [APIMANAGER-2438] - Cannot authenticate when publishing to external wso2 store in https mode +
    • +
    • [APIMANAGER-2439] - Error when publishing to external tenant store in the same node +
    • +
    • [APIMANAGER-2440] - HTTP 500 page when click in "Visit publisher store" due to an invalid url +
    • +
    • [APIMANAGER-2447] - Error thrown when the swagger doc permissions changed to restrict for registered users +
    • +
    • [APIMANAGER-2448] - Add documentation button not working in 21/05/14 nightly built AM 1.7.0 pack +
    • +
    • [APIMANAGER-2449] - Swagger doc update function not working +
    • +
    • [APIMANAGER-2451] - [Pulisher] Exception "Invalid number of parameters or their types" thrown when selecting 'Add' or 'New API' +
    • +
    • [APIMANAGER-2457] - Error when saving the API in Design stage +
    • +
    • [APIMANAGER-2458] - Cannot Create Copies of the Published API +
    • +
    • [APIMANAGER-2459] - Tenant Store-Anonymous view documents listing shwoing without considering doc permissions +
    • +
    • [APIMANAGER-2460] - Exceptions in store when you click on lifecycles for APIs in Design stage +
    • +
    • [APIMANAGER-2461] - Swagger UI not showing in tenant store -API Browse view +
    • +
    • [APIMANAGER-2462] - Resource path is not mandatory and neither checked or validated or generated when creating API +
    • +
    • [APIMANAGER-2463] - [Tenant mode]Doc permissions not propagating when the API visibility is 'Restricted by roles' +
    • +
    • [APIMANAGER-2465] - Workflow admin login fails when the key manager has a web context root +
    • +
    • [APIMANAGER-2466] - Store is taking a very long time to load when connected to OpenLDAP +
    • +
    • [APIMANAGER-2469] - Cannot remove a resource completely +
    • +
    • [APIMANAGER-2470] - Tenant contexts mixes up when two tenants/super admin doing operations on store +
    • +
    • [APIMANAGER-2471] - Cannot create a tenant +
    • +
    • [APIMANAGER-2472] - How to configure <RevokeAPIURL> in distributed setup +
    • +
    • [APIMANAGER-2473] - Application creation - UI issue +
    • +
    • [APIMANAGER-2478] - API_M doc links should be directed v1.7.0 docs +
    • +
    • [APIMANAGER-2479] - Cannot arrange the order of precedence of resources +
    • +
    • [APIMANAGER-1883] - Token generation fails with 'org.wso2.carbon.identity.oauth.tokenprocessor.EncryptionDecryptionPersistenceProcessor' TokenPersistenceProcessor +
    • +
    • [APIMANAGER-1890] - Resource base URI is shown in wadl and shouldn't we replace it with gateway parameters as we do for wsdls +
    • +
    • [APIMANAGER-1988] - No UI message showing when no subscriptions available for logged user +
    • +
    • [APIMANAGER-1999] - Make the API LC executor independent from G-Reg. +
    • +
    • [APIMANAGER-2042] - Provide the ability for the tenants to customise their Store theme +
    • +
    • [APIMANAGER-2097] - Add more help contexts for add/edit API form in publisher +
    • +
    • [APIMANAGER-2177] - Better to have direct filter options in publisher API page +
    • +
    • [APIMANAGER-2280] - Production and Sandbox URLs are not validated +
    • +
    • [APIMANAGER-2352] - make Store names configurable in a multi tenanted environment +
    • +
    • [APIMANAGER-2356] - Seperate configuration used to cache Token and API Resource cache in APIM gateway node +
    • +
    • [APIMANAGER-2404] - Add API resource sub-context based search to APIStore +
    • +
    • [APIMANAGER-2432] - Add more granular level permissions to API documents +
    • +
    • [APIMANAGER-2444] - [API publisher] Add ability to store roles against API Scopes +
    • +
    • [APIMANAGER-2450] - Change the way how swagger content retrieving in APIStore without using registry permlinks +
    • +
    + +

    Patches for previous release version

    +
      +
    • [APIMANAGER-1992] - API Usage By User report in WSO2 Api publisher does not work on Postgres +
    • +
    • [APIMANAGER-1997] - APIM 1.6.0 WSDL reference points to absolute GRed resource location in a mounted setup +
    • +
    • [APIMANAGER-2033] - HTTP endpoints get replaced with HTTPS gateway URL +
    • +
    • [APIMANAGER-2036] - If an API is deleted from External API Store, the publishing to External API Store again fails +
    • +
    • [APIMANAGER-2204] - User claims are not included in JWT token +
    • +
    • [APIMANAGER-2241] - ConcurrentModificationException at server startup +
    • +
    • [APIMANAGER-2254] - Fields under endpoint type are not rendered in IE 9 and below +
    • +
    + + + + + + + + +

    All resolved issues

    + + +

    Key Features of WSO2 API Manager

    +

    + Following is a categorization of the core features supported by WSO2 API Manager + based on the target user group. +

    +
      +
    • Create a Store of all Available APIs: +
        +
      • Graphical experience similar to Android Marketplace or Apple App Store.
      • +
      • Browse APIs by provider, tags or name.
      • +
      • Self-registration to developer community to subscribe to APIs.
      • +
      • Subscribe to APIs and manage subscriptions on per-application basis.
      • +
      • Subscriptions can be at different service tiers based on expected usage levels.
      • +
      • Role based access to API Store; manage public and private APIs.
      • +
      • Manage subscriptions at a per-developer level.
      • +
      • Browse API documentation, download helpers for easy consumption.
      • +
      • Comment on and rate APIs.
      • +
      • Forum for discussing API usage issues (Available soon in future version).
      • +
      • Try APIs directly on the store front.
      • +
      • Internationalization (i18n) support.
      • +
      + +
    • +
    • Publishing and Governing API Use: +
        + +
      • Publish APIs to external consumers and partners, as well as internal users.
      • +
      • Supports publishing multiple protocols including SOAP, REST, JSON and XML style services as APIs.
      • +
      • Manage API versions and deployment status by version.
      • +
      • Govern the API lifecycle (publish, deprecate, retire).
      • +
      • Attach documentation (files, external URLs) to APIs.
      • +
      • Apply Security policies to APIs (authentication, authorization).
      • +
      • Associate API available to system defined service tiers.
      • +
      • Provision and Manage API keys.
      • +
      • Track consumers per API.
      • +
      • One-click deployment to API Gateway for immediate publishing.
      • +
      + +
    • +
    • Route API Traffic: +
        + +
      • Supports API authentication with OAuth2.
      • +
      • Extremely high performance pass-through message routing with sub-millisecond latency.
      • +
      • Enforce rate limiting and throttling policies for APIs by consumer.
      • +
      • Horizontally scalable with easy deployment into cluster using proven routing infrastructure.
      • +
      • Scales to millions of developers/users.
      • +
      • Capture all statistics and push to pluggable analytics system.
      • +
      • Configure API routing policies with capabilities of WSO2 Enterprise Service Bus.
      • +
      • Powered by WSO2 Enterprise Service Bus.
      • +
      +
    • + +
    • Manage Developer Community: +
        +
      • Self-sign up for API consumption.
      • +
      • Manage user account including password reset.
      • +
      • Developer interaction with APIs via comments and ratings.
      • +
      • Support for developer communication via forums (Available soon in future version).
      • +
      • Powered by WSO2 Identity Server.
      • +
      +
    • + +
    • Govern Complete API Lifecycle: +
        +
      • Manage API lifecycle from cradle to grave: create, publish, block, deprecate and retire.
      • +
      • Publish both production and sandbox keys for APIs to enable easy developer testing.
      • +
      • Publish APIs to partner networks such as ProgrammableWeb (Available soon in future version).
      • +
      • Powered by WSO2 Governance Registry.
      • +
      +
    • + +
    • Monitor API Usage and Performance: +
        +
      • All API usage published to pluggable analytics framework.
      • +
      • Out of the box support for WSO2 Business Activity Monitor and Google Analytics.
      • +
      • View metrics by user, API and more.
      • +
      • Customized reporting via plugging reporting engines.
      • +
      • Monitor SLA compliance.
      • +
      • Powered by WSO2 Business Activity Monitor.
      • +
      +
    • + +
    • Pluggable, Extensible and Themeable: +
        +
      • All components are highly customizable thru styling, theming and open source code.
      • +
      • Storefront implemented with Jaggery (jaggeryjs.org) for easy customization.
      • +
      • Pluggable to third party analytics systems and billing systems (Available soon in future version).
      • +
      • Pluggable to existing user stores including via JDBC and LDAP.
      • +
      • Components usable separately - storefront can be used to front APIs gatewayed via third party gateways such as Intel Expressway Service Gateway.
      • +
      • Support for Single Sign On (SSO) using SAML 2.0 for easy integration with existing web apps
      • +
      +
    • + +
    • Easily Deployable in Enterprise Setting: +
        +
      • Role based access control for managing users and their authorization levels.
      • +
      • Store front can be deployed in DMZ for external access with Publisher inside the firewall for private control.
      • +
      • Different user stores for developer focused store-front and internal operations in publisher.
      • +
      • Integrates with enterprise identity systems including LDAP and Microsoft Active Directory.
      • +
      • Gateway can be deployed in DMZ with controlled access to WSO2 Identity Server (for authentication/authorization) and governance database behind firewall.
      • + +
      +
    • + +
    • Support for creating multi-tenanted APIs +
        +
      • Run a single instance and provide API Management to multiple customers
      • +
      • Share APIs between different departments in a large enterprise
      • +
      +
    • + +
    • Publishing and Governing API Use +
        +
      • Document an API using Swagger
      • +
      • Restrict API Access tokens to domains/IPs
      • +
      • Ability to block a subscription and restricting a complete application
      • +
      • Ability to revoke access tokens
      • +
      • Separate validity period configuration for Application Access Token
      • +
      • OAuth2 Authorization Code Grant Type Support
      • +
      • Configuring execution point of mediation extensions
      • +
      +
    • + +
    • Monitor API Usage and Performance +
        +
      • Improved dashboard for monitoring usage statistics (Filtering data for a date range, More visually appealing widgets)
      • +
      +
    • +
    + +

    Known Issues

    +

    + All the open issues pertaining to WSO2 API Manager are reported at the following + location: +

    + + +

    How You Can Contribute

    +

    + Mailing Lists +

    +

    + Join our mailing list and correspond with the developers directly. +

    + +

    + Reporting Issues +

    +

    + We encourage you to report issues, documentation faults and feature requests + regarding + WSO2 API Manager through the public API Manager + JIRA. You + can use the + Carbon JIRA + to report any + issues related to the Carbon base framework or associated Carbon components. +

    + +

    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 more details and to take advantage of this unique opportunity please + visit http://wso2.com/support. +

    +

    + To learn more about WSO2 API Manager and WSO2 support offerings please visit + http://wso2.com/products/api-manager. +

    + +

    + -- The WSO2 API Manager Team -- +

    +
    + + diff --git a/docs/xdoc/samples/advanced_mediation_samples.xml b/docs/xdoc/samples/advanced_mediation_samples.xml new file mode 100644 index 0000000000..b05911b840 --- /dev/null +++ b/docs/xdoc/samples/advanced_mediation_samples.xml @@ -0,0 +1,2071 @@ + + + + + + + + WSO2 ESB - Advanced Mediation Samples + + + +

    Running the Advanced Mediation samples with WSO2 Enterprise Service Bus +(ESB)

    + +

    Using scripts in mediation (Script Mediator) +

    + +

    The ESB Script Mediator is a ESB extension, and thus all prerequisites are +not bundled by default with the ESB distribution. Before you use some script +mediators you may need to manually add the required jar files to the ESB lib +directory, and optionally perform other installation tasks as may be required +by the individual scripting language. This is explained in the Samples Setup guide.

    + +

    Sample 350: Introduction to the script mediator using +js scripts

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <localEntry key="stockquoteScript" src="file:repository/samples/resources/script/stockquoteTransform.js"/>
    +
    +    <in>
    +        <!-- transform the custom quote request into a standard quote request expected by the service -->
    +        <script language="js" key="stockquoteScript" function="transformRequest"/>
    +        <send>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +        </send>
    +    </in>
    +    <out>
    +        <!-- transform the standard response back into the custom format the client expects -->
    +        <script language="js" key="stockquoteScript" function="transformResponse"/>
    +        <send/>
    +    </out>
    +</definitions> 
    +
    <x><![CDATA[
    +  function transformRequest(mc) {
    +     var symbol = mc.getPayloadXML()..*::Code.toString();
    +     mc.setPayloadXML(
    +        <m:getQuote xmlns:m="http://services.samples">
    +           <m:request>
    +              <m:symbol>{symbol}</m:symbol>
    +           </m:request>
    +        </m:getQuote>);
    +  }
    +
    +  function transformResponse(mc) {
    +     var symbol = mc.getPayloadXML()..*::symbol.toString();
    +     var price = mc.getPayloadXML()..*::last.toString();
    +     mc.setPayloadXML(
    +        <m:CheckPriceResponse xmlns:m="http://services.samples/xsd">
    +   <m:Code>{symbol}</m:Code>
    +   <m:Price>{price}</m:Price>
    +        </m:CheckPriceResponse>);
    +  }
    +]]></x>
    + +

    Objective: Introduction to the script mediators

    + +

    Prerequisites:

    + +

    Start the Synapse configuration numbered 350: i.e. wso2esb-samples -sn +350
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    This sample is similar to sample 8 but instead of using XSLT the +transformation is done with JavaScript and E4X. Note that the script source +loaded from a resource must be specified within a CDATA tag within an XML +element. The script used in this example has two functions, 'transformRequest' +and 'transformResponse', and the Synapse configuration uses the function +attribute to specify which function should be invoked. Use the stock quote +client to issue a custom quote client as follows.:

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dmode=customquote
    + +

    ESB uses the script mediator and the specified Javascript function to +convert the custom request to a standard quote request. Subsequently the +response received is transformed and sent back to the client.

    + +

    Sample 351: In-line script mediation with +JavaScript

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <in>
    +        <!-- transform the custom quote request into a standard quote requst expected by the service -->
    +        <script language="js"><![CDATA[
    +               var symbol = mc.getPayloadXML()..*::Code.toString();
    +               mc.setPayloadXML(
    +                  <m:getQuote xmlns:m="http://services.samples/xsd">
    +                     <m:request>
    +                        <m:symbol>{symbol}</m:symbol>
    +                     </m:request>
    +                  </m:getQuote>);
    +        ]]></script>
    +        <send>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +        </send>
    +    </in>
    +    <out>
    +        <!-- transform the standard response back into the custom format the client expects -->
    +        <script language="js"><![CDATA[
    +               var symbol = mc.getPayloadXML()..*::symbol.toString();
    +               var price = mc.getPayloadXML()..*::last.toString();
    +               mc.setPayloadXML(
    +                  <m:CheckPriceResponse xmlns:m="http://services.samples/xsd">
    +               <m:Code>{symbol}</m:Code>
    +               <m:Price>{price}</m:Price>
    +                  </m:CheckPriceResponse>);
    +            ]]></script>
    +        <send/>
    +    </out>
    +</definitions> 
    + +

    Objective: Introduction to in-line script mediation

    + +

    Prerequisites:

    + +

    Start the Synapse configuration numbered 351: i.e. wso2esb-samples -sn +351
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    This example is functionally equivalent to sample # 350 and sample # 8, and +demonstrates in-line script mediation in ESB. Use the stock quote client to +send a custom quote as in example # 350 to test this example.

    + +

    Sample 352: Accessing Synapse message context API +methods using scripting language

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <in>
    +       <!-- change the MessageContext into a response and set a response payload -->
    +       <script language="js"><![CDATA[
    +          mc.setTo(mc.getReplyTo());
    +          mc.setProperty("RESPONSE", "true");
    +          mc.setPayloadXML(
    +             <ns:getQuoteResponse xmlns:ns="http://services.samples/xsd">
    +                <ns:return>
    +                   <ns:last>99.9</ns:last>
    +                </ns:return>
    +             </ns:getQuoteResponse>);
    +       ]]></script>
    +    </in>
    +    <send/>
    +</definitions> 
    + +

    Objective: Accessing the Synapse APIs from scripting +languages

    + +

    Prerequisites:

    + +

    Start the Synapse configuration numbered 352: i.e. wso2esb-samples -sn +352
    +

    + +

    This example shows how an inline JavaScript mediator script could access the +Synapse message context API to set its 'To' EPR and to set a custom property to +mark it as a response. Execute the stock quote client, and you will receive the +response "99.9" as the last sale price as per the above script.

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/
    + ...
    +stockquote:
    +     [java] Standard :: Stock price = $99.9
    + +

    Sample 353: Using Ruby scripts for mediation

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <localEntry key="stockquoteScript" src="file:repository/samples/resources/script/stockquoteTransform.rb"/>
    +    <in>
    +        <!-- transform the custom quote request into a standard quote request expected by the service -->
    +        <script language="rb" key="stockquoteScript" function="transformRequest"/>
    +
    +        <!-- send message to real endpoint referenced by name "stockquote" and stop -->
    +        <send>
    +            <endpoint name="stockquote">
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +        </send>
    +    </in>
    +    <out>
    +        <!-- transform the standard response back into the custom format the client expects -->
    +        <script language="rb" key="stockquoteScript" function="transformResponse"/>
    +        <send/>
    +    </out>
    +</definitions> 
    +
    <x><![CDATA[
    +require 'rexml/document'
    +include REXML
    +
    +def transformRequest(mc)
    +   newRequest= Document.new '<m:getQuote xmlns:m="http://services.samples/xsd">'<<
    +      '<m:request><m:symbol></m:symbol></m:request></m:getQuote>'
    +   newRequest.root.elements[1].elements[1].text = mc.getPayloadXML().root.elements[1].get_text
    +   mc.setPayloadXML(newRequest)
    +end
    +
    +def transformResponse(mc)
    +   newResponse = Document.new '<m:CheckPriceResponse xmlns:m="http://services.samples/xsd"><m:Code>' <<
    +      '</m:Code><m:Price></m:Price></m:CheckPriceResponse>'
    +   newResponse.root.elements[1].text = mc.getPayloadXML().root.elements[1].elements[1].get_text
    +   newResponse.root.elements[2].text = mc.getPayloadXML().root.elements[1].elements[2].get_text
    +   mc.setPayloadXML(newResponse)
    +end
    +]]></x>
    + +

    Objective: Script mediators using Ruby

    + +

    Prerequisites:

    + +

    This sample uses Ruby so first setup support for this in ESB as described at +Configuring JRuby.

    + +

    Start the Synapse configuration numbered 353: i.e. wso2esb-samples -sn +353
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    This sample is functionally equivalent to sample # 350 (#351 and #8) but +instead uses a Ruby script using the JRuby interpreter. The script has two +functions, 'transformRequest' and 'transformResponse', and the Synapse +configuration specifies which function is to be invoked when used. Execute the +stock quote client to send a custom stock quote as per example #350 and check +the received stock quote response.

    + +

    Sample 354: Using In-lined Ruby scripts for +mediation

    + +
    +
    <!-- Using In-lined Ruby scripts for mediation -->
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <in>
    +        <script language="rb">
    +            <![CDATA[
    +                require 'rexml/document'
    +                include REXML
    +                newRequest= Document.new '<m:getQuote xmlns:m="http://services.samples/xsd"><m:request><m:symbol>...test...</m:symbol></m:request></m:getQuote>'
    +                newRequest.root.elements[1].elements[1].text = $mc.getPayloadXML().root.elements[1].get_text
    +                $mc.setPayloadXML(newRequest)
    +            ]]>
    +        </script>
    +        <send>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +        </send>
    +    </in>
    +    <out>
    +        <script language="rb">
    +            <![CDATA[
    +                require 'rexml/document'
    +                include REXML
    +                newResponse = Document.new '<m:CheckPriceResponse xmlns:m="http://services.samples/xsd"><m:Code></m:Code><m:Price></m:Price></m:CheckPriceResponse>'
    +                newResponse.root.elements[1].text = $mc.getPayloadXML().root.elements[1].elements[1].get_text
    +                newResponse.root.elements[2].text = $mc.getPayloadXML().root.elements[1].elements[2].get_text
    +                $mc.setPayloadXML(newResponse)
    +            ]]>
    +        </script>
    +        <send/>
    +    </out>
    +</definitions> 
    +
    + +

    Objective: Script mediators using Ruby(In-lined Ruby +Script)

    + +

    Prerequisites:

    + +

    This sample uses Ruby so first setup support for this in ESB as described at +Configuring JRuby.

    + +

    Start the Synapse configuration numbered 354: i.e. wso2esb-samples -sn +354
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    This sample is functionally equivalent to the sample #353.

    + +

    Runs the client with

    +
     ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dmode=customquote
    + +

    Database interactions in mediation (DBLookup / +DBReport)

    + +

    Following database mediators use Derby in a client/server configuration by +using the network server. Therefore, to proceed with the following samples, you +need a working Derby database server and you have to follow the steps in Sample Setup Guide before going +through the samples.

    + +

    Sample 360: Introduction to dblookup mediator

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="myFaultHandler">
    +        <makefault>
    +            <code value="tns:Receiver" xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +            <reason expression="get-property('ERROR_MESSAGE')"/>
    +        </makefault>
    +
    +        <property name="RESPONSE" value="true"/>
    +        <header name="To" expression="get-property('ReplyTo')"/>
    +        <send/>
    +        <drop/>
    +    </sequence>
    +
    +    <sequence name="main" onError="myFaultHandler">
    +        <in>
    +            <log level="custom">
    +                <property name="text"
    +                          value="** Looking up from the Database **"/>
    +            </log>
    +            <dblookup xmlns="http://ws.apache.org/ns/synapse">
    +                <connection>
    +                    <pool>
    +                        <driver>org.apache.derby.jdbc.ClientDriver</driver>
    +                        <url>jdbc:derby://localhost:1527/esbdb;create=false</url>
    +                        <user>esb</user>
    +                        <password>esb</password>
    +                    </pool>
    +                </connection>
    +                <statement>
    +                    <sql>select * from company where name =?</sql>
    +                    <parameter expression="//m0:getQuote/m0:request/m0:symbol"
    +                               xmlns:m0="http://services.samples/xsd" type="VARCHAR"/>
    +                    <result name="company_id" column="id"/>
    +                </statement>
    +            </dblookup>
    +
    +            <switch source="get-property('company_id')">
    +                <case regex="c1">
    +                    <log level="custom">
    +                        <property name="text"
    +                                  expression="fn:concat('Company ID - ',get-property('company_id'))"/>
    +                    </log>
    +                    <send>
    +                        <endpoint>
    +                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                        </endpoint>
    +                    </send>
    +                </case>
    +                <case regex="c2">
    +                    <log level="custom">
    +                        <property name="text"
    +                                  expression="fn:concat('Company ID - ',get-property('company_id'))"/>
    +                    </log>
    +                    <send>
    +                        <endpoint>
    +                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                        </endpoint>
    +                    </send>
    +                </case>
    +                <case regex="c3">
    +                    <log level="custom">
    +                        <property name="text"
    +                                  expression="fn:concat('Company ID - ',get-property('company_id'))"/>
    +                    </log>
    +                    <send>
    +                        <endpoint>
    +                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                        </endpoint>
    +                    </send>
    +                </case>
    +                <default>
    +                    <log level="custom">
    +                        <property name="text" value="** Unrecognized Company ID **"/>
    +                    </log>
    +                    <makefault>
    +                        <code value="tns:Receiver"
    +                              xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +                        <reason value="** Unrecognized Company ID **"/>
    +                    </makefault>
    +                    <property name="RESPONSE" value="true"/>
    +                    <header name="To" action="remove"/>
    +                    <send/>
    +                    <drop/>
    +                </default>
    +            </switch>
    +            <drop/>
    +        </in>
    +
    +        <out>
    +            <send/>
    +        </out>
    +
    +    </sequence>
    +
    +</definitions>
    + +

    Objective:Introduction to the dblookup mediator

    + +

    Prerequisites: Setting up Derby database as explained +above.

    + +

    Start the Synapse configuration numbered 360: i.e. wso2esb-samples -sn 360 +

    + +

    Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    This sample demonstrates simple database read operations through ESB. When a +message arrives at dblookup mediator, it opens a connection to the database and +executes the SQL query. The SQL query use '?' character for attributes that +will be filled at runtime. The parameters define how to calculate the value of +those attributes at runtime. In this sample a dblookup mediator has been used +to extract 'id' of the company from the company database using the symbol which +is evaluated using an xpath against the SOAP envelope. Then 'id' base switching +will be done by a switch mediator.

    + +

    When the IBM stock quote is requested,

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=IBM
    + +

    ESB console shows

    +
    INFO LogMediator text = ** Looking up from the Database **INFO LogMediator text = Company ID ? c1
    + +

    For the SUN stock quote,

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=SUN
    + +

    ESB console shows

    +
    INFO LogMediator text = ** Looking up from the Database **INFO LogMediator text = Company ID ? c2
    + +

    and for the MSFT stock quote,

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=MSFT
    +
    INFO LogMediator text = ** Looking up from the Database **
    INFO LogMediator text = Company ID ? c2
    + +

    For any other symbols, ESB console shows

    +
    INFO LogMediator text = ** Unrecognized Company ID **
    + +

    and the client gets a response which has following message.

    +
    ** Unrecognized Company ID **
    + +
    +
    + +

    Sample 361: Introduction to dbreport mediator

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="main">
    +        <in>
    +            <send>
    +                <endpoint>
    +                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                </endpoint>
    +            </send>
    +        </in>
    +
    +        <out>
    +            <log level="custom">
    +                <property name="text"
    +                          value="** Reporting to the Database **"/>
    +            </log>
    +            <dbreport xmlns="http://ws.apache.org/ns/synapse">
    +                <connection>
    +                    <pool>
    +                        <driver>org.apache.derby.jdbc.ClientDriver</driver>
    +                        <url>jdbc:derby://localhost:1527/esbdb;create=false</url>
    +                        <user>esb</user>
    +                        <password>esb</password>
    +                    </pool>
    +                </connection>
    +                <statement>
    +                    <sql>update company set price=? where name =?</sql>
    +                    <parameter expression="//m0:return/m1:last/child::text()"
    +                               xmlns:m0="http://services.samples" xmlns:m1="http://services.samples/xsd" type="DOUBLE"/>
    +                    <parameter expression="//m0:return/m1:symbol/child::text()"
    +                               xmlns:m0="http://services.samples" xmlns:m1="http://services.samples/xsd" type="VARCHAR"/>
    +                </statement>
    +            </dbreport>
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +</definitions>
    + +
    +

    Objective: Introduction to the dbreport mediator

    + +

    Prerequisites: Setting up Derby database as above.

    + +

    Start the Synapse configuration numbered 361: i.e. wso2esb-samples -sn 361 +

    + +

    Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    +
    + +

    This sample demonstrate simple database write operations. The dbreport +mediator writes (i.e. inserts one row) to a table using the message details. It +works the same as the dblookup mediator. In this sample , dbreport mediator is +used for updating the stock price of the company using the last quote value +which is calculated by evaluating an XPath against the response message. After +running this sample, user can check the company table using the Derby client +tool. It will show the inserted value by the dbreport mediator.

    + +

    Run the client using,

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=IBM
    + +

    and then execute the following query using database client tool against +synapsedb.

    +
    select price from company where name='IBM';
    + +

    It will show some value as follows.

    +
    96.39535981018865
    + +
    +
    + +

    Sample 362: Action of dbreport and dblookup mediators +together

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="main">
    +        <in>
    +            <send>
    +                <endpoint>
    +                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                </endpoint>
    +            </send>
    +        </in>
    +
    +        <out>
    +            <log level="custom">
    +                <property name="text"
    +                          value="** Reporting to the Database **"/>
    +            </log>
    +
    +            <dbreport xmlns="http://ws.apache.org/ns/synapse">
    +                <connection>
    +                    <pool>
    +                        <driver>org.apache.derby.jdbc.ClientDriver</driver>
    +                        <url>jdbc:derby://localhost:1527/esbdb;create=false</url>
    +                        <user>esb</user>
    +                        <password>esb</password>
    +                    </pool>
    +                </connection>
    +                <statement>
    +                    <sql>update company set price=? where name =?</sql>
    +                    <parameter expression="//m0:return/m1:last/child::text()"
    +                               xmlns:m0="http://services.samples" xmlns:m1="http://services.samples/xsd" type="DOUBLE"/>
    +                    <parameter expression="//m0:return/m1:symbol/child::text()"
    +                               xmlns:m0="http://services.samples" xmlns:m1="http://services.samples/xsd" type="VARCHAR"/>
    +                </statement>
    +            </dbreport>
    +            <log level="custom">
    +                <property name="text"
    +                          value="** Looking up from the Database **"/>
    +            </log>
    +            <dblookup xmlns="http://ws.apache.org/ns/synapse">
    +                <connection>
    +                    <pool>
    +                        <driver>org.apache.derby.jdbc.ClientDriver</driver>
    +                        <url>jdbc:derby://localhost:1527/esbdb;create=false</url>
    +                        <user>esb</user>
    +                        <password>esb</password>
    +                    </pool>
    +                </connection>
    +                <statement>
    +                    <sql>select * from company where name =?</sql>
    +                    <parameter expression="//m0:return/m1:symbol/child::text()"
    +                               xmlns:m0="http://services.samples" xmlns:m1="http://services.samples/xsd" type="VARCHAR"/>
    +                    <result name="stock_price" column="price"/>
    +                </statement>
    +            </dblookup>
    +            <log level="custom">
    +                <property name="text"
    +                          expression="fn:concat('Stock price - ',get-property('stock_price'))"/>
    +            </log>
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +</definitions>
    + +

    Objective: Demonstrate the use of dbreport and dblookup +mediators

    + +

    Prerequisites: Setting up Derby database as above.

    + +

    Start the Synapse configuration numbered 362: i.e. wso2esb-samples -sn 362 +

    + +

    Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    In this sample ,the dbreport mediator works the same as the above sample. It +updates the price for the given company using the response messages content. +Then the dblookup mediator reads the last updated value from the company +database and logs it.

    + +

    When running client,

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=IBM
    + +

    ESB console shows,

    +
    INFO LogMediator text = ** Reporting to the Database **

    ...

    INFO LogMediator text = ** Looking up from the Database **

    ...

    INFO LogMediator text = Stock price - 153.47886496064808
    + +

    Sample 363: Reusable database connection pools

    +
    <!-- Reusable database connection pool -->
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="myFaultHandler">
    +        <makefault>
    +            <code value="tns:Receiver" xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +            <reason expression="get-property('ERROR_MESSAGE')"/>
    +        </makefault>
    +
    +        <property name="RESPONSE" value="true"/>
    +        <header name="To" expression="get-property('ReplyTo')"/>
    +        <send/>
    +        <drop/>
    +    </sequence>
    +
    +    <sequence name="main" onError="myFaultHandler">
    +        <in>
    +            <log level="custom">
    +                <property name="text"
    +                          value="** Looking up from the Database **"/>
    +            </log>
    +            <dblookup>
    +                <connection>
    +                    <pool>
    +                        <dsName>lookupdb</dsName>
    +                        <icClass>com.sun.jndi.rmi.registry.RegistryContextFactory</icClass>
    +                        <url>rmi://localhost:2199</url>
    +                        <user>esb</user>
    +                        <password>esb</password>
    +                    </pool>
    +                </connection>
    +                <statement>
    +                    <sql>select * from company where name =?</sql>
    +                    <parameter expression="//m0:getQuote/m0:request/m0:symbol"
    +                               xmlns:m0="http://services.samples/xsd" type="VARCHAR"/>
    +                    <result name="company_id" column="id"/>
    +                </statement>
    +            </dblookup>
    +
    +            <switch source="get-property('company_id')">
    +                <case regex="c1">
    +                    <log level="custom">
    +                        <property name="text"
    +                                  expression="fn:concat('Company ID - ',get-property('company_id'))"/>
    +                    </log>
    +                    <send>
    +                        <endpoint>
    +                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                        </endpoint>
    +                    </send>
    +                </case>
    +                <case regex="c2">
    +                    <log level="custom">
    +                        <property name="text"
    +                                  expression="fn:concat('Company ID - ',get-property('company_id'))"/>
    +                    </log>
    +                    <send>
    +                        <endpoint>
    +                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                        </endpoint>
    +                    </send>
    +                </case>
    +                <case regex="c3">
    +                    <log level="custom">
    +                        <property name="text"
    +                                  expression="fn:concat('Company ID - ',get-property('company_id'))"/>
    +                    </log>
    +                    <send>
    +                        <endpoint>
    +                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                        </endpoint>
    +                    </send>
    +                </case>
    +                <default>
    +                    <log level="custom">
    +                        <property name="text" value="** Unrecognized Company ID **"/>
    +                    </log>
    +                    <makefault>
    +                        <code value="tns:Receiver"
    +                              xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +                        <reason value="** Unrecognized Company ID **"/>
    +                    </makefault>
    +                    <property name="RESPONSE" value="true"/>
    +                    <header name="To" action="remove"/>
    +                    <send/>
    +                    <drop/>
    +                </default>
    +            </switch>
    +            <drop/>
    +        </in>
    +
    +        <out>
    +            <log level="custom">
    +                <property name="text"
    +                          value="** Reporting to the Database **"/>
    +            </log>
    +            <dbreport>
    +                <connection>
    +                    <pool>
    +                        <dsName>reportdb</dsName>
    +                        <icClass>com.sun.jndi.rmi.registry.RegistryContextFactory</icClass>
    +                        <url>rmi://localhost:2199</url>
    +                        <user>esb</user>
    +                        <password>esb</password>
    +                    </pool>
    +                </connection>
    +                <statement>
    +                    <sql>update company set price=? where name =?</sql>
    +                    <parameter expression="//m0:return/m1:last/child::text()"
    +                               xmlns:m0="http://services.samples" xmlns:m1="http://services.samples/xsd" type="DOUBLE"/>
    +                    <parameter expression="//m0:return/m1:symbol/child::text()"
    +                               xmlns:m0="http://services.samples" xmlns:m1="http://services.samples/xsd" type="VARCHAR"/>
    +                </statement>
    +            </dbreport>
    +            <log level="custom">
    +                <property name="text"
    +                          value="** Looking up from the Database **"/>
    +            </log>
    +            <dblookup>
    +                <connection>
    +                    <pool>
    +                        <dsName>reportdb</dsName>
    +                        <icClass>com.sun.jndi.rmi.registry.RegistryContextFactory</icClass>
    +                        <url>rmi://localhost:2199</url>
    +                        <user>esb</user>
    +                        <password>esb</password>
    +                    </pool>
    +                </connection>
    +                <statement>
    +                    <sql>select * from company where name =?</sql>
    +                    <parameter expression="//m0:return/m1:symbol/child::text()"
    +                               xmlns:m0="http://services.samples" xmlns:m1="http://services.samples/xsd" type="VARCHAR"/>
    +                    <result name="stock_price" column="price"/>
    +                </statement>
    +            </dblookup>
    +            <log level="custom">
    +                <property name="text"
    +                          expression="fn:concat('Stock price - ',get-property('stock_price'))"/>
    +            </log>
    +            <send/>
    +
    +        </out>
    +
    +    </sequence>
    +
    +</definitions>
    + +

    Objective: Demonstrate the use of reusable database +connection pools

    + +

    Prerequisites: Setting up DataBase and DataSources +according to the sample setup guide.

    + +

    Start the Synapse configuration numbered 363: i.e. wso2esb-samples -sn +363

    + +

    Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    Runs the client as follows

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/
    + +

    Then the console output

    +
     INFO LogMediator text = ** Looking up from the Database **
    +    ...
    + INFO LogMediator text = Company ID - c1
    +    ...
    + INFO LogMediator text = ** Reporting to the Database **
    +    ...
    + INFO LogMediator text = ** Looking up from the Database **
    +    ...
    + INFO LogMediator text = Stock price - 183.3635460215262
    + + + +

    Sample 364: Executing database Stored Procedures

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse"
    +             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    +             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">
    +
    +    <sequence name="main">
    +        <in>
    +            <send>
    +                <endpoint>
    +                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                </endpoint>
    +            </send>
    +        </in>
    +
    +        <out>
    +            <log level="custom">
    +                <property name="text" value="** Reporting to the Database **"/>
    +            </log>
    +
    +            <dbreport>
    +                <connection>
    +                    <pool>
    +                        <driver>com.mysql.jdbc.Driver</driver>
    +                        <url>jdbc:mysql://localhost:3306/synapsedb</url>
    +                        <user>user</user>
    +                        <password>password</password>
    +                    </pool>
    +                </connection>
    +                <statement>
    +                    <sql>call updateCompany(?,?)</sql>
    +                    <parameter xmlns:m0="http://services.samples"
    +                               xmlns:m1="http://services.samples/xsd"
    +                               expression="//m0:return/m1:last/child::text()" type="DOUBLE"/>
    +                    <parameter xmlns:m0="http://services.samples"
    +                               xmlns:m1="http://services.samples/xsd"
    +                               expression="//m0:return/m1:symbol/child::text()" type="VARCHAR"/>
    +                </statement>
    +            </dbreport>
    +            <log level="custom">
    +                <property name="text" value="** Looking up from the Database **"/>
    +            </log>
    +            <dblookup>
    +                <connection>
    +                    <pool>
    +                        <driver>com.mysql.jdbc.Driver</driver>
    +                        <url>jdbc:mysql://localhost:3306/synapsedb</url>
    +                        <user>user</user>
    +                        <password>password</password>
    +                    </pool>
    +                </connection>
    +                <statement>
    +                    <sql>call getCompany(?)</sql>
    +                    <parameter xmlns:m0="http://services.samples"
    +                               xmlns:m1="http://services.samples/xsd"
    +                               expression="//m0:return/m1:symbol/child::text()" type="VARCHAR"/>
    +                    <result name="stock_prize" column="price"/>
    +                </statement>
    +            </dblookup>
    +            <log level="custom">
    +                <property name="text"
    +                          expression="fn:concat('Stock Prize - ',get-property('stock_prize'))"/>
    +            </log>
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +</definitions>
    + +

    Objective: Demonstrate the use of dblookup and dbreport mediators to execute a database Stored Procedures

    + +

    Prerequisites: Set up MySQL database server according to the sample setup guide.

    + +

    Start the Synapse configuration numbered 364: i.e. wso2esb-samples -sn +364

    + +

    Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    Runs the client as follows

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=IBM
    + +

    Then you will get the following console output

    +
    INFO LogMediator text = ** Looking up from the Database ** ...
    +INFO LogMediator text = Company ID - c1 ...
    +INFO LogMediator text = Stock price - 183.3635460215262
    +
    + + + + +

    + +

    Throttling messages (Throttle Mediator)

    + +

    Sample 370: Introduction to throttle mediator and +concurrency throttling

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <sequence name="main">
    +        <in>
    +            <throttle id="A">
    +                <policy>
    +                    <!-- define throttle policy -->
    +                    <wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
    +                                xmlns:throttle="http://www.wso2.org/products/wso2commons/throttle">
    +                        <throttle:ThrottleAssertion>
    +                            <throttle:MaximumConcurrentAccess>10</throttle:MaximumConcurrentAccess>
    +                        </throttle:ThrottleAssertion>
    +                    </wsp:Policy>
    +                </policy>
    +                <onAccept>
    +                    <log level="custom">
    +                        <property name="text" value="**Access Accept**"/>
    +                    </log>
    +                    <send>
    +                        <endpoint>
    +                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                        </endpoint>
    +                    </send>
    +                </onAccept>
    +                <onReject>
    +                    <log level="custom">
    +                        <property name="text" value="**Access Denied**"/>
    +                    </log>
    +                    <makefault>
    +                        <code value="tns:Receiver"
    +                              xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +                        <reason value="**Access Denied**"/>
    +                    </makefault>
    +                    <property name="RESPONSE" value="true"/>
    +                    <header name="To" action="remove"/>
    +                    <send/>
    +                    <drop/>
    +                </onReject>
    +            </throttle>
    +        </in>
    +        <out>
    +            <throttle id="A"/>
    +            <send/>
    +        </out>
    +    </sequence>
    +</definitions>
    + +

    Objective: Demonstrate the use of throttle mediator for +concurrency throttling

    + +

    Prerequisites:

    + +

    Deploy the SimpleStockQuoteService in sample Axis2 server and start it on +port 9000.

    + +

    Start ESB with the sample configuration 370 (i.e. wso2esb-samples -sn 370). +

    + +

    Above configuration specifies a throttle mediator inside the in mediator. +Therefore, all request messages directed to the main sequence will be subjected +to throttling. Throttle mediator has 'policy', 'onAccept' and 'onReject' tags +at top level. The 'policy' tag specifies the throttling policy for throttling +messages. This sample policy only contains a component called +"MaximumConcurrentAccess" .This indicates the maximum number of concurrent +requests that can pass through Synapse on a single unit of time. To test +concurrency throttling, it is required to send concurrent requests to Synapse. +If Synapse with above configuration, receives 20 requests concurrently from +clients, then approximately half of those will succeed while the others being +throttled. The client command to try this is as follows.

    +
    ant stockquote -Dsymbol=IBM -Dmode=quote -Daddurl=http://localhost:8280/
    + +

    Sample 371: Restricting requests based on policies +

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <sequence name="main">
    +        <in>
    +            <throttle id="A">
    +                <policy>
    +                    <!-- define throttle policy -->
    +                    <wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
    +                                xmlns:throttle="http://www.wso2.org/products/wso2commons/throttle">
    +                        <throttle:MediatorThrottleAssertion>
    +                            <wsp:Policy>
    +                                <throttle:ID throttle:type="IP">other</throttle:ID>
    +                                <wsp:Policy>
    +                                    <throttle:Control>
    +                                        <wsp:Policy>
    +                                            <throttle:MaximumCount>4</throttle:MaximumCount>
    +                                            <throttle:UnitTime>800000</throttle:UnitTime>
    +                                            <throttle:ProhibitTimePeriod wsp:Optional="true">1000
    +                                            </throttle:ProhibitTimePeriod>
    +                                        </wsp:Policy>
    +                                    </throttle:Control>
    +                                </wsp:Policy>
    +                            </wsp:Policy>
    +                            <wsp:Policy>
    +                                <throttle:ID throttle:type="IP">10.100.1.160 - 10.100.1.165</throttle:ID>
    +                                <wsp:Policy>
    +                                    <throttle:Control>
    +                                        <wsp:Policy>
    +                                            <throttle:MaximumCount>5</throttle:MaximumCount>
    +                                            <throttle:UnitTime>800000</throttle:UnitTime>
    +                                            <throttle:ProhibitTimePeriod wsp:Optional="true">100000
    +                                            </throttle:ProhibitTimePeriod>
    +                                        </wsp:Policy>
    +                                    </throttle:Control>
    +                                </wsp:Policy>
    +                            </wsp:Policy>
    +                        </throttle:MediatorThrottleAssertion>
    +                    </wsp:Policy>
    +                </policy>
    +                <onAccept>
    +                    <log level="custom">
    +                        <property name="text" value="**Access Accept**"/>
    +                    </log>
    +                    <send>
    +                        <endpoint>
    +                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                        </endpoint>
    +                    </send>
    +                </onAccept>
    +                <onReject>
    +                    <log level="custom">
    +                        <property name="text" value="**Access Denied**"/>
    +                    </log>
    +                    <makefault>
    +                        <code value="tns:Receiver"
    +                              xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +                        <reason value="**Access Denied**"/>
    +                    </makefault>
    +                    <property name="RESPONSE" value="true"/>
    +                    <header name="To" action="remove"/>
    +                    <send/>
    +                    <drop/>
    +                </onReject>
    +            </throttle>
    +        </in>
    +        <out>
    +            <throttle id="A"/>
    +            <send/>
    +        </out>
    +    </sequence>
    +</definitions>
    + +

    Objective: Demonstrate the use of throttle mediator for restricting +request counts

    + +

    Prerequisites:

    + +

    Deploy the SimpleStockQuoteService in sample Axis2 server and start it on +port 9000.

    + +

    Start ESB with the sample configuration 371 (i.e. wso2esb-samples -sn 371). +

    + +

    Above configuration specifies a throttle mediator inside the in mediator. +Therefore, all request messages directed to the main sequence will be subjected +to throttling. Throttle mediator has policy, onAccept and onReject tags at the +top level. Policy tag specifies the throttling policy to be applied for +messages. It contains some IP address ranges and the maximum number of messages +to be allowed for those ranges within a time period given in "UnitTime" tag. +"ProhibitTimePeriod" tag specifies the time period to prohibit further requests +after the received request count exceeds the specified time. Now run the client +5 times repetitively using the following command to see how throttling works. +

    +
    ant stockquote -Dsymbol=IBM -Dmode=quote -Daddurl=http://localhost:8280/
    + +

    For the first four requests you will get the quote prices for IBM as +follows.

    +
    [java] Standard :: Stock price = $177.20143371883802
    + +

    You will receive the following response for the fifth request.

    +
    [java] org.apache.axis2.AxisFault: **Access Denied**
    + +

    Maximum number of requests within 800000 milliseconds is specified as 4 for +any server (including localhost) other than the explicitly specified ones. +Therefore, our fifth request is denied by the throttle mediator. You can verify +this by looking at the ESB console.

    +
    [HttpServerWorker-1] INFO  LogMediator - text = **Access Accept**
    +[HttpServerWorker-2] INFO  LogMediator - text = **Access Accept**
    +[HttpServerWorker-3] INFO  LogMediator - text = **Access Accept**
    +[HttpServerWorker-4] INFO  LogMediator - text = **Access Accept**
    +[HttpServerWorker-5] INFO  LogMediator - text = **Access Denied** 
    + +

    Sample 372: Use of both concurrency throttling and +request rate based throttling

    +
    <!-- Use of both concurrency throttling and request rate based throttling -->
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <registry provider="org.wso2.carbon.mediation.registry.ESBRegistry">
    +        <!-- the root property of the simple URL registry helps resolve a resource URL as root + key -->
    +        <parameter name="root">file:repository/</parameter>
    +        <!-- all resources loaded from the URL registry would be cached for this number of milli seconds -->
    +        <parameter name="cachableDuration">150000</parameter>
    +    </registry>
    +
    +    <sequence name="onAcceptSequence">
    +        <log level="custom">
    +            <property name="text" value="**Access Accept**"/>
    +        </log>
    +        <send>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +        </send>
    +    </sequence>
    +    <sequence name="onRejectSequence" trace="enable">
    +        <log level="custom">
    +            <property name="text" value="**Access Denied**"/>
    +        </log>
    +        <makefault>
    +            <code value="tns:Receiver"
    +                  xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +            <reason value="**Access Denied**"/>
    +        </makefault>
    +        <property name="RESPONSE" value="true"/>
    +        <header name="To" action="remove"/>
    +        <send/>
    +        <drop/>
    +    </sequence>
    +    <proxy name="StockQuoteProxy">
    +        <target>
    +             <inSequence>
    +                <throttle onReject="onRejectSequence" onAccept="onAcceptSequence" id="A">
    +                    <policy key="repository/samples/resources/policy/throttle_policy.xml"/>
    +                </throttle>
    +            </inSequence>
    +            <outSequence>
    +                <throttle id="A"/>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +</definitions>
    + +
    +
    + +

    Objective: Use of both concurrency throttling and request rate based +throttling

    + +

    Prerequisites: Deploy the SimpleStockQuoteService in sample +Axis2 server and start it on port 9000.

    + +

    Start ESB with the sample configuration 372 (i.e. wso2esb-samples -sn 372). +

    + +

    Throttle policy is loaded from the ?throttle_policy.xml? .That policy +contains merging policy from sample 370 and 371. To check the functionality , +it is need to run load test.The all enabled request from the concurrency +throttling will be controlled by the access rate base throttling according to +the policy.

    + +

    Run the client as follows

    +
    ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy
    + +
    +

    You will get results same as sample 371.if you run the load test, results +will be different due to affect of concurrency throttling.

    +
    + +

    Extending the mediation in java (Class Mediator)

    + +

    Class mediator can be used to write your own custom mediation in Java and +you have access to the SynapseMessageContext and to the full Synapse API in +there. This is a useful extension mechanism within ESB to extend its +functionality. This class can contain fields for which you can assign values at +runtime through the configuration.

    + +

    Sample 380: Writing your own custom mediation in +Java

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="fault">
    +        <makefault>
    +            <code value="tns:Receiver" xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +            <reason value="Mediation failed."/>
    +        </makefault>
    +        <send/>
    +    </sequence>
    +
    +    <sequence name="main" onError="fault">
    +        <in>
    +            <send>
    +                <endpoint name="stockquote">
    +                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                </endpoint>
    +            </send>
    +        </in>
    +        <out>
    +            <class name="samples.mediators.DiscountQuoteMediator">
    +                <property name="discountFactor" value="10"/>
    +                <property name="bonusFor" value="5"/>
    +            </class>
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +</definitions>
    + +

    Objective: Demonstrate the use of Class mediator to extend the +mediation functionality

    + +

    Prerequisites:

    + +

    Make sure the synapse-samples-1.0.jar is in your class path (by default this +jar is placed in the lib directory when installing ESB).

    + +

    Start ESB with the sample configuration 380 (i.e. wso2esb-samples -sn 380) +

    + +

    Start the sample Axis2 server and deploy the SimpleStockQuoteService.

    + +

    In this configuration, ESB hands over the request message to the specified +endpoint, which sends it to the Axis2 server running on port 9000.

    + +

    But the response message is passed through the class mediator before sending +it back to the client. Two parameters named "discountFactor"

    + +

    and "bonusFor" are passed to the instance mediator implementation class +(i.e. samples.mediators.DiscountQuoteMediator) before each

    + +

    invocation. Code of the mediator implementation class is shown below.

    +
    package samples.mediators;
    +
    +import org.apache.synapse.MessageContext;
    +import org.apache.synapse.Mediator;
    +import org.apache.axiom.om.OMElement;
    +import org.apache.axiom.om.OMAbstractFactory;
    +import org.apache.axiom.om.OMFactory;
    +import org.apache.axiom.soap.SOAPFactory;
    +import org.apache.commons.logging.Log;
    +import org.apache.commons.logging.LogFactory;
    +
    +import javax.xml.namespace.QName;
    +
    +public class DiscountQuoteMediator implements Mediator {
    +
    +    private static final Log log = LogFactory.getLog(DiscountQuoteMediator.class);
    +
    +    private String discountFactor="10";
    +
    +    private String bonusFor="10";
    +
    +    private int bonusCount=0;
    +
    +    public DiscountQuoteMediator(){}
    +
    +    public boolean mediate(MessageContext mc) {
    +
    +        String price= mc.getEnvelope().getBody().getFirstElement().getFirstElement().
    +                getFirstChildWithName(new QName("http://services.samples/xsd","last")).getText();
    +
    +        //converting String properties into integers
    +        int discount=Integer.parseInt(discountFactor);
    +        int bonusNo=Integer.parseInt(bonusFor);
    +        double currentPrice=Double.parseDouble(price);
    +
    +        //discounting factor is deducted from current price form every response
    +        Double lastPrice = new Double(currentPrice - currentPrice * discount / 100);
    +
    +        //Special discount of 5% offers for the first responses as set in the bonusFor property
    +        if (bonusCount <= bonusNo) {
    +            lastPrice = new Double(lastPrice.doubleValue() - lastPrice.doubleValue() * 0.05);
    +            bonusCount++;
    +        }
    +
    +        String discountedPrice = lastPrice.toString();
    +
    +        mc.getEnvelope().getBody().getFirstElement().getFirstElement().getFirstChildWithName
    +                (new QName("http://services.samples/xsd","last")).setText(discountedPrice);
    +
    +        System.out.println("Quote value discounted.");
    +        System.out.println("Original price: " + price);
    +        System.out.println("Discounted price: " + discountedPrice);
    +
    +        return true;
    +    }
    +
    +    public String getType() {
    +        return null;
    +    }
    +
    +    public void setTraceState(int traceState) {
    +        traceState = 0;
    +    }
    +
    +    public int getTraceState() {
    +        return 0;
    +    }
    +
    +    public void setDiscountFactor(String discount) {
    +        discountFactor=discount;
    +    }
    +
    +    public String getDiscountFactor() {
    +        return discountFactor;
    +    }
    +
    +    public void setBonusFor(String bonus){
    +        bonusFor=bonus;
    +    }
    +
    +    public String getBonusFor(){
    +        return bonusFor;
    +    }
    +}
    + +

    All classes developed for class mediation should implement the Mediator +interface, which contains the mediate(...) method. mediate(...) method of the +above class is invoked for each response message mediated through the main +sequence, with the message context of the current message as the parameter. All +the details of the message including the SOAP headers, SOAP body and properties +of the context hierarchy can be accessed from the message context. In this +sample, the body of the message is retrieved and the discount percentage is +subtracted from the quote price. If the quote request number is less than the +number specified in the "bonusFor" property in the configuration, a special +discount is given.

    + +

    Now run the client using the following command.

    +
    ant stockquote -Dsymbol=IBM -Dmode=quote -Daddurl=http://localhost:8280
    + +

    You will see the below output in the client console with the discounted +quote value.

    +
    [java] Standard :: Stock price = $138.77458254967408
    + +

    Now check the console running Synapse. You will see the original value and +the discounted value for the requested quote as follows.

    +
    Quote value discounted.
    +Original price: 162.30945327447262
    +Discounted price: 138.77458254967408
    + + + +

    Sample 381: Class mediator to CBR binary message

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse"
    +             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    +             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">
    +
    +    <proxy name="JMSBinaryProxy" transports="jms">
    +        <target inSequence="BINARY_CBR_SEQ"/>
    +    </proxy>
    +
    +    <sequence name="BINARY_CBR_SEQ">
    +        <in>
    +            <log level="full"/>
    +            <property action="set" name="OUT_ONLY" value="true"/>
    +            <class name="samples.mediators.BinaryExtractMediator">
    +                <property name="offset" value="11"/>
    +                <property name="length" value="4"/>
    +                <property name="variableName" value="symbol"/>
    +                <property name="binaryEncoding" value="utf-8"/>
    +            </class>
    +            <log level="custom">
    +                <property name="symbol" expression="get-property('symbol')"/>
    +            </log>
    +            <switch source="get-property('symbol')">
    +                <case regex="GOOG">
    +                    <send>
    +                        <endpoint>
    +                            <address
    +                                    uri="jms:/dynamicTopics/mdd.GOOG?transport.jms.ConnectionFactoryJNDIName=TopicConnectionFactory&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&java.naming.provider.url=tcp://localhost:61616&transport.jms.DestinationType=topic"/>
    +                        </endpoint>
    +                    </send>
    +                </case>
    +                <case regex="MSFT">
    +                    <send>
    +                        <endpoint>
    +                            <address
    +                                    uri="jms:/dynamicTopics/mdd.MSFT?transport.jms.ConnectionFactoryJNDIName=TopicConnectionFactory&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&java.naming.provider.url=tcp://localhost:61616&transport.jms.DestinationType=topic"/>
    +                        </endpoint>
    +                    </send>
    +                </case>
    +                <default/>
    +            </switch>
    +        </in>
    +    </sequence>
    +
    +</definitions>
    + +

    Objective: Demonstrate on CBR a message with binary payload

    + +

    Prerequisites:

    + +

    Make sure the synapse-samples-1.0.jar is in your class path (by default this jar is placed in the lib directory when installing Synapse)

    + +

    +Configure JMS transport using ActiveMQ (refer Sample Configuration Guide) +

    + +

    Start ESB with the sample configuration 381 (i.e. wso2esb-samples -sn 381) +

    + +

    Start the sample Axis2 server and deploy the SimpleStockQuoteService.

    + +

    In this configuration, a proxy has configured to accept incoming JMS messages. JMS messages + contains a binary payload. User configure the offset, length, binary encoding of the text + literal that it need to use for CBR. And a variable name to set the decoded value as a property. + Configuration simply route the messages based on the text to different endpoints. +
    A JMS producer and two instances of a consumer used to demonstrate the CBR functionality.

    + +


    Now run the first consumer using the following command.

    +
    ant mddconsumer -Djms_topic=mdd.MSFT
    + +

    Now run the second consumer using the following command.

    +
    ant mddconsumer -Djms_topic=mdd.GOOG
    + +

    So, now both consumers are ready to listen the topic

    +

    Now run the market data producer to genenrate market data for symbol 'MSFT' using the following command.

    +
    ant mddproducer -Dsymbol=MSFT
    + +

    Now run the market data producer to genenrate market data for symbol 'GOOG' using the following command.

    +
    ant mddproducer -Dsymbol=GOOG
    + +

    You will see the below output in the client console(s) based on the symbol.

    +
    mddconsumer:
    +[java]  Market data recived for symbol : topic://mdd.MSFT
    +[java]  Market data recived for symbol : topic://mdd.MSFT
    +    
    + + +

    Evaluating XQuery for mediation (XQuery Mediator)

    + +

    Sample 390: Introduction to the XQuery mediator +

    +
      <!-- Introduction to the XQuery mediator -->
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <!-- the SimpleURLRegistry allows access to a URL based registry (e.g. file:/// or http://) -->
    +    <registry provider="org.wso2.esb.registry.ESBRegistry">
    +        <!-- the root property of the simple URL registry helps resolve a resource URL as root + key -->
    +        <parameter name="root">file:repository/samples/resources/</parameter>
    +        <!-- all resources loaded from the URL registry would be cached for this number of milli seconds -->
    +        <parameter name="cachableDuration">15000</parameter>
    +    </registry>
    +
    +    <localEntry key="xquery-key-req"
    +                src="file:repository/samples/resources/xquery/xquery_req.xq"/>
    +    <proxy name="StockQuoteProxy">
    +        <target>
    +            <inSequence>
    +                <xquery key="xquery-key-req">
    +                    <variable name="payload" type="ELEMENT"/>
    +                </xquery>
    +                <send>
    +                    <endpoint>
    +                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                    </endpoint>
    +                </send>
    +            </inSequence>
    +            <outSequence>
    +                <out>
    +                    <xquery key="xquery/xquery_res.xq">
    +                        <variable name="payload" type="ELEMENT"/>
    +                        <variable name="code" type="STRING"
    +                                  expression="self::node()//m0:return/m0:symbol/child::text()"
    +                                  xmlns:m0="http://services.samples/xsd"/>
    +                        <variable name="price" type="DOUBLE"
    +                                  expression="self::node()//m0:return/m0:last/child::text()"
    +                                  xmlns:m0="http://services.samples/xsd"/>
    +                    </xquery>
    +                    <send/>
    +                </out>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +</definitions> 
    + +

    This example uses the XQuery mediator to perform transformations. This +sample behaves the same as sample number 8 and the only difference is that this +sample uses XQuery instead of XSLT for transformation.

    + +

    Execute the custom quote client as 'ant stockquote -Dmode=customquote ...' +

    +
    ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy -Dmode=customquote 
    + +

    Sample 391: How to use data from an external XML +document with in XQuery

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <!-- the SimpleURLRegistry allows access to  URL based registry (e.g. file:/// or http://) -->
    +    <registry provider="org.wso2.carbon.mediation.registry.ESBRegistry">
    +        <!-- the root property of the simple URL registry helps resolve a resource URL as root + key -->
    +        <parameter name="root">file:repository/samples/resources/</parameter>
    +        <!-- all resources loaded from the URL registry would be cached for this number of milli seconds -->
    +        <parameter name="cachableDuration">15000</parameter>
    +    </registry>
    +
    +    <proxy name="StockQuoteProxy">
    +        <target>
    +            <inSequence>
    +                <send>
    +                    <endpoint>
    +                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                    </endpoint>
    +                </send>
    +            </inSequence>
    +            <outSequence>
    +                <out>
    +                    <xquery key="xquery/xquery_commisson.xq">
    +                        <variable name="payload" type="ELEMENT"></variable>
    +                            <variable name="commission" type="ELEMENT" key="misc/commission.xml"></variable>
    +                    </xquery>
    +                    <send/>
    +                </out>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +</definitions>
    + +

    Objective: Demonstrate the use of XQuery mediator to import external +XML documents to the XQuery engine

    + +

    Prerequisites:Deploy the SimpleStockQuoteService in sample +Axis2 server and start it on port 9000.

    + +

    Start ESB with the sample configuration 391 (i.e. wso2esb-samples -sn 391). +

    + +

    In this sample, data from commission.xml document is used inside XQUERY +document. The stock quote price from the response and commission from the +commission.xml document will be added and given as a new price .

    + +

    Invoke the client as follows.

    +
    ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy
    + +

    Splitting messages in to parts and process in parallel +(Iterate / Clone)

    + +

    Sample 400: Message splitting and aggregating the +responses

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <proxy name="SplitAggregateProxy">
    +        <target>
    +            <inSequence>
    +                <iterate expression="//m0:getQuote/m0:request" preservePayload="true"
    +                         attachPath="//m0:getQuote"
    +                         xmlns:m0="http://services.samples">
    +                    <target>
    +                        <sequence>
    +                            <send>
    +                                <endpoint>
    +                                    <address
    +                                        uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                                </endpoint>
    +                            </send>
    +                        </sequence>
    +                    </target>
    +                </iterate>
    +            </inSequence>
    +            <outSequence>
    +                <aggregate>
    +                    <onComplete expression="//m0:getQuoteResponse"
    +                                xmlns:m0="http://services.samples">
    +                        <send/>
    +                    </onComplete>
    +                </aggregate>
    +            </outSequence>
    +        </target>
    +    </proxy>
    +</definitions>
    + +

    Objective: Demonstrate the use of Iterate mediator to split the +messages in to parts and process them asynchronously and then aggregate the +responses coming in to ESB

    + +

    Prerequisites:Deploy the SimpleStockQuoteService in sample +Axis2 server and start it on port 9000.

    + +

    Start ESB with the sample configuration 400 (i.e. wso2esb-samples -sn 400). +

    + +

    In this sample, the message sent to ESB has embedded with a number of +elements of the same type in one message. When ESB received this message it +will iterate through those elements and then sent to the specified endpoint. +When all the responses appear in to ESB then those messages will be aggregated +to form the resultant response and sent back to the client.

    + +

    Invoke the client as follows.

    +
    ant stockquote -Daddurl=http://localhost:8280/services/SplitAggregateProxy -Ditr=4
    + +

    Caching the responses over the requests (Cache +Mediator)

    + +

    Cache mediator can be used to utilize the network bandwidth, to protect the +backend service from being loaded with the same type of requests like browser +refresh actions and also to speed up the execution of the web service. This +mediator should be used with sence, because it is not applicable for each and +every service (for example services with dynamic responses for a particular +release)

    + +

    Sample 420: Simple cache implemented on ESB for the +actual service

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <in>
    +        <cache timeout="20" scope="per-host" collector="false"
    +               hashGenerator="org.wso2.caching.digest.DOMHASHGenerator">
    +            <implementation type="memory" maxSize="100"/>
    +        </cache>
    +        <send>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +        </send>
    +    </in>
    +    <out>
    +        <cache collector="true"/>
    +        <send/>
    +    </out>
    +</definitions>
    + +

    Objective: Demonstrate the use of Cache mediator in order to cache +the response and use that cached response as the response for an identical xml +request

    + +

    Prerequisites:Deploy the SimpleStockQuoteService in sample +Axis2 server and start it on port 9000.

    + +

    Start ESB with the sample configuration 420 (i.e. wso2esb-samples -sn 420). +

    + +

    In this sample, the message sent to ESB is checked for an existing cached +response by calculating the hash value of the request. If there is a cache hit +in ESB then this request will not be forwarded to the actual service, rather +ESB respond to the client with the cached response. In case of a cache miss +that particular message will be forwarded to the actual service and cached that +response in the out path for the use of consecutive requests of the same type. +

    + +

    To observe this behaviour, invoke the client as follows.

    +
    ant stockquote -Dtrpurl=http://localhost:8280/
    + +

    You could notice that if you send more than one requests within 20 seconds +only the first request is forwarded to the actual service, and the rest of the +requests will be served by the cache inside ESB. You could observe this by +looking at the printed line of the axis2 server, as well as by observing a +constant rate as the response to the client instead of the random rate, which +changes by each and every 20 seconds.
    +

    + +

    Synchronize web service invocation with Callout mediator +

    + +

    The Callout mediator calls the given service URL with the request message +which is given by the source attribute, waits for the response and attaches the +received response to the destination which is given by the target attribute. +Both the source and the target can be a key or an XPath. In the case of the +source, this key refers to either a message context property or to a local +entry. For the target, this key refers to a message context property only.

    + +

    Sample 430: Simple Callout Mediator for synchronizing +web service invocation

    +
        <!-- Simple callout  mediator -->
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <callout serviceURL="http://localhost:9000/services/SimpleStockQuoteService"
    +             action="urn:getQuote">
    +        <source xmlns:s11="http://schemas.xmlsoap.org/soap/envelope/"
    +                xmlns:s12="http://www.w3.org/2003/05/soap-envelope"
    +                xpath="s11:Body/child::*[fn:position()=1] | s12:Body/child::*[fn:position()=1]"/>
    +        <target xmlns:s11="http://schemas.xmlsoap.org/soap/envelope/"
    +                xmlns:s12="http://www.w3.org/2003/05/soap-envelope"
    +                xpath="s11:Body/child::*[fn:position()=1] | s12:Body/child::*[fn:position()=1]"/>
    +    </callout>
    +    <property name="RESPONSE" value="true"/>
    +    <header name="To" action="remove"/>
    +    <send/>
    +    <drop/>
    +</definitions> 
    + +
    +

    Objective: Demonstrate the use of the Callout mediator for +the synchronized web service invocation

    +
    + +

    Prerequisites: Deploy the SimpleStockQuoteService in sample +Axis2 server and start it on port 9000.

    + +

    Start Synapse with the sample configuration 430 (i.e. wso2esb-samples -sn +430).

    + +

    In this sample, Callout mediator does the direct service invocation to the +StockQuoteService using the client request, get the response and set it as the +first child of the SOAP message body. Then using the send mediator, the message +is sent back to the client.

    + +

    Invoke the client as follows.

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/
    + + + +

    Mediating JSON Messages

    + +

    Supporting JSON messages in ESB

    + +

    Sample 440: Exposing a SOAP Service Over JSON

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse"
    +             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    +             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">
    +
    +    <proxy name="JSONProxy" transports="http https">
    +        <target>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +            <inSequence>
    +                <log level="full"/>
    +                <xslt key="in_transform"/>
    +                <property name="messageType" scope="axis2" value="text/xml"/>
    +            </inSequence>
    +            <outSequence>
    +                <log level="full"/>
    +                <xslt key="out_transform"/>
    +                <property name="messageType" scope="axis2" value="application/json"/>
    +                <send/>
    +            </outSequence>
    +        </target>
    +    </proxy>
    +
    +    <localEntry key="in_transform">
    +        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    +                        xmlns:fn="http://www.w3.org/2005/02/xpath-functions"
    +                        xmlns:m0="http://services.samples" version="2.0" exclude-result-prefixes="m0 fn">
    +            <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
    +            <xsl:template match="*">
    +                <xsl:element name="{local-name()}" namespace="http://services.samples">
    +                    <xsl:copy-of select="attribute::*"/>
    +                    <xsl:apply-templates/>
    +                </xsl:element>
    +            </xsl:template>
    +        </xsl:stylesheet>
    +    </localEntry>
    +
    +    <localEntry key="out_transform">
    +        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    +            <xsl:output method="xml" version="1.0" encoding="UTF-8"/>
    +            <xsl:template match="*">
    +                <xsl:element name="{local-name()}">
    +                    <xsl:apply-templates/>
    +                </xsl:element>
    +            </xsl:template>
    +        </xsl:stylesheet>
    +    </localEntry>
    +
    +</definitions>
    + +
    +

    Objective: Demonstrate the ability to switch between JSON and XML/SOAP content interchange formats

    +
    + +

    Prerequisites: Deploy the SimpleStockQuoteService in sample +Axis2 server and start it on port 9000.

    + +

    Start Synapse with the sample configuration 440 (i.e. wso2esb-samples -sn +440).

    +

    Setup Synapse and the sample Axis2 client for JSON (Refer Synapse Samples Setup Guide for details)

    + +

    Invoke the client as follows.

    +
    ant jsonclient -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/services/JSONProxy
    +

    JSON client will send a stockquote request to Synapse using the JSON content interchange format. + Synapse will trnasform it into a SOAP request and forward to the Axis2 server. + The SOAP response from the Axis2 server will be converted into a JSON message and sent back to + the JSON client.

    + +

    You may use a tool like TCPMon to monitor the JSON requests sent over the wire. A sample JSON request and response is shown below:

    +
    {"getQuote":{"request":{"symbol":"IBM"}}}
    +
    {"getQuoteResponse":{"return":{"change":3.853593376681722,"earnings":12.802850763714854,"high":67.92488310190126,"last":66.14619264746406,"lastTradeTimestamp":"Mon Aug 23 16:48:40 IST 2010","low":-66.04000424423522,"marketCap":-9334516.42324327,"name":"IBM Company","open":-64.61950137150009,"peRatio":-19.78600441437058,"percentageChange":5.411779328273005,"prevClose":71.2075112994578,"symbol":"IBM","volume":16842}}}
    +
    + +

    Modifying URLs with URL Rewrite Mediator

    +

    + URL rewrite mediator enables modifying URL values in the message. The input URL could be taken + from the 'To' header of the message or from a property available on the message. Once the input + URL is selected, a series of user defined rewrite rules will be evaluated on the message. Depending + on the outcome of these rule evaluations, the URL will be modified and set on the message. +

    +

    + URL rewrite mediator breaks the URL down to seven segments. +

    +
      +
    • Protocol
    • +
    • User information
    • +
    • Hostname
    • +
    • Port
    • +
    • Path
    • +
    • Query
    • +
    • Reference parameter
    • +
    +

    + Note that this breakdown is inline with the URI specification (RFC2396). URL rewrite mediator + enables rewriting each of the above segments separately and finally combining them to get + the final URL value. It also supports rewriting the entire URL string at once. +

    + +

    Sample 450: Introduction to the URL Rewrite Mediator

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="main">
    +        <in>
    +            <rewrite>
    +                <rewriterule>
    +                    <action type="replace" regex="soap" value="services" fragment="path"/>
    +                </rewriterule>
    +            </rewrite>
    +            <send/>
    +        </in>
    +        <out>
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +</definitions>
    +
    +

    + Objective: Demonstrate the basic functions of the URL rewrite mediator +

    +

    + Prerequisites: Deploy the SimpleStockQuoteService in sample Axis2 server + and start it on port 9000. +

    +

    + Start ESB with the sample configuration 450 (i.e. wso2esb-samples -sn 450). +

    +

    + Invoke the client as follows. +

    +
    ant stockquote -Dtrpurl=http://localhost:8280 -Daddurl=http://localhost:9000/soap/SimpleStockQuoteService
    +

    + Note that the address URL of the client request contains the context 'soap'. But in the + Axis2 server all the services are deployed under a context named 'services' by default. + ESB will rewrite the To header of the request by replacing the 'soap' context with 'services. + Hence the request will be delivered to the Axis2 server and the Axis2 client will receive a + valid response. +

    +
    + +

    Sample 451: Conditional URL Rewriting

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="main">
    +        <in>
    +            <rewrite>
    +                <rewriterule>
    +                    <condition>
    +                        <and>
    +                            <equal type="url" source="host" value="localhost"/>
    +                            <not>
    +                                <equal type="url" source="protocol" value="https"/>
    +                            </not>
    +                        </and>
    +                    </condition>
    +                    <action fragment="protocol" value="https"/>
    +                    <action fragment="port" value="9002"/>
    +                </rewriterule>
    +            </rewrite>
    +            <send/>
    +        </in>
    +        <out>
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +</definitions>
    +
    +

    + Objective: Demonstrate the ability of the URL rewrite mediator to evaluate conditions on messages and perform rewrites based on the results. +

    +

    + Prerequisites: Deploy the SimpleStockQuoteService in sample Axis2 server + and start it on port 9000. +

    +

    + Start ESB with the sample configuration 451 (i.e. wso2esb-samples -sn 451). +

    +

    + Invoke the Axis2 client and send some requests to ESB with different address URL values. + If the address URL value contains localhost as the hostname and https as the protocol + prefix, ESB will route the message as it is. But if the hostname is localhost and the + protocol is not https, Synapse will rewrite the URL by setting https as the protocol. The + port number will also be set to the HTTPS port of the Axis2 server. +

    +

    + The condition evaluation feature is provided by the Synapse evaluator framework. Currently + one can evaluate expressions on URL values, query parameters, transport headers, properties + and SOAP envelope content using this framework. Hence URL rewriting can be done based on + any of these aspects. +

    +
    + +

    Sample 452: Conditional URL Rewriting with Multiple Rules

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="main">
    +        <in>
    +            <property name="http.port" value="9000"/>
    +            <property name="https.port" value="9002"/>
    +            <rewrite>
    +                <rewriterule>
    +                    <action fragment="host" value="localhost"/>
    +                    <action fragment="path" type="prepend" value="/services"/>
    +                </rewriterule>
    +                <rewriterule>
    +                    <condition>
    +                        <equal type="url" source="protocol" value="http"/>
    +                    </condition>
    +                    <action fragment="port" xpath="get-property('http.port')"/>
    +                </rewriterule>
    +                <rewriterule>
    +                    <condition>
    +                        <equal type="url" source="protocol" value="https"/>
    +                    </condition>
    +                    <action fragment="port" xpath="get-property('https.port')"/>
    +                </rewriterule>
    +            </rewrite>
    +            <log level="full"/>
    +            <send/>
    +        </in>
    +        <out>
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +</definitions>
    +
    +

    + Objective: Demonstrate the ability of the URL rewrite mediator to perform rewrites based on multiple rules. +

    +

    + Prerequisites: Deploy the SimpleStockQuoteService in sample Axis2 server + and start it on port 9000. +

    +

    + Start ESB with the sample configuration 452 (i.e. wso2esb-samples -sn 452). +

    +

    + Invoke the Axis2 client as follows. +

    +
    ant stockquote -Dtrpurl=http://localhost:8280 -Daddurl=http://test.com/SimpleStockQuoteService
    +

    + The provided address URL does not contain a port number and the context. The URL rewrite + mediator will replace the hostname to be 'localhost' and add the context '/services' to the + path. Then it will add the appropriate port number to the URL by looking at the protocol + prefix. Ultimately the service request will be routed the sample Axis2 server and the + client will receive a valid response. Note that the Synapse configuration does not specify + any endpoints explicitly. So the messages are sent to the rewritten To header. +

    +

    + Another important aspect shown by this sample is the ability of the URL rewrite mediator to + obtain the necessary values by executing XPath expressions. The port numbers are calculated + by executing an XPath on the messages. +

    +
    + +

    Publishing Events to Topics Using the Event Mediator

    +

    + WSO2 ESB can be used as an event broker. It comes with a built-in eventing implementation and + a lightweight event broker based on Apache Qpid. You can use the ESB management console to + create event topics and clients can subscribe to those topics by sending WS-Eventing + subscription requests. The management console also allows creating static subscription. +

    +

    + WSO2 ESB is also equipped with an event mediator which can be used to publish messages to + predefined topics. With this mediator it is possible for a sequence or a proxy service to + directly publish a received request or a response to a topic as an event. +

    + +

    Sample 460: Introduction to Eventing and Event Mediator

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="main">
    +        <log/>
    +        <event topic="stockquote"/>
    +    </sequence>
    +
    +</definitions>
    +
    +

    + Objective: Demonstrate the usage of the event mediator to publish messages to event topics +

    +

    + Prerequisites: Deploy the SimpleStockQuoteService in sample Axis2 server + and start it on port 9000. +

    +

    + Start ESB with the sample configuration 460 (i.e. wso2esb-samples -sn 460). +

    +

    + Now sign in to the ESB management console can select 'Topics > Add' option from the 'Manage' + menu. Enter the name 'stockquote' for the topic and click 'Add Topic'. This will create an + event topic named 'stockquote' and you will be directed to the 'Topic Browser' tree view. The + newly created topic will be shown on the tree. Click on this topic and select the 'Subscribe' + option to create a static subscription. Enter the value 'http://localhost:9000/services/SimpleStockQuoteService' + in the 'Event Sink URL' field and click 'Subscribe'. +

    +

    + Now run the sample client as follows to send a request to the main sequence. +

    +
    ant stockquote -Dtrpurl=http://localhost:8280 -Dmode=placeorder
    +

    + The request will be published to the 'stockquote' topic by the event mediator and as a result + the subscriber (Axis2 server in this case) will receive a copy of the message. You will see a + log entry in the Axis2 server console indicating the receipt of the place order request. +

    +

    + Note that the provided ESB configuration does not explicitly specify the endpoint of the Axis2 + server. Also we don't set the actual EPR of the service on the request when sending the message + from the client either. Therefore the only reason that Axis2 receives the message is because + it is subscribed to the 'stockquote' event topic. +

    +
    + +

    Spring

    +

    Sample 470: How to initialize and use a Spring Bean as a Mediator

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse"
    +             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    +             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">
    +
    +    <registry provider="org.apache.synapse.registry.url.SimpleURLRegistry">
    +        <parameter name="root">file:repository/conf/sample/resources/</parameter>
    +        <parameter name="cachableDuration">15000</parameter>
    +    </registry>
    +
    +    <sequence name="main">
    +        <!--Setting the Spring Mediator and its Spring Beans xml file location -->
    +        <!--Note that springtest is the bean id used in springCustomLogger.xml -->
    +        <spring bean="springtest" key="spring/springCustomLogger.xml"/>
    +        <send/>
    +    </sequence>
    +
    +</definitions>
    + +

    springCustomLogger.xml file

    +
    +<?xml version="1.0" encoding="UTF-8"?>
    +<!DOCTYPE beans PUBLIC  "-//SPRING//DTD BEAN//EN"
    +    "http://www.springframework.org/dtd/spring-beans.dtd">
    +
    +<beans>
    +
    +   <bean id="springtest" class="samples.mediators.extensions.SpringCustomLogger" singleton="false">
    +	   <property name="userName"><value>"Synapse User"</value></property>
    +	   <property name="email"><value>"usr@synapse.org"</value></property>
    +   </bean>
    +
    +</beans>
    +
    + +
    +

    + Objective: Demonstrate How to initialize and use a SpringBean as a mediator +

    +

    + Prerequisites: Deploy the SimpleStockQuoteService in sample Axis2 server + and start it on port 9000. +

    +

    + Start ESB with the sample configuration 470 (i.e. wso2esb-samples -sn 470). +

    +

    + In this sample, the Spring Bean, SpringCustomLogger get initialized using + springCustomLogger.xml file and then it log the message Id. +

    +

    + Invoke the client as follows. +

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/
    +

    If you have enabled logging for the samples.mediators package you will see an + output similar to the following on the console:

    +
    +    2010-09-26 20:46:57,946 [-] [HttpServerWorker-1]  INFO SpringCustomLogger Starting Spring Meditor
    +    2010-09-26 20:46:57,946 [-] [HttpServerWorker-1]  INFO SpringCustomLogger Bean in Initialized with User:["Synapse User"]
    +    2010-09-26 20:46:57,946 [-] [HttpServerWorker-1]  INFO SpringCustomLogger E-MAIL:["usr@synapse.org"]
    +    2010-09-26 20:46:57,946 [-] [HttpServerWorker-1]  INFO SpringCustomLogger Massage Id:  urn:uuid:383FA8B27D7CC549D91285514217720
    +    2010-09-26 20:46:57,946 [-] [HttpServerWorker-1]  INFO SpringCustomLogger Logged....
    + +
    + + diff --git a/docs/xdoc/samples/endpoint_mediation_samples.xml b/docs/xdoc/samples/endpoint_mediation_samples.xml new file mode 100644 index 0000000000..305ba2ffa4 --- /dev/null +++ b/docs/xdoc/samples/endpoint_mediation_samples.xml @@ -0,0 +1,935 @@ + + + + + + + + WSO2 ESB - Endpoint samples + + + +

    Running the Endpoint Mediation samples with WSO2 Enterprise Service Bus (ESB)

    + +

    Sample 50: POX to SOAP conversion

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <!-- filtering of messages with XPath and regex matches -->
    +    <filter source="get-property('To')" regex=".*/StockQuote.*">
    +        <send>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService" format="soap11"/>
    +            </endpoint>
    +        </send>
    +        <drop/>
    +    </filter>
    +    <send/>
    +</definitions> 
    + +

    Objective: POX to SOAP conversion

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 50: i.e. wso2esb-samples -sn 50

    + +

    Start the Axis2 server and deploy the SimpleStockQuoteService if not +already done

    + +

    Execute the 'ant stockquote' specifying that the request should be a REST +request as follows:

    +
    ant stockquote -Dtrpurl=http://localhost:8280/services/StockQuote -Drest=true
    + +

    This example shows a http REST request (as shown below) being transformed +into a SOAP request and forwarded to the stock quote service.

    +
    POST /services/StockQuote HTTP/1.1
    +Content-Type: application/xml; charset=UTF-8;action="urn:getQuote";
    +SOAPAction: urn:getQuote
    +User-Agent: Axis2
    +Host: 127.0.0.1
    +Transfer-Encoding: chunked
    +
    +75
    +<m0:getQuote xmlns:m0="http://services.samples/xsd">
    +   <m0:request>
    +      <m0:symbol>IBM</m0:symbol>
    +   </m0:request>
    +</m0:getQuote>0
    + +

    Sample 51: MTOM and SwA optimizations and +request/response correlation

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <in>
    +        <filter source="get-property('Action')" regex="urn:uploadFileUsingMTOM">
    +            <property name="example" value="mtom"/>
    +            <send>
    +                <endpoint>
    +                    <address uri="http://localhost:9000/services/MTOMSwASampleService" optimize="mtom"/>
    +                </endpoint>
    +            </send>
    +        </filter>
    +        <filter source="get-property('Action')" regex="urn:uploadFileUsingSwA">
    +            <property name="example" value="swa"/>
    +            <send>
    +                <endpoint>
    +                    <address uri="http://localhost:9000/services/MTOMSwASampleService" optimize="swa"/>
    +                </endpoint>
    +            </send>
    +        </filter>
    +    </in>
    +    <out>
    +        <filter source="get-property('example')" regex="mtom">
    +            <property name="enableMTOM" value="true" scope="axis2"/>
    +        </filter>
    +        <filter source="get-property('example')" regex="swa">
    +            <property name="enableSwA" value="true" scope="axis2"/>
    +        </filter>
    +        <send/>
    +    </out>
    +</definitions>
    + +

    Objective: MTOM and SwA optimizations and request/response +correlation

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 51: i.e. wso2esb-samples -sn 51
    +Start the Axis2 server and deploy the MTOMSwASampleService if not already +done

    + +

    Execute the 'ant optimizeclient' specifying MTOM optimization as follows: +

    +
    ant optimizeclient -Dopt_mode=mtom
    + +

    The configuration now sets a local message context property, and forwards +the message to 'http://localhost:9000/services/MTOMSwASampleService' optimizing +binary content as MTOM. By sending this message through TCPMon you would be +able to see the actual message sent over the http transport if required. Thus +during response processing, by checking the local message property ESB could +identify the past information about the current message context, and uses +this knowledge to transform the response back to the client in the same +format as the original request.

    + +

    When the client executes successfully, it will upload a file containing +the ASF logo and receive its response back again and save it into a temporary +file.

    +
    [java] Sending file : ./../../repository/samples/resources/mtom/asf-logo.gif as MTOM
    +
    [java] Saved response to file : ./../../work/temp/sampleClient/mtom-49258.gif
    + +

    Next try SwA as:

    +
    ant optimizeclient -Dopt_mode=swa
    +
    [java] Sending file : ./../../repository/samples/resources/mtom/asf-logo.gif as SwA
    +[java] Saved response to file : ./../../work/temp/sampleClient/swa-47549.gif
    + +

    By using TCPMon and sending the message through it, one can inspect that +the requests and responses sent are indeed MTOM optimized or sent as http +attachments as follows:

    +
    POST http://localhost:9000/services/MTOMSwASampleService HTTP/1.1
    +Host: 127.0.0.1
    +SOAPAction: urn:uploadFileUsingMTOM
    +Content-Type: multipart/related; boundary=MIMEBoundaryurn_uuid_B94996494E1DD5F9B51177413845353; type="application/xop+xml";
    +start="<0.urn:uuid:B94996494E1DD5F9B51177413845354@apache.org>"; start-info="text/xml"; charset=UTF-8
    +Transfer-Encoding: chunked
    +Connection: Keep-Alive
    +User-Agent: Synapse-HttpComponents-NIO
    +
    +--MIMEBoundaryurn_uuid_B94996494E1DD5F9B51177413845353241
    +Content-Type: application/xop+xml; charset=UTF-8; type="text/xml"
    +Content-Transfer-Encoding: binary
    +Content-ID:
    +   <0.urn:uuid:B94996494E1DD5F9B51177413845354@apache.org>221b1
    +      <?xml version='1.0' encoding='UTF-8'?>
    +         <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    +            <soapenv:Body>
    +               <m0:uploadFileUsingMTOM xmlns:m0="http://www.apache-synapse.org/test">
    +                  <m0:request>
    +                     <m0:image>
    +                        <xop:Include href="cid:1.urn:uuid:78F94BC50B68D76FB41177413845003@apache.org" xmlns:xop="http://www.w3.org/2004/08/xop/include" />
    +                     </m0:image>
    +                  </m0:request>
    +               </m0:uploadFileUsingMTOM>
    +            </soapenv:Body>
    +         </soapenv:Envelope>
    +--MIMEBoundaryurn_uuid_B94996494E1DD5F9B51177413845353217
    +Content-Type: image/gif
    +Content-Transfer-Encoding: binary
    +Content-ID:
    +         <1.urn:uuid:78F94BC50B68D76FB41177413845003@apache.org>22800GIF89a... << binary content >>
    +
    POST http://localhost:9000/services/MTOMSwASampleService HTTP/1.1
    +Host: 127.0.0.1
    +SOAPAction: urn:uploadFileUsingSwA
    +Content-Type: multipart/related; boundary=MIMEBoundaryurn_uuid_B94996494E1DD5F9B51177414170491; type="text/xml";
    +start="<0.urn:uuid:B94996494E1DD5F9B51177414170492@apache.org>"; charset=UTF-8
    +Transfer-Encoding: chunked
    +Connection: Keep-Alive
    +User-Agent: Synapse-HttpComponents-NIO
    +
    +--MIMEBoundaryurn_uuid_B94996494E1DD5F9B51177414170491225
    +Content-Type: text/xml; charset=UTF-8
    +Content-Transfer-Encoding: 8bit
    +Content-ID:
    +   <0.urn:uuid:B94996494E1DD5F9B51177414170492@apache.org>22159
    +      <?xml version='1.0' encoding='UTF-8'?>
    +         <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    +            <soapenv:Body>
    +               <m0:uploadFileUsingSwA xmlns:m0="http://www.apache-synapse.org/test">
    +                  <m0:request>
    +                     <m0:imageId>urn:uuid:15FD2DA2584A32BF7C1177414169826</m0:imageId>
    +                  </m0:request>
    +               </m0:uploadFileUsingSwA>
    +            </soapenv:Body>
    +         </soapenv:Envelope>22--34MIMEBoundaryurn_uuid_B94996494E1DD5F9B511774141704912
    +17
    +Content-Type: image/gif
    +Content-Transfer-Encoding: binary
    +Content-ID:
    +         <urn:uuid:15FD2DA2584A32BF7C1177414169826>22800GIF89a... << binary content >>
    + +

    Sample 52: Session less load balancing between 3 +endpoints

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="main" onError="errorHandler">
    +        <in>
    +            <send>
    +                <endpoint>
    +                    <loadbalance>
    +                        <endpoint>
    +                            <address uri="http://localhost:9001/services/LBService1">
    +                                <enableAddressing/>
    +                                <suspendDurationOnFailure>60</suspendDurationOnFailure>
    +                            </address>
    +                        </endpoint>
    +                        <endpoint>
    +                            <address uri="http://localhost:9002/services/LBService1">
    +                                <enableAddressing/>
    +                                <suspendDurationOnFailure>60</suspendDurationOnFailure>
    +                            </address>
    +                        </endpoint>
    +                        <endpoint>
    +                            <address uri="http://localhost:9003/services/LBService1">
    +                                <enableAddressing/>
    +                                <suspendDurationOnFailure>60</suspendDurationOnFailure>
    +                            </address>
    +                        </endpoint>
    +                    </loadbalance>
    +                </endpoint>
    +            </send><drop/>
    +        </in>
    +
    +        <out>
    +            <!-- Send the messages where they have been sent (i.e. implicit To EPR) -->
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +    <sequence name="errorHandler">
    +
    +        <makefault>
    +            <code value="tns:Receiver" xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +            <reason value="COULDN'T SEND THE MESSAGE TO THE SERVER."/>
    +        </makefault>
    +
    +        <header name="To" action="remove"/>
    +        <property name="RESPONSE" value="true"/>
    +
    +        <send/>
    +    </sequence>
    +
    +</definitions>
    + +

    Objective: Demonstrate the simple load balancing among a set of +endpoints

    + +

    Prerequisites:

    + +

    Start ESB with sample configuration 52. (i.e. wso2esb-samples -sn 52)

    + +

    Deploy the LoadbalanceFailoverService by switching to <ESB installation +directory>/samples/axis2Server/src/LoadbalanceFailoverService directory +and running ant.

    + +

    Start three instances of sample Axis2 server on HTTP ports 9001, 9002 and +9003 and give some unique names to each server.

    + +

    Example commands to run sample Axis2 servers from the <ESB installation +directory>/samples/axis2Server directory in Linux are listed below:

    +
    ./axis2server.sh -http 9001 -https 9005 -name MyServer1
    +./axis2server.sh -http 9002 -https 9006 -name MyServer2
    +./axis2server.sh -http 9003 -https 9007 -name MyServer3
    + +

    Now we are done with setting up the environment for load balance sample. +Start the load balance and failover client using the following command:

    +
    ant loadbalancefailover -Di=100
    + +

    This client sends 100 requests to the LoadbalanceFailoverService through +ESB. ESB will distribute the load among the three endpoints mentioned in the +configuration in round-robin manner. LoadbalanceFailoverService appends the +name of the server to the response, so that client can determine which server +has processed the message. If you examine the console output of the client, +you can see that requests are processed by three servers as follows:

    +
    [java] Request: 1 ==> Response from server: MyServer1
    +[java] Request: 2 ==> Response from server: MyServer2
    +[java] Request: 3 ==> Response from server: MyServer3
    +[java] Request: 4 ==> Response from server: MyServer1
    +[java] Request: 5 ==> Response from server: MyServer2
    +[java] Request: 6 ==> Response from server: MyServer3
    +[java] Request: 7 ==> Response from server: MyServer1
    +...
    + +

    Now run the client without the -Di=100 parameter to send infinite +requests. While running the client shutdown the server named MyServer1. You +can observe that requests are only distributed among MyServer2 and MyServer3 +after shutting down MyServer1. Console output before and after shutting down +MyServer1 is listed below (MyServer1 was shutdown after request 63):

    +
    ...
    +[java] Request: 61 ==> Response from server: MyServer1
    +[java] Request: 62 ==> Response from server: MyServer2
    +[java] Request: 63 ==> Response from server: MyServer3
    +[java] Request: 64 ==> Response from server: MyServer2
    +[java] Request: 65 ==> Response from server: MyServer3
    +[java] Request: 66 ==> Response from server: MyServer2
    +[java] Request: 67 ==> Response from server: MyServer3
    +...
    + +

    Now restart MyServer1. You can observe that requests will be again sent to +all three servers roughly after 60 seconds. This is because we have specified +<suspendDurationOnFailure> as 60 seconds in the configuration. +Therefore, load balance endpoint will suspend any failed child endpoint only +for 60 seconds after detecting the failure.

    + +

    Sample 53: Failover sending among 3 endpoints

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="main" onError="errorHandler">
    +        <in>
    +            <send>
    +                <endpoint>
    +                    <failover>
    +                        <endpoint>
    +                            <address uri="http://localhost:9001/services/LBService1">
    +                                <enableAddressing/>
    +                                <suspendDurationOnFailure>60</suspendDurationOnFailure>
    +                            </address>
    +                        </endpoint>
    +                        <endpoint>
    +                            <address uri="http://localhost:9002/services/LBService1">
    +                                <enableAddressing/>
    +                                <suspendDurationOnFailure>60</suspendDurationOnFailure>
    +                            </address>
    +                        </endpoint>
    +                        <endpoint>
    +                            <address uri="http://localhost:9003/services/LBService1">
    +                                <enableAddressing/>
    +                                <suspendDurationOnFailure>60</suspendDurationOnFailure>
    +                            </address>
    +                        </endpoint>
    +                    </failover>
    +                </endpoint>
    +            </send><drop/>
    +        </in>
    +
    +        <out>
    +            <!-- Send the messages where they have been sent (i.e. implicit To EPR) -->
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +    <sequence name="errorHandler">
    +
    +        <makefault>
    +            <code value="tns:Receiver" xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +            <reason value="COULDN'T SEND THE MESSAGE TO THE SERVER."/>
    +        </makefault>
    +
    +        <header name="To" action="remove"/>
    +        <property name="RESPONSE" value="true"/>
    +
    +        <send/>
    +    </sequence>
    +
    +</definitions>
    + +

    Objective: Demonstrate the failover sending

    + +

    Prerequisites:

    + +

    Start ESB with sample configuration 53 (i.e. wso2esb-samples -sn 53)

    + +

    Deploy the LoadbalanceFailoverService and start three instances of sample +Axis2 server as mentioned in sample 52.

    + +

    Above configuration sends messages with the failover behavior. Initially +the server at port 9001 is treated as primary and other two are treated as +back ups. Messages are always directed only to the primary server. If the +primary server has failed, next listed server is selected as the primary. +Thus, messages are sent successfully as long as there is at least one active +server. To test this, run the loadbalancefailover client to send infinite +requests as follows:

    +
    ant loadbalancefailover
    + +

    You can see that all requests are processed by MyServer1. Now shutdown +MyServer1 and inspect the console output of the client. You will observe that +all subsequent requests are processed by MyServer2.

    + +

    The console output with MyServer1 shutdown after request 127 is listed +below:

    +
    ...
    +[java] Request: 125 ==> Response from server: MyServer1
    +[java] Request: 126 ==> Response from server: MyServer1
    +[java] Request: 127 ==> Response from server: MyServer1
    +[java] Request: 128 ==> Response from server: MyServer2
    +[java] Request: 129 ==> Response from server: MyServer2
    +[java] Request: 130 ==> Response from server: MyServer2
    +...
    + +

    You can keep on shutting down servers like this. Client will get a +response till you shutdown all listed servers. Once all servers are shutdown, +the error sequence is activated and a fault message is sent to the client as +follows.

    +
    [java] COULDN'T SEND THE MESSAGE TO THE SERVER.
    + +

    Once a server is detected as failed, it will be added to the active +servers list again after 60 seconds (specified in +<suspendDurationOnFailure> in the configuration). Therefore, if you +have restarted any of the stopped servers and have shutdown all other +servers, messages will be directed to the newly started server.

    + +

    Sample 54: Session affinity load balancing between 3 +endpoints

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="main" onError="errorHandler">
    +        <in>
    +            <send>
    +                <endpoint>
    +                    <!-- specify the session as the simple client session provided by Synapse for
    +                    testing purpose -->
    +                    <session type="simpleClientSession"/>
    +
    +                    <loadbalance>
    +                        <endpoint>
    +                            <address uri="http://localhost:9001/services/LBService1">
    +                                <enableAddressing/>
    +                            </address>
    +                        </endpoint>
    +                        <endpoint>
    +                            <address uri="http://localhost:9002/services/LBService1">
    +                                <enableAddressing/>
    +                            </address>
    +                        </endpoint>
    +                        <endpoint>
    +                            <address uri="http://localhost:9003/services/LBService1">
    +                                <enableAddressing/>
    +                            </address>
    +                        </endpoint>
    +                    </loadbalance>
    +                </endpoint>
    +            </send><drop/>
    +        </in>
    +
    +        <out>
    +            <!-- Send the messages where they have been sent (i.e. implicit To EPR) -->
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +    <sequence name="errorHandler">
    +
    +        <makefault>
    +            <code value="tns:Receiver" xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +            <reason value="COULDN'T SEND THE MESSAGE TO THE SERVER."/>
    +        </makefault>
    +
    +        <header name="To" action="remove"/>
    +        <property name="RESPONSE" value="true"/>
    +
    +        <send/>
    +    </sequence>
    +
    +</definitions>
    + +

    Objective: Demonstrate the load balancing with session affinity +using client initiated sessions

    + +

    Prerequisites:

    + +

    Start ESB with sample configuration 54 (i.e. wso2esb-samples -sn 54).

    + +

    Deploy the LoadbalanceFailoverService and start three instances of the +sample Axis2 server as in sample 52.

    + +

    Above configuration is same as the load balancing configuration in sample +52, except that the session type is specified as "simpleClientSession". This +is a client initiated session, which means that the client generates the +session identifier and sends it to with each request. In this sample session +type, client adds a SOAP header named ClientID containing the identifier of +the client. ESB binds this ID with a server on the first request and sends +all seccessive requests containing that ID to the same server. Now switch to +samples/axis2Client directory and run the client using the following command +to check this in action.

    +
    ant loadbalancefailover -Dmode=session
    + +

    In the session mode, client continuously sends requests with three diferent +client (session) IDs. One ID is selected among these three IDs for each +request randomly. Then client prints the session ID with the responded server +for each request. Client output for the first 10 requests are shown below. +

    +
    [java] Request: 1 Session number: 1 Response from server: MyServer3
    +[java] Request: 2 Session number: 2 Response from server: MyServer2
    +[java] Request: 3 Session number: 0 Response from server: MyServer1
    +[java] Request: 4 Session number: 2 Response from server: MyServer2
    +[java] Request: 5 Session number: 1 Response from server: MyServer3
    +[java] Request: 6 Session number: 2 Response from server: MyServer2
    +[java] Request: 7 Session number: 2 Response from server: MyServer2
    +[java] Request: 8 Session number: 1 Response from server: MyServer3
    +[java] Request: 9 Session number: 0 Response from server: MyServer1
    +[java] Request: 10 Session number: 0 Response from server: MyServer1
    +... 
    + +

    You can see that session number 0 is always directed to the server named +MyServer1. That means session number 0 is bound to MyServer1. Similarly +session 1 and 2 are bound to MyServer3 and MyServer2 respectively.

    + +

    Sample 55: Session affinity load balancing between fail +over endpoints

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="main" onError="errorHandler">
    +        <in>
    +            <send>
    +                <endpoint>
    +                    <!-- specify the session as the simple client session provided by Synapse for
    +                    testing purpose -->
    +                    <session type="simpleClientSession"/>
    +
    +                    <loadbalance>
    +                        <endpoint>
    +                            <failover>
    +                                <endpoint>
    +                                    <address uri="http://localhost:9001/services/LBService1">
    +                                        <enableAddressing/>
    +                                    </address>
    +                                </endpoint>
    +                                <endpoint>
    +                                    <address uri="http://localhost:9002/services/LBService1">
    +                                        <enableAddressing/>
    +                                    </address>
    +                                </endpoint>
    +                            </failover>
    +                        </endpoint>
    +                        <endpoint>
    +                            <failover>
    +                                <endpoint>
    +                                    <address uri="http://localhost:9003/services/LBService1">
    +                                        <enableAddressing/>
    +                                    </address>
    +                                </endpoint>
    +                                <endpoint>
    +                                    <address uri="http://localhost:9004/services/LBService1">
    +                                        <enableAddressing/>
    +                                    </address>
    +                                </endpoint>
    +                            </failover>
    +                        </endpoint>
    +                    </loadbalance>
    +                </endpoint>
    +            </send><drop/>
    +        </in>
    +
    +        <out>
    +            <!-- Send the messages where they have been sent (i.e. implicit To EPR) -->
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +    <sequence name="errorHandler">
    +
    +        <makefault>
    +            <code value="tns:Receiver" xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +            <reason value="COULDN'T SEND THE MESSAGE TO THE SERVER."/>
    +        </makefault>
    +
    +        <header name="To" action="remove"/>
    +        <property name="RESPONSE" value="true"/>
    +
    +        <send/>
    +    </sequence>
    +
    +</definitions>
    + +

    Objective: Demonstrate the session affinity based load balancing +with failover capability

    + +

    Prerequisites:

    + +

    Start ESB with sample configuration 55 (i.e. wso2esb-samples -sn 55).

    + +

    Deploy the LoadbalanceFailoverService and start four sample Axis2 servers +on http ports 9001, 9002, 9003 and 9004 respectively (make sure to specify +unconflicting https ports).

    + +

    This configuration also uses "simpleClientSession" to bind sessions as in +the previous sample. But failover endpoints are specified as the child +endpoints of the load balance endpoint. Therefore sessions are bound to the +failover endpoints. Session information has to be replicated among the +servers listed under each failover endpoint using some clustering mechanism. +Therefore, if one endpoint bound to a session failed, successive requests for +that session will be directed to the next endpoint in that failover group. +Run the client using the following command to observe this behaviour.

    +
    ant loadbalancefailover -Dmode=session
    + +

    You can see a client output as shown below.

    +
    ...
    +[java] Request: 222 Session number: 0 Response from server: MyServer1
    +[java] Request: 223 Session number: 0 Response from server: MyServer1
    +[java] Request: 224 Session number: 1 Response from server: MyServer1
    +[java] Request: 225 Session number: 2 Response from server: MyServer3
    +[java] Request: 226 Session number: 0 Response from server: MyServer1
    +[java] Request: 227 Session number: 1 Response from server: MyServer1
    +[java] Request: 228 Session number: 2 Response from server: MyServer3
    +[java] Request: 229 Session number: 1 Response from server: MyServer1
    +[java] Request: 230 Session number: 1 Response from server: MyServer1
    +[java] Request: 231 Session number: 2 Response from server: MyServer3
    +...
    + +

    Note that session 0 is always directed to MyServer1 and session 1 is +directed to MyServer3. No requests are directed to MyServer2 and MyServer4 as +they are kept as backups by failover endpoints. Now shutdown the server named +MyServer1 while running the sample. You will observe that all successive +requests for session 0 is now directed to MyServer2, which is the backup +server for MyServer1's group. This is shown below, where MyServer1 was +shutdown after the request 534.

    +
    ...
    +[java] Request: 529 Session number: 2 Response from server: MyServer3
    +[java] Request: 530 Session number: 1 Response from server: MyServer1
    +[java] Request: 531 Session number: 0 Response from server: MyServer1
    +[java] Request: 532 Session number: 1 Response from server: MyServer1
    +[java] Request: 533 Session number: 1 Response from server: MyServer1
    +[java] Request: 534 Session number: 1 Response from server: MyServer1
    +[java] Request: 535 Session number: 0 Response from server: MyServer2
    +[java] Request: 536 Session number: 0 Response from server: MyServer2
    +[java] Request: 537 Session number: 0 Response from server: MyServer2
    +[java] Request: 538 Session number: 2 Response from server: MyServer3
    +[java] Request: 539 Session number: 0 Response from server: MyServer2
    +...
    + +

    Sample 56: WSDL endpoint

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="main">
    +        <in>
    +            <send>
    +                <!-- get epr from the given wsdl -->
    +                <endpoint>
    +                    <wsdl uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl" service="SimpleStockQuoteService" port="SimpleStockQuoteServiceSOAP11port_http"/>
    +                </endpoint>
    +            </send>
    +        </in>
    +
    +        <out>
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +</definitions>
    + +

    Objective: Demonstrate the use of WSDL endpoints

    + +

    Prerequisites:

    + +

    Start the Synapse configuration numbered 56 (i.e. wso2esb-samples -sn 56). +

    + +

    Deploy the SimpleStockQuoteService and start the sample Axis2 server.

    + +

    This sample uses a WSDL endpoint inside the send mediator. WSDL endpoints +can extract endpoint's address from the given WSDL. As WSDL documents can +have many services and many ports inside each service, the service and port +of the required endpoint has to be specified. As with address endpoints, QoS +parameters for the endpoint can be specified inline in the configuration. An +excerpt taken from the sample_proxy_1.wsdl containing the specified service +and port is listed below.

    +
    <wsdl:service name="SimpleStockQuoteService">
    +    <wsdl:port name="SimpleStockQuoteServiceSOAP11port_http"
    +               binding="axis2:SimpleStockQuoteServiceSOAP11Binding">
    +        <soap:address location="http://localhost:9000/services/SimpleStockQuoteService"/>
    +    </wsdl:port>
    +    <wsdl:port name="SimpleStockQuoteServiceSOAP12port_http"
    +               binding="axis2:SimpleStockQuoteServiceSOAP12Binding">
    +        <soap12:address location="http://localhost:9000/services/SimpleStockQuoteService"/>
    +    </wsdl:port>
    +</wsdl:service>
    + +

    Specified service and port refers to the endpoint address +"http://localhost:9000/services/SimpleStockQuoteService" according to the above +WSDL. Now run the client using the following command.

    +
    ant stockquote -Dsymbol=IBM -Dmode=quote -Daddurl=http://localhost:8280
    + +

    Client will print the quote price for IBM received from the server running +on port 9000. Observe the Axis2 console and the ESB console to verify this +behavior.

    +

    +Sample 57: Dynamic load balancing between 3 nodes

    +
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="main" onError="errorHandler">
    +        <in>
    +            <send>
    +                <endpoint name="dynamicLB">
    +                    <dynamicLoadbalance failover="true"
    +                                           algorithm="org.apache.synapse.endpoints.algorithms.RoundRobin">
    +                        <membershipHandler
    +                                class="org.apache.synapse.core.axis2.Axis2LoadBalanceMembershipHandler">
    +                            <property name="applicationDomain" value="apache.axis2.application.domain"/>
    +                        </membershipHandler>
    +                    </dynamicLoadbalance>
    +                </endpoint>
    +            </send>
    +            <drop/>
    +        </in>
    +
    +        <out>
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +    <sequence name="errorHandler">
    +        <makefault response="true">
    +            <code value="tns:Receiver" xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +            <reason value="COULDN'T SEND THE MESSAGE TO THE SERVER."/>
    +        </makefault>
    +        <send/>
    +    </sequence>
    +
    +</definitions>
    +
    +

    +Objective: Demonstrate the simple dynamic load balancing among a set of nodes

    +

    +Prerequisites:

    +

    + Enable clustering and group management in the <ESB installation directory>/ repository/conf/axis2.xml + file. This can be done by setting the "enable" attribute of the "cluster" and + "groupManagement" elements. Also provide the IP address of you machine as the values of the + "mcastBindAddress" and "localMemberHost" parameters. +

    +

    Start ESB with sample configuration 57. (i.e. wso2esb-samples -sn 57)

    +

    + Deploy the LoadbalanceFailoverService by switching to <Synapse installation directory>/samples/axis2Server/src/LoadbalanceFailoverService + directory and running ant. +

    +

    + Enable clustering in the <Synapse installation directory>/samples/axis2Server/ repository/conf/axis2.xml + file. This can be done by setting the "enable" attribute of the "cluster" + element. Also provide the IP address of you machine as the values of the "mcastBindAddress" + and "localMemberHost" parameters. Make sure that the "applicationDomain" of the membershipHandler is + the same as the domain name specified in the axis2.xml files of the Axis2 servers. Then Start three + instances of sample Axis2 server on HTTP ports 9001, 9002 and 9003 and give some unique names to each + server. +

    +

    Example commands to run sample Axis2 servers from the <Synapse installation directory>/samples/axis2Server directory in Linux are listed below:

    +
    ./axis2server.sh -http 9001 -https 9005 -name MyServer1
    +./axis2server.sh -http 9002 -https 9006 -name MyServer2
    +./axis2server.sh -http 9003 -https 9007 -name MyServer3
    +

    Now we are done with setting up the environment for load balance sample. Start the load balance and failover client using the following command:

    +
    ant loadbalancefailover -Di=100
    +

    This client sends 100 requests to the LoadbalanceFailoverService through Synapse. Synapse will distribute the load among the three nodes mentioned in the configuration in a round-robin manner. LoadbalanceFailoverService appends the name of the server to the response, so that client can determine which server has processed the message. If you examine the console output of the client, you can see that requests are processed by three servers as follows:

    +
    [java] Request: 1 ==> Response from server: MyServer1
    +[java] Request: 2 ==> Response from server: MyServer2
    +[java] Request: 3 ==> Response from server: MyServer3
    +[java] Request: 4 ==> Response from server: MyServer1
    +[java] Request: 5 ==> Response from server: MyServer2
    +[java] Request: 6 ==> Response from server: MyServer3
    +[java] Request: 7 ==> Response from server: MyServer1
    +...
    +

    Now run the client without the -Di=100 parameter, i.e. ant loadbalancefailover, to send infinite requests. While running the client shutdown the server named MyServer1. You can observe that requests are only distributed among MyServer2 and MyServer3 after shutting down MyServer1. Console output before and after shutting down MyServer1 is listed below (MyServer1 was shutdown after request 63):

    +
    ...
    +[java] Request: 61 ==> Response from server: MyServer1
    +[java] Request: 62 ==> Response from server: MyServer2
    +[java] Request: 63 ==> Response from server: MyServer3
    +[java] Request: 64 ==> Response from server: MyServer2
    +[java] Request: 65 ==> Response from server: MyServer3
    +[java] Request: 66 ==> Response from server: MyServer2
    +[java] Request: 67 ==> Response from server: MyServer3
    +...
    +

    Now restart MyServer1. You can observe that requests will be again sent to all three servers.

    +

    +Sample 58: Static load balancing between 3 nodes

    +
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="main" onError="errorHandler">
    +        <in>
    +            <send>
    +                <endpoint>
    +                    <loadbalance failover="true">
    +                        <member hostName="127.0.0.1" httpPort="9001" httpsPort="9005"/>
    +                        <member hostName="127.0.0.1" httpPort="9002" httpsPort="9006"/>
    +                        <member hostName="127.0.0.1" httpPort="9003" httpsPort="9007"/>
    +                    </loadbalance>
    +                </endpoint>
    +            </send>
    +            <drop/>
    +        </in>
    +
    +        <out>
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +    <sequence name="errorHandler">
    +        <makefault response="true">
    +            <code value="tns:Receiver" xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +            <reason value="COULDN'T SEND THE MESSAGE TO THE SERVER."/>
    +        </makefault>
    +        <send/>
    +    </sequence>
    +
    +</definitions>
    +
    +

    +Objective: Demonstrate the simple static load balancing among a set of nodes

    +

    +Prerequisites:

    +

    Start Synapse with sample configuration 58. (i.e. wso2esb-samples -sn 58)

    +

    Deploy the LoadbalanceFailoverService by switching to <Synapse installation directory>/samples/axis2Server/src/LoadbalanceFailoverService directory and running ant.

    +

    Start three instances of sample Axis2 server on HTTP ports 9001, 9002 and 9003 and give some unique names to each server.

    +

    Example commands to run sample Axis2 servers from the <Synapse installation directory>/samples/axis2Server directory in Linux are listed below:

    +
    ./axis2server.sh -http 9001 -https 9005 -name MyServer1
    +./axis2server.sh -http 9002 -https 9006 -name MyServer2
    +./axis2server.sh -http 9003 -https 9007 -name MyServer3
    +

    Now we are done with setting up the environment for load balance sample. Start the load balance and failover client using the following command:

    +
    ant loadbalancefailover -Di=100
    +

    This client sends 100 requests to the LoadbalanceFailoverService through Synapse. Synapse will distribute the load among the three nodes mentioned in the configuration in a round-robin manner. LoadbalanceFailoverService appends the name of the server to the response, so that client can determine which server has processed the message. If you examine the console output of the client, you can see that requests are processed by three servers as follows:

    +
    [java] Request: 1 ==> Response from server: MyServer1
    +[java] Request: 2 ==> Response from server: MyServer2
    +[java] Request: 3 ==> Response from server: MyServer3
    +[java] Request: 4 ==> Response from server: MyServer1
    +[java] Request: 5 ==> Response from server: MyServer2
    +[java] Request: 6 ==> Response from server: MyServer3
    +[java] Request: 7 ==> Response from server: MyServer1
    +...
    +

    Now run the client without the -Di=100 parameter, i.e. ant loadbalancefailover, to send infinite requests. While running the client shutdown the server named MyServer1. You can observe that requests are only distributed among MyServer2 and MyServer3 after shutting down MyServer1. Console output before and after shutting down MyServer1 is listed below (MyServer1 was shutdown after request 63):

    +
    ...
    +[java] Request: 61 ==> Response from server: MyServer1
    +[java] Request: 62 ==> Response from server: MyServer2
    +[java] Request: 63 ==> Response from server: MyServer3
    +[java] Request: 64 ==> Response from server: MyServer2
    +[java] Request: 65 ==> Response from server: MyServer3
    +[java] Request: 66 ==> Response from server: MyServer2
    +[java] Request: 67 ==> Response from server: MyServer3
    +...
    +

    Now restart MyServer1. You can observe that requests will be again sent to all three servers.

    +

    Sample 59: Weighted load balancing between 3 +endpoints

    +
    <?xml version="1.0" encoding="UTF-8"?>
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <sequence name="main" onError="errorHandler">
    +        <in>
    +            <send>
    +                <endpoint>
    +                    <loadbalance
    +                            algorithm="org.apache.synapse.endpoints.algorithms.WeightedRoundRobin">
    +                        <endpoint>
    +                            <address uri="http://localhost:9001/services/LBService1">
    +                                <enableAddressing/>
    +                                <suspendOnFailure>
    +                                    <initialDuration>20000</initialDuration>
    +                                    <progressionFactor>1.0</progressionFactor>
    +                                </suspendOnFailure>
    +                            </address>
    +                            <property name="loadbalance.weight" value="1"/>
    +                        </endpoint>
    +                        <endpoint>
    +                            <address uri="http://localhost:9002/services/LBService1">
    +                                <enableAddressing/>
    +                                <suspendOnFailure>
    +                                    <initialDuration>20000</initialDuration>
    +                                    <progressionFactor>1.0</progressionFactor>
    +                                </suspendOnFailure>
    +                            </address>
    +                            <property name="loadbalance.weight" value="2"/>
    +                        </endpoint>
    +                        <endpoint>
    +                            <address uri="http://localhost:9003/services/LBService1">
    +                                <enableAddressing/>
    +                                <suspendOnFailure>
    +                                    <initialDuration>20000</initialDuration>
    +                                    <progressionFactor>1.0</progressionFactor>
    +                                </suspendOnFailure>
    +                            </address>
    +                            <property name="loadbalance.weight" value="3"/>
    +                        </endpoint>
    +                    </loadbalance>
    +                </endpoint>
    +            </send>
    +            <drop/>
    +        </in>
    +        <out>
    +            <send/>
    +        </out>
    +    </sequence>
    +    <sequence name="errorHandler">
    +        <makefault response="true">
    +            <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
    +            <reason value="COULDN'T SEND THE MESSAGE TO THE SERVER."/>
    +        </makefault>
    +        <send/>
    +    </sequence>
    +</definitions>
    + +

    Objective: Demonstrate the weighted load balancing among a set of +endpoints

    + +

    Prerequisites:

    + +

    Start ESB with sample configuration 59. (i.e. wso2esb-samples -sn 59)

    + +

    Deploy the LoadbalanceFailoverService and start three instances of sample Axis2 server as mentioned in sample 52.

    + +

    Above configuration sends messages with the weighted loadbalance behaviour. Weight of each leaf +address endpoint is defined by integer value of "loadbalance.weight" property associated with each endpoint. +If weight of a endpoint is x, x number of requests will send to that endpoint before switch to next active endpoint. +
    To test this, run the loadbalancefailover client to send 100 requests as follows:

    +
    ant loadbalancefailover -Di=100
    + +

    This client sends 100 requests to the LoadbalanceFailoverService through +ESB. ESB will distribute the load among the three endpoints mentioned in the +configuration in weighted round-robin manner. LoadbalanceFailoverService appends the +name of the server to the response, so that client can determine which server +has processed the message. If you examine the console output of the client, +you can see that requests are processed by three servers as follows:

    +
    [java] Request: 1 ==> Response from server: MyServer1
    +[java] Request: 2 ==> Response from server: MyServer2
    +[java] Request: 3 ==> Response from server: MyServer2
    +[java] Request: 4 ==> Response from server: MyServer3
    +[java] Request: 5 ==> Response from server: MyServer3
    +[java] Request: 6 ==> Response from server: MyServer3
    +[java] Request: 7 ==> Response from server: MyServer1
    +[java] Request: 8 ==> Response from server: MyServer2
    +[java] Request: 9 ==> Response from server: MyServer2
    +[java] Request: 10 ==> Response from server: MyServer3
    +[java] Request: 11 ==> Response from server: MyServer3
    +[java] Request: 12 ==> Response from server: MyServer3
    +...
    + +

    As logs, endpoint with weight 1 received a 1 request and endpoint with weight 2 received 2 +requests and etc... in a cycle

    + + diff --git a/docs/xdoc/samples/message_mediation_samples.xml b/docs/xdoc/samples/message_mediation_samples.xml new file mode 100644 index 0000000000..b55b3e6a03 --- /dev/null +++ b/docs/xdoc/samples/message_mediation_samples.xml @@ -0,0 +1,994 @@ + + + + + + + + WSO2 ESB - Message Mediation Samples + + + +

    Running the Message Mediation samples with WSO2 Enterprise Service Bus (ESB)

    +

    Sample 0: Introduction to ESB

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <!-- log all attributes of messages passing through -->
    +    <log level="full"/>
    +
    +    <!-- Send the messageto implicit destination -->
    +    <send/>
    +</definitions>
    + +

    Objective: Introduction to ESB. Shows how a message could be made +to pass through ESB and logged before it is delivered to its +ultimate receiver.

    + +

    The Stock quote client can operate in the following modes for this example.

    +
      +
    • Smart Client mode
    • +
    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ 
    +
      +
    • Using ESB as a HTTP Proxy
    • +
    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dprxurl=http://localhost:8280/
    +
      +
    • Gateway Mode / Dumb Client
    • +
    +

    See sample # 1

    + +

    Prerequisites: +
    Start the Synapse configuration numbered 0: e.g. wso2esb-samples -sn 0 +
    Start the Axis2 server and deploy the SimpleStockQuoteService if not already +deployed

    + +

    Execute the Smart Client

    + +

    By tracing the execution of ESB with the log output level set to DEBUG, +you will see the client request arriving at ESB with a WS-Addressing 'To' set +to EPR http://localhost:9000/services/SimpleStockQuoteService. The ESB engine +logs the message at the "full" log level (i.e. all the message headers and +the body) then sends the message to its implicit 'To' address which is +http://localhost:9000/services/SimpleStockQuoteService. You will see a message in +the Axis2 server console confirming that the message got routed to the sample +server and the sample service hosted at the sample server generating a stock +quote for the requested symbol.

    +
    Sat Nov 18 21:01:23 IST 2006 SimpleStockQuoteService :: Generating quote for : IBM
    + +

    The response message generated by the service is again received by ESB, +and flows through the same mediation rules, which logs the response message +and then sends it back. This time to the client. On the client console you +should see an output similar to the following based on the message received +by the client.

    +
    Standard :: Stock price = $95.26454380258552
    + +

    Execute the Proxy Client

    + +

    You will see the exact same behaviour as per the previous example when you +run this scenario. However this time the difference is at the client, as it +sends the message to the WS-Addressing 'To' address +http://localhost:9000/services/SimpleStockQuoteService, but the transport +specifies ESB as the http proxy.

    + +

    Sample 1: Simple content based routing (CBR) of messages

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <!-- filtering of messages with XPath and regex matches -->
    +    <filter source="get-property('To')" regex=".*/StockQuote.*">
    +        <send>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +        </send>
    +        <drop/>
    +    </filter>
    +    <send/>
    +</definitions> 
    + +

    Objective: Introduction to simple content based routing. Shows how +a message could be made to pass through ESB using the Dumb Client mode, where +ESB acts as a gateway to accept all messages and then perform mediation and +routing based on message properties or content.

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 1: i.e. wso2esb-samples -sn 1
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +deployed
    +

    + +

    Execute the Dumb Client as:

    +
    ant stockquote -Dtrpurl=http://localhost:8280/services/StockQuote
    + +

    This time you will see ESB receiving a message for which ESB was set as +the ultimate receiver of the message. Based on the 'To' EPR of +http://localhost:8280/services/StockQuote, ESB performs a match to the path +'/StockQuote' and as the request matches the XPath expression of the filter +mediator, the filter mediator's child mediators execute. This sends the +message to a different endpoint as specified by the endpoint definition. The +'drop' mediator terminates further processing of the current message in a +configuration. During response processing, the filter condition fails, and +thus the implicit 'send' mediator forwards the response back to the client. +

    + +

    Sample 2: CBR with the Switch-case mediator, using +message properties

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <switch source="//m0:getQuote/m0:request/m0:symbol" xmlns:m0="http://services.samples">
    +        <case regex="IBM">
    +            <!-- the property mediator sets a local property on the *current* message -->
    +            <property name="symbol" value="Great stock - IBM"/>
    +        </case>
    +        <case regex="MSFT">
    +            <property name="symbol" value="Are you sure? - MSFT"/>
    +        </case>
    +        <default>
    +            <!-- it is possible to assign the result of an XPath expression as well -->
    +            <property name="symbol"
    +                  expression="fn:concat('Normal Stock - ', //m0:getQuote/m0:request/m0:symbol)"
    +                  xmlns:m0="http://services.samples"/>
    +        </default>
    +    </switch>
    +
    +    <log level="custom">
    +        <!-- the get-property() XPath extension function allows the lookup of local message properties
    +            as well as properties from the Axis2 or Transport contexts (i.e. transport headers) -->
    +        <property name="symbol" expression="get-property('symbol')"/>
    +        <!-- the get-property() function supports the implicit message headers To/From/Action/FaultTo/ReplyTo -->
    +        <property name="epr" expression="get-property('To')"/>
    +    </log>
    +
    +    <!-- Send the messages where they are destined to (i.e. the 'To' EPR of the message) -->
    +    <send/>
    +</definitions>
    + +

    Objective: Introduce switch-case mediator and writing and reading +of local properties set on a message instance

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 2: i.e. wso2esb-samples -sn 2
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done.

    + +

    Execute the 'ant stockquote ..' request again in the smart client mode, +specifying 'IBM', 'MSFT' and 'SUN' as the stock symbols. When the symbol IBM +is requested, viewing the mediation logs you will see that the case +statements' first case for 'IBM' is executed and a local property named +'symbol' was set to 'Great stock - IBM'. Subsequently this local property +value is looked up by the log mediator and logged using the 'get-property()' +XPath extension function.

    + +

    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService +-Dtrpurl=http://localhost:8280/ -Dsymbol=IBM

    +
    INFO LogMediator - symbol = Great stock - IBM, epr = http://localhost:9000/axis2/services/SimpleStockQuoteService 
    + +

    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService +-Dtrpurl=http://localhost:8280/ -Dsymbol=MSFT

    +
    INFO LogMediator - symbol = Are you sure? - MSFT, epr = http://localhost:9000/axis2/services/SimpleStockQuoteService
    + +

    Sample 3: Local Registry entry definitions, reusable +endpoints and sequences

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <!-- define a string resource entry to the local registry -->
    +    <localEntry key="version">0.1</localEntry>
    +    <!-- define a reuseable endpoint definition -->
    +    <endpoint name="simple">
    +        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +    </endpoint>
    +
    +    <!-- define a reusable sequence -->
    +    <sequence name="stockquote">
    +        <!-- log the message using the custom log level. illustrates custom properties for log -->
    +        <log level="custom">
    +            <property name="Text" value="Sending quote request"/>
    +            <property name="version" expression="get-property('version')"/>
    +            <property name="direction" expression="get-property('direction')"/>
    +        </log>
    +        <!-- send message to real endpoint referenced by key "simple" endpoint definition -->
    +        <send>
    +            <endpoint key="simple"/>
    +        </send>
    +    </sequence>
    +
    +    <sequence name="main">
    +        <in>
    +            <property name="direction" value="incoming"/>
    +            <sequence key="stockquote"/>
    +        </in>
    +        <out>
    +            <send/>
    +        </out>
    +    </sequence>
    +</definitions>
    + +

    Objective: Illustrates local registry entry definitions, reusable +endpoints and sequences

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 3: i.e. wso2esb-samples -sn 3
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    This example uses a sequence named as "main" that specifies the main +mediation rules to be executed. This is equivalent to directly specifying the +mediators of the main sequence within the <definitions> tags. This is +the recommended and also a better approach for non-trivial configurations. +Execute the 'ant stockquote ..' request again, and following through the +mediation logs you will now notice that the sequence named "main" is +executed. Then for the incoming message flow the <in> mediator +executes, and it calls the sequence named "stockquote".

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/
    +
    DEBUG SequenceMediator - Sequence mediator <main> :: mediate()
    DEBUG InMediator - In mediator mediate()
    DEBUG SequenceMediator - Sequence mediator <stockquote> :: mediate()
    + +

    As the "stockquote" sequence executes, the log mediator dumps a simple +text/string property, result of an XPath evaluation, that picks up the key +named "version", and a second result of an XPath evaluation that picks up a +local message property set previously by the <property> mediator. The +get-property() XPath extension function is able to read message properties +local to the current message, local or remote registry entries, Axis2 message +context properties as well as transport headers. The local entry definition +for "version" defines a simple text/string registry entry for that which is +visible to all messages that pass through ESB.

    +
    [HttpServerWorker-1] INFO  LogMediator - Text = Sending quote request, version = 0.1, direction = incoming
    +[HttpServerWorker-1] DEBUG SendMediator - Send mediator :: mediate()
    +[HttpServerWorker-1] DEBUG AddressEndpoint - Sending To: http://localhost:9000/services/SimpleStockQuoteService 
    + +

    Sample 4: Introduction to error handling

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <!-- the default fault handling sequence used by Synapse - named 'fault' -->
    +    <sequence name="fault">
    +        <log level="custom">
    +            <property name="text" value="An unexpected error occured"/>
    +            <property name="message" expression="get-property('ERROR_MESSAGE')"/>
    +        </log>
    +        <drop/>
    +    </sequence>
    +
    +    <sequence name="sunErrorHandler">
    +        <log level="custom">
    +            <property name="text" value="An unexpected error occured for stock SUN"/>
    +            <property name="message" expression="get-property('ERROR_MESSAGE')"/>
    +        </log>
    +        <drop/>
    +    </sequence>
    +
    +    <!-- default message handling sequence used by Synapse - named 'main' -->
    +    <sequence name="main">
    +        <in>
    +            <switch source="//m0:getQuote/m0:request/m0:symbol" xmlns:m0="http://services.samples">
    +                <case regex="IBM">
    +                    <send>
    +                        <endpoint><address uri="http://localhost:9000/services/SimpleStockQuoteService"/></endpoint>
    +                    </send>
    +                </case>
    +                <case regex="MSFT">
    +                    <send>
    +                        <endpoint key="bogus"/>
    +                    </send>
    +                </case>
    +                <case regex="SUN">
    +                    <sequence key="sunSequence"/>
    +                </case>
    +            </switch>
    +            <drop/>
    +        </in>
    +
    +        <out>
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +    <sequence name="sunSequence" onError="sunErrorHandler">
    +        <send>
    +            <endpoint key="sunPort"/>
    +        </send>
    +    </sequence>
    +
    +</definitions> 
    + +

    Objective: Introduction to error handling with the 'fault' +sequence

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 4: i.e. wso2esb-samples -sn 4
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    When the IBM stock quote is requested, the configuration routes it to the +defined inline endpoint, which routes the message to the +SimpleStockQuoteService on the local Axis2 instance. Hence a valid response +message is shown at the client.

    + +

    If you lookup a stock quote for 'MSFT', ESB is instructed to route the +message to the endpoint defined as the 'bogus' endpoint, which does not +exist. ESB executes the specified error handler sequence closest to the point +where the error was encountered. In this case, the currently executing +sequence is 'main' and it does not specify an 'onError' attribute. Whenever +ESB cannot find an error handler, it looks for a sequence named 'fault'. Thus +the 'fault' sequence can be seen executing, and writing the generic error +message to the logs.

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=MSFT
    +
    [HttpServerWorker-1] DEBUG SendMediator - Send mediator :: mediate()
    +[HttpServerWorker-1] ERROR IndirectEndpoint - Reference to non-existent endpoint for key : bogus
    +[HttpServerWorker-1] DEBUG MediatorFaultHandler - MediatorFaultHandler :: handleFault
    +[HttpServerWorker-1] DEBUG SequenceMediator - Sequence mediator <fault> :: mediate()
    +[HttpServerWorker-1] DEBUG LogMediator - Log mediator :: mediate()
    +[HttpServerWorker-1] INFO  LogMediator - text = An unexpected error occured, message = Reference to non-existent endpoint for key : bogus
    + +

    When the 'SUN' quote is requested, a custom sequence 'sunSequence' is +invoked, and it specifies 'sunErrorHandler' as its error handler. Hence when +the send fails, you could see the proper error handler invocation and the +custom error message printed as follows.

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=SUN
    +
    [HttpServerWorker-1] DEBUG SequenceMediator - Sequence mediator <sunSequence> :: mediate()
    +[HttpServerWorker-1] DEBUG SequenceMediator - Setting the onError handler for the sequence
    +[HttpServerWorker-1] DEBUG AbstractListMediator - Implicit Sequence <SequenceMediator> :: mediate()
    +[HttpServerWorker-1] DEBUG SendMediator - Send mediator :: mediate()
    +[HttpServerWorker-1] ERROR IndirectEndpoint - Reference to non-existent endpoint for key : sunPort
    +[HttpServerWorker-1] DEBUG MediatorFaultHandler - MediatorFaultHandler :: handleFault
    +[HttpServerWorker-1] DEBUG SequenceMediator - Sequence mediator <sunErrorHandler> :: mediate()
    +[HttpServerWorker-1] DEBUG AbstractListMediator - Implicit Sequence <SequenceMediator> :: mediate()
    +[HttpServerWorker-1] DEBUG LogMediator - Log mediator :: mediate()
    +[HttpServerWorker-1] INFO  LogMediator - text = An unexpected error occured for stock SUN, message = Reference to non-existent endpoint for key : sunPort
    + +

    Sample 5: Creating SOAP fault messages and changing the +direction of a message

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="myFaultHandler">
    +        <makefault>
    +            <code value="tns:Receiver" xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +            <reason expression="get-property('ERROR_MESSAGE')"/>
    +        </makefault>
    +
    +        <send/>
    +    </sequence>
    +
    +    <sequence name="main" onError="myFaultHandler">
    +        <in>
    +            <switch source="//m0:getQuote/m0:request/m0:symbol"
    +                    xmlns:m0="http://services.samples">
    +                <case regex="MSFT">
    +                    <send>
    +                        <endpoint><address uri="http://bogus:9000/services/NonExistentStockQuoteService"/></endpoint>
    +                    </send>
    +                </case>
    +                <case regex="SUN">
    +                    <send>
    +                        <endpoint><address uri="http://localhost:9009/services/NonExistentStockQuoteService"/></endpoint>
    +                    </send>
    +                </case>
    +            </switch>
    +            <drop/>
    +        </in>
    +
    +        <out>
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +</definitions>
    + +

    Objective: Makefault mediator and sending back error responses +

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 5: i.e. wso2esb-samples -sn 5
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    When the MSFT stock quote is requested, an unknown host exception would be +generated. A connection refused exception would be generated for the SUN +stock request. This error message is captured and returned to the original +client as a SOAP fault in this example.

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=MSFT
    + +

    returns,

    +
    <soapenv:Fault xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><faultcode>soapenv:Client</faultcode>
    +    <faultstring>Connection refused or failed for : bogus:9000 </faultstring><detail /></soapenv:Fault>
    + +

    And

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=SUN
    + +

    returns,

    +
    <soapenv:Fault xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><faultcode>soapenv:Client</faultcode>
    +    <faultstring> Connection refused or failed for : localhost/127.0.0.1:9009</faultstring><detail /></soapenv:Fault>
    + +

    Sample 6: Manipulating SOAP headers, and filtering +incoming and outgoing messages

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <in>
    +        <header name="To" value="http://localhost:9000/services/SimpleStockQuoteService"/>
    +    </in>
    +    <send/>
    +</definitions>
    + +

    Objective: Introduction to header, in (out) mediators

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 6: i.e. wso2esb-samples -sn 6
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    In this example we use the stockquote client in the dumb client mode, +setting the 'To' EPR of the message to ESB. Then the 'in' mediator processes +the incoming messages, and manipulates the 'To' header to refer to the stock +quote service on the sample Axis2 server. Thus it is now possible to request +for a stock quote as follows.

    +
    ant stockquote -Dtrpurl=http://localhost:8280/
    + +

    Sample 7: Introduction to local Registry entries and +using Schema validation

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <localEntry key="validate_schema">
    +        <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    +                    xmlns="http://www.apache-synapse.org/test" elementFormDefault="qualified"
    +                    attributeFormDefault="unqualified"
    +                    targetNamespace="http://services.samples">
    +            <xs:element name="getQuote">
    +                <xs:complexType>
    +                    <xs:sequence>
    +                        <xs:element name="request">
    +                            <xs:complexType>
    +                                <xs:sequence>
    +                                    <xs:element name="stocksymbol" type="xs:string"/>
    +                                </xs:sequence>
    +                            </xs:complexType>
    +                        </xs:element>
    +                    </xs:sequence>
    +                </xs:complexType>
    +            </xs:element>
    +        </xs:schema>
    +    </localEntry>
    +
    +    <in>
    +        <validate>
    +            <schema key="validate_schema"/>
    +            <on-fail>
    +                <!-- if the request does not validate againt schema throw a fault -->
    +                <makefault>
    +                    <code value="tns:Receiver"
    +                            xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +                    <reason value="Invalid custom quote request"/>
    +                </makefault>
    +                <property name="RESPONSE" value="true"/>
    +                <header name="To" expression="get-property('ReplyTo')"/>
    +            </on-fail>
    +        </validate>
    +    </in>
    +    <send/>
    +</definitions> 
    + +

    Objective: Introduction to local (static) registry entries and the +validate mediator

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 7: i.e. wso2esb-samples -sn 7
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    This example shows how a static XML fragment could be made available to +the ESB local registry. Resources defined in the local registry are static +(i.e. never changes over the lifetime of the configuration) and may be +specified as a source URL, inline text or inline xml. In this example the +schema is made available under the key 'validate_schema'.

    + +

    The validate mediator by default operates on the first child element of +the SOAP body. You may specify an XPath expression using the 'source' +attribute to override this behaviour. The validate mediator now uses the +'validate_schema' resource to validate the incoming message, and if the +message validatation fails it invokes the 'on-fail' sequence of mediators. +

    + +

    If you send a stockquote request using 'ant stockquote ...' you will get a +fault back with the message 'Invalid custom quote request' as the schema +validation failed. This is because the schema used in the example expects a +slightly different message than what is created by the stock quote client. +(i.e. expects a 'stocksymbol' element instead of 'symbol' to specify the stock +symbol)

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/
    + +

    Sample 8: Introduction to static and dynamic registry +resources, and using XSLT transformations

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <!-- the SimpleURLRegistry allows access to a URL based registry (e.g. file:/// or http://) -->
    +    <registry provider="org.wso2.carbon.mediation.registry.ESBRegistry">
    +        <!-- the root property of the simple URL registry helps resolve a resource URL as root + key -->
    +        <parameter name="root">file:./repository/samples/resources/</parameter>
    +        <!-- all resources loaded from the URL registry would be cached for this number of milli seconds -->
    +        <parameter name="cachableDuration">15000</parameter>
    +    </registry>
    +
    +    <!-- define the request processing XSLT resource as a static URL source -->
    +    <localEntry key="xslt-key-req" src="file:repository/samples/resources/transform/transform.xslt"/>
    +
    +    <in>
    +        <!-- transform the custom quote request into a standard quote requst expected by the service -->
    +        <xslt key="xslt-key-req"/>
    +    </in>
    +    <out>
    +        <!-- transform the standard response back into the custom format the client expects -->
    +        <!-- the key is looked up in the remote registry and loaded as a 'dynamic' registry resource -->
    +        <xslt key="transform/transform_back.xslt"/>
    +    </out>
    +    <send/>
    +</definitions>
    + +

    Objective: Introduction to static and dynamic registry resources +and the XSLT mediator

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 8: i.e. wso2esb-samples -sn 8
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    This example uses the XSLT mediator to perform transformations, and the +xslt transformations are specified as registry resources. The first resource +'xslt-key-req' is specified as a 'local' registry entry. Local entries do not +place the resource on the registry, but simply make it available to the local +configuration. If a local entry is defined with a key that already exists in +the remote registry, the local entry will get higher preference and override +the remote resource.

    + +

    In this example you will notice the new 'registry' definition. ESB comes +with a simple URL based registry implementation SimpleURLRegistry. During +initialization of the registry, the SimpleURLRegistry expects to find a +property named 'root', which specifies a prefix for the registry keys used +later. When the SimpleURLRegistry is used, this root is prefixed to the entry +keys to form the complete URL for the resource being looked up. The registry +caches a resource once requested, and caches it internally for a specified +duration. Once this period expires, it will reload the meta information about +the resource and reload its cached copy if necessary, the next time the +resource is requested.

    + +

    Hence the second XSLT resource key 'transform/transform_back.xslt' +concatenated with the 'root' of the SimpleURLRegistry +'file:repository/samples/resources/' forms the complete URL of the +resource as +'file:repository/samples/resources/transform/transform_back.xslt' and +caches its value for a period of 15000 ms.

    + +

    Execute the custom quote client as 'ant stockquote -Dmode=customquote ...' +and analyze the the ESB debug log output

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dmode=customquote
    + +

    The incoming message is now transformed into a standard stock quote +request as expected by the SimpleStockQuoteService deployed on the local +Axis2 instance, by the XSLT mediator. The XSLT mediator uses Xalan-J to +perform the transformations. It is possible to configure the underlying +transformation engine using properties where necessary. The response from the +SimpleStockQuoteService is converted back into the custom format as expected +by the client during the out message processing.

    + +

    During the response processing the SimpleURLRegistry fetches the resource.

    + +

    If you run the client again immediately (i.e within 15 seconds of the +first request) you will not see the resource being reloaded by the registry +as the cached value would be still valid.

    + +

    However if you leave the system idle for 15 seconds or more and then retry +the same request, you will now notice that the registry noticed the cached +resource has expired and will check the meta information about the resource +to check if the resource itself has changed and will require a fresh fetch +from the source URL. If the meta data / version number indicates that a +reload of the cached resource is not necessary (i.e. unless the resource +itself actually changed) the updated meta information is used and the cache +lease extended as appropriate.

    +
    [HttpClientWorker-1] DEBUG AbstractRegistry - Cached object has expired for key : transform/transform_back.xslt
    +[HttpClientWorker-1] DEBUG SimpleURLRegistry - Perform RegistryEntry lookup for key : transform/transform_back.xslt
    +[HttpClientWorker-1] DEBUG AbstractRegistry - Expired version number is same as current version in registry
    +[HttpClientWorker-1] DEBUG AbstractRegistry - Renew cache lease for another 15s 
    + +

    Now edit the +repository/samples/resources/transform/transform_back.xslt file and add a +blank line at the end. Now when you run the client again, and if the cache is +expired, the resource would be re-fetched from its URL by the registry and +this can be seen by the following debug log messages

    +
    [HttpClientWorker-1] DEBUG AbstractRegistry - Cached object has expired for key : transform/transform_back.xslt
    +[HttpClientWorker-1] DEBUG SimpleURLRegistry - Perform RegistryEntry lookup for key : transform/transform_back.xslt
    + +

    Thus the SimpleURLRegistry allows resource to be cached, and updates +detected so that the changes could be reloaded without restarting the ESB +instance.

    + +

    Sample 9: Introduction to dynamic sequences with the +Registry

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <registry provider="org.wso2.carbon.mediation.registry.ESBRegistry">
    +        <parameter name="root">file:./repository/samples/resources/</parameter>
    +        <parameter name="cachableDuration">15000</parameter>
    +    </registry>
    +
    +    <sequence key="sequence/dynamic_seq_1.xml"/>
    +</definitions> 
    + +

    Objective: Introduction to dynamic sequences with a +Registry

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 9: i.e. wso2esb-samples -sn 9
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    This example introduces the dynamic behaviour of ESB through the use of a +Registry. ESB supports dynamic definitions for sequences and endpoints, and +as seen before, for resources. In this example we define a Synapse +configuration which references a sequence definition specified as a registry +key. The registry key resolves to the actual content of the sequence which +would be loaded dynamically by ESB at runtime, and cached appropriately as +per its definition in the registry. Once the cache expires, ESB would recheck +the meta information for the definition and re-load the sequence definition +if necessary and re-cache it again.

    + +

    Once ESB is started, execute the stock quote client as 'ant stockquote..'. +You will notice that that ESB fetches the definition of the sequence from the +registry and executes its rules as follows:

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/
    +
    [HttpServerWorker-1] DEBUG SequenceMediator - Sequence mediator <dynamic_sequence> :: mediate()
    +...
    +[HttpServerWorker-1] INFO  LogMediator - message = *** Test Message 1 ***
    + +

    Now if you execute the client immediately (i.e. within 15 seconds of the +last execution) you will notice that the sequence was not reloaded. If you +edit the sequence definition in +repository/samples/resources/sequence/dynamic_seq_1.xml (i.e. edit the +log message to read as "*** Test Message 2 ***") and execute the client +again, you will notice that the new message is not yet visible (i.e. if you +execute this within 15 seconds of loading the resource for the first time) +However, after 15 seconds elapsed since the original caching of the sequence, +you will notice that the new sequence is loaded and executed by ESB from the +following log messages.

    +
    [HttpServerWorker-1] DEBUG SequenceMediator - Sequence mediator <dynamic_sequence> :: mediate()
    +...
    +[HttpServerWorker-1] INFO  LogMediator - message = *** Test Message 2 ***
    + +

    The cache timeout could be tuned appropriately by configuring the URL +registry to suite the environment and the needs.

    + +

    Sample 10: Introduction to dynamic endpoints with the +Registry

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <registry provider="org.wso2.carbon.mediation.registry.ESBRegistry">
    +        <parameter name="root">file:repository/samples/resources/</parameter>
    +        <parameter name="cachableDuration">15000</parameter>
    +    </registry>
    +
    +    <in>
    +        <send>
    +            <endpoint key="endpoint/dynamic_endpt_1.xml"/>
    +        </send>
    +    </in>
    +    <out>
    +        <send/>
    +    </out>
    +</definitions> 
    + +

    Objective: Introduction to dynamic endpoints with the +Registry

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 10: i.e. wso2esb-samples -sn 10
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done
    +Start a second Axis2 server on http port 9001 and https port 9003 as follows: +

    +
    ./axis2server.sh -http 9001 -https 9003
    + +

    This example introduces dynamic endpoints, where the definition of an +endpoint is stored in the Registry. To follow this example execute the stock +quote client as 'ant stockquote..' and see that the message is routed to the +SimpleStockQuoteService on the default Axis2 instance on http port 9000. +Repeat the above example immediately again, and notice that the endpoint is +cached and reused by ESB - similarly to example # 8.

    +
    ant stockquote -Dtrpurl=http://localhost:8280/
    + +

    Now edit the repository/samples/resources/endpoint/dynamic_endpt_1.xml +definition and update the address to +"http://localhost:9001/services/SimpleStockQuoteService". After the cached +expires, the Registry loads the new definition of the endpoint, and then the +messages can be seen being routed to the second sample Axis2 server on http +port 9001.

    + +

    Sample 11: A full registry based configuration, and +sharing a configuration between multiple instances

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <registry provider="org.wso2.carbon.mediation.registry.ESBRegistry">
    +        <parameter name="root">file:./repository/samples/resources/</parameter>
    +        <parameter name="cachableDuration">15000</parameter>
    +    </registry>
    +</definitions> 
    + +

    Objective: A full registry based configuration

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 11: i.e. wso2esb-samples -sn 11
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    This example shows a full registry based ESB configuration. Thus it is +possible to start a remote configuration from multiple instances of ESB in a +clustered environment easily. The Synapse configuration held on a node +hosting ESB simply points to the registry and looks up the actual +configuration by requesting the key 'synapse.xml'.

    + +

    (Note: Full registry based configuration is not dynamic atleast for the +moment. i.e. it is not reloading itself)

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/
    +
    [HttpServerWorker-1] INFO LogMediator - message = This is a dynamic Synapse configuration
    + +

    The actual synapse.xml loaded is:

    +
    <!-- a registry based Synapse configuration -->
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <log level="custom">
    +        <property name="message" value="This is a dynamic Synapse configuration $$$"/>
    +    </log>
    +    <send/>
    +</definitions>
    + +

    Sample 12: One way messaging / fireAndForget through +ESB

    + +

    Objective: Demonstrate one way messaging / fireAndForget through +ESB

    + +

    Prerequisites:
    +Start the Axis2 server and deploy the SimpleStockQuoteService (Refer steps +above)
    +Start the Synapse configuration numbered 0: i.e. wso2esb-samples -sn 0

    + +

    This example invokes the one-way 'placeOrder' operation on the +SimpleStockQuoteService using the custom client which uses the Axis2 +ServiceClient.fireAndForget() API. To test this, use 'ant +-Dmode=placeorder...' and you will notice the one way message flowing through +ESB into the sample Axis2 server instance, which reports the acceptance of +the order as follows:

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dmode=placeorder
    +
    SimpleStockQuoteService :: Accepted order for : 7482 stocks of IBM at $ 169.27205579038733
    + +

    If you send your client request through TCPmon, you will notice that the +SimpleStockQuoteService replies to ESB with a HTTP 202 reply, and that ESB +in-turn replies to the client with a HTTP 202 acknowledgement

    + +

    +Sample 13: Dual channel invocation through synapse +

    +

    +Objective: Demonstrate dual channel messaging +through synapse +

    +

    Prerequisites:
    Start the Axis2 server +and deploy the SimpleStockQuoteService (Refer steps above)
    Start +the Synapse configuration numbered 0: i.e. wso2esb-samples.sh -sn 0 +

    +

    +This example invokes the same 'getQuote' operation on the +SimpleStockQuoteService using the custom client which uses the Axis2 +ServiceClient API with useSeparateListener set to true so that the response is +coming through a different channel than the one which is used to send the request +to a callback defined in the client. +To test this, use 'ant +-Dmode=dualquote...' and you will notice the dual channel invocation +through Synapse into the sample Axis2 server instance, which reports the response +back to the client over a different channel: +

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dmode=dualquote
    +
    Response received to the callback
    +    Standard dual channel :: Stock price = $57.16686934968289
    +

    +If you send your client request through TCPmon, you will notice that +Synapse replies to the client with a HTTP 202 acknowledgment when you send the request and +the communication between synapse and the server happens on a single channel and then you +get the response back from synapse to the clients callback in a different channel (which +cannot be observed through TCPmon) +

    +

    +Also you could see the wsa:Reply-To header being something like +http://localhost:8200/axis2/services/anonService2 which implies that the reply +is being on a different channel listening on the port 8200. Please note that it is +required to engage addressing when using the dual channel invocation because it +requires the wsa:Reply-To header. +

    + + +

    +Sample 14: Sequences and Endpoints as local registry items +

    + +
    <definitions xmlns="http://ws.apache.org/ns/synapse"
    +             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    +             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">
    +
    +    <localEntry key="local-enrty-ep-key"
    +                src="file:repository/conf/sample/resources/endpoint/dynamic_endpt_1.xml"/>
    +
    +    <localEntry key="local-enrty-sequence-key">
    +        <sequence name="dynamic_sequence">
    +            <log level="custom">
    +                <property name="message" value="*** Test Message 1 ***"/>
    +            </log>
    +        </sequence>
    +    </localEntry>
    +
    +    <sequence name="main">
    +        <in>
    +            <sequence key="local-enrty-sequence-key"/>
    +            <send>
    +                <endpoint key="local-enrty-ep-key"/>
    +            </send>
    +        </in>
    +        <out>
    +            <send/>
    +        </out>
    +    </sequence>
    +</definitions>
    + +

    +Objective: Sequence and Endpoints as local registry entries +

    +

    Prerequisites:
    Start the Axis2 server +and deploy the SimpleStockQuoteService (Refer steps above)
    Start +the Synapse configuration numbered 14: i.e. wso2esb-samples.sh -sn 14 +

    +

    +This example shows sequences and endpoints fetched from local registry. +Thus it is possible to have endpoints sequences as local registry entries including file entries. +Execute the following command to see the sample working, where you will be able to see the +log statement from the fetched sequence from the local entry and the endpoint will be fetched from +the specified file at runtime and be cached in the system

    +
    ant stockquote -Dtrpurl=http://localhost:8280/
    + + + +

    +Sample 15: Message Enrichment through Synapse

    +
    +<definitions xmlns="http://synapse.apache.org/ns/2010/04/configuration">
    +    <sequence name="main">
    +        <in>
    +            <enrich>
    +                <source type="custom"
    +                        xpath="//m0:getQuote/m0:request/m0:symbol/text()"
    +                        xmlns:m0="http://services.samples"/>
    +                <target type="property" property="ORIGINAL_REQ"/>
    +            </enrich>
    +            <enrich>
    +                <source type="body"/>
    +                <target type="property" property="REQUEST_PAYLOAD"/>
    +            </enrich>
    +
    +            <enrich>
    +                <source type="inline" key="init_req"/>
    +                <target xmlns:m0="http://services.samples"
    +                        xpath="//m0:getQuote/m0:request/m0:symbol/text()"/>
    +            </enrich>
    +
    +            <send>
    +                <endpoint>
    +                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                </endpoint>
    +            </send>
    +            <drop/>
    +        </in>
    +        <out>
    +            <header xmlns:urn="http://synapse.apache.org" name="urn:lastTradeTimestamp" value="foo"/>
    +            <enrich>
    +                <source type="custom"
    +                        xpath="//ns:getQuoteResponse/ns:return/ax21:lastTradeTimestamp"
    +                        xmlns:ns="http://services.samples"
    +                        xmlns:ax21="http://services.samples/xsd"/>
    +                <target xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    +                        xmlns:urn="http://synapse.apache.org"
    +                        xpath="/soapenv:Envelope/soapenv:Header/urn:lastTradeTimestamp"/>
    +            </enrich>
    +             <log level="full"/>
    +            <log>
    +                <property name="Original Request Symbol" expression="get-property('ORIGINAL_REQ')"/>
    +                <property name="Request Payload" expression="get-property('REQUEST_PAYLOAD')"/>
    +            </log>
    +            <send/>
    +        </out>
    +
    +    </sequence>
    +    <localEntry key="init_req">MSFT</localEntry>
    +    <localEntry key="price_req">
    +        <m0:symbol xmlns:m0="http://services.samples">MSFT</m0:symbol>
    +    </localEntry>
    +
    +</definitions>
    +
    +

    +Objective: Introduction to Message Copying and Content Enriching with Enrich Mediator

    +

    +Prerequisites: +
    Start the Synapse configuration numbered 15: i.e. synapse -sample 15 +
    Start the Axis2 server and deploy the SimpleStockQuoteService if not already done +

    +
    ./axis2server.sh
    +

    This sample demonstrate the various capabilities of Enrich Mediator. Inside the in-sequence we store/copy different + parts of the message to properties and just before sending the message to the StockQuoteService, we modify the + request value based on the local entry value-init_req. Then in the out-sequence, the enrich mediator is used + to enrich a soap header based on the 'lastTradeTimestamp' value of the response. +

    +
    ant stockquote -Dtrpurl=http://localhost:8280/services/StockQuote
    +

    You can try with different local entries as the source with the correct target xpath values.

    + +

    +Sample 16: Introduction to dynamic and static registry keys

    +
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <!-- the SimpleURLRegistry allows access to a URL based registry (e.g. file:/// or http://) -->
    +    <registry provider="org.wso2.carbon.mediation.registry.ESBRegistry">
    +        <!-- the root property of the simple URL registry helps resolve a resource URL as root + key -->
    +        <parameter name="root">file:repository/samples/resources/</parameter>
    +        <!-- all resources loaded from the URL registry would be cached for this number of milli seconds -->
    +        <parameter name="cachableDuration">15000</parameter>
    +    </registry>
    +
    +    <sequence name="main">
    +        <in>
    +            <!-- define the request processing XSLT resource as a property value -->
    +            <property name="symbol" value="transform/transform.xslt"/>
    +            <!-- {} denotes that this key is a dynamic one and it is not a static key -->
    +            <!-- use Xpath expression "get-property()" to evaluate real key from property -->
    +            <xslt key="{get-property('symbol')}"/>
    +        </in>
    +        <out>
    +            <!-- transform the standard response back into the custom format the client expects -->
    +            <!-- the key is looked up in the remote registry using a static key -->
    +            <xslt key="transform/transform_back.xslt"/>
    +        </out>
    +        <send/>
    +    </sequence>
    +
    +</definitions>
    +
    +

    +Objective: Introduction to dynamic and static keys

    +

    +Prerequisites: +
    Start the Synapse configuration numbered 16: i.e. synapse -sample 16 +
    Start the Axis2 server and deploy the SimpleStockQuoteService if not already done +

    +
    ./axis2server.sh
    +

    This Sample demonstrates the use of dynamic keys with mediators. XSLT mediator is used as an + example for that and deference between static and dynamic usage of keys are shown with that. +

    +

    The first registry resource "transform/transform.xslt" is set as a property value. Inside the + XSLT mediator the local property value is lookup using the Xpath expression "get-property()". + Likewise any Xpath expression can be enclosed inside "{ }" to denote that it is a dynamic key. + Then the mediator will evaluate the real value for that expression. +

    +

    The second XSLT resource "transform/transform_back.xslt" is used simply as a static key as + usual. It is not included inside "{ }" and because of the mediator directly use the static + value as the key. +

    +

    Execute the custom quote client as 'ant stockquote -Dmode=customquote' and analys the output + which is similar to the Sample 8. +

    + +
    ant stockquote -Dtrpurl=http://localhost:8280/services/StockQuote
    +

    You can try with different local entries as the source with the correct target xpath values.

    + + + diff --git a/docs/xdoc/samples/misc_samples.xml b/docs/xdoc/samples/misc_samples.xml new file mode 100644 index 0000000000..45bbeaf5b6 --- /dev/null +++ b/docs/xdoc/samples/misc_samples.xml @@ -0,0 +1,646 @@ + + + + + + + + WSO2 ESB - Miscellaneous Samples + + + + +

    + Sample 650: File hierarchy based configuration builder +

    +

    +   +

    +
    +      synapse_sample_650.xml
    +         |-- endpoints
    +         |   `-- foo.xml
    +         |-- events
    +         |   `-- event1.xml
    +         |-- local-entries
    +         |   `-- bar.xml
    +         |-- proxy-services
    +         |   |-- proxy1.xml
    +         |   |-- proxy2.xml
    +         |   `-- proxy3.xml
    +         |-- registry.xml
    +         |-- sequences
    +         |   |-- custom-logger.xml
    +         |   |-- fault.xml
    +         |   `-- main.xml
    +         |-- synapse.xml
    +         `-- tasks
    +             `-- task1.xml
    +
    +    
    +
    +

    + Objective: Demonstrate the ability to construct the Synapse configuration from a file hierarchy +

    +

    + Prerequisites: Deploy the + SimpleStockQuoteService in sample Axis2 server and start it on port + 9000. +

    +

    + Start ESB with the sample configuration 650 (i.e. wso2esb-samples.sh -sn 650). +

    +

    + Go to the repository/samples directory and locate the subdirectory named synapse_sample_650.xml + within it. When ESB is started with the sample configuration 650, ESB will load the configuration from + this directory. You will find a number of subdirectories and a set of XML files in each of those directories. + Synapse will parse all the XML files in this file hierarchy and construct the full Synapse configuration at startup. + As a result when this sample is executed Synapse will start with four proxy services, several sequences, a task, an event + source and some endpoint and local entry definitions. +

    +

    + The names of the subdirectories (eg: proxy-services, sequences, endpoints) are fixed and hence cannot be changed. + Also the registry definition should go into a file named registry.xml which resides at the top level of the file + hierarchy. It can also be specified in the synapse.xml file at top level. This synapse.xml file can include + any item that can be normally defined in a synapse.xml file. The files which define proxy services, sequences, + endpoints etc can have any name. These configuration files must have the .xml extension at the end of the name. Synapse + will ignore any files which do not have the .xml extension. +

    +

    + None of the directories and files in the sample file hierachy are mandatory. You can leave entire directories out if + you do not need them. For example if your configuration does not contain any proxy services you can leave the + subdirectory named proxy-services out. +

    +

    + To use this feature you should simply pass a path to an existing directory when starting the Synapse server. The + SynapseServer class which is responsible for starting the server accepts a file path as an argument from where to + load the configuration. Generally we pass the path to the synapse.xml file as the value of this argument. If you + pass a directory path instead, Synapse configuration will be loaded from the specified directory. Note the following + line on the console when Synapse is loading the configuration from a file hierarchy. +

    +
    2009-08-04 14:14:42,489 [-] [main]  INFO SynapseConfigurationBuilder Loaded Synapse configuration from the directory hierarchy at : /home/synapse/repository/conf/sample/synapse_sample_650.xml
    +

    + This feature comes in handy when managing large Synapse configurations. It is easier to maintain a well structured + file hierarchy than managing one large flat XML file. +

    +
    +

    + Sample 651: Using Synapse observers +

    +
    +

    + Objective: Demonstrate the ability to monitor the Synapse configuration at runtime using the + SynapseObserver interface +

    +

    + Open the synapse.properties file in the ESB_HOME/webapps/ROOT/WEB-INF/classes directory using a text editor and add the following + line to the synapse.properties file. This entry defines the simple logging Synapse observer. +

    +
    synapse.observers=samples.userguide.SimpleLoggingObserver
    +

    + Open the log4j.properties file in the ESB_HOME/lib directory and add the followin line which sets the INFO log + level to the samples.userguide package. +

    +
    log4j.category.samples.userguide=INFO
    +

    + Start Synapse using any of the sample configurations. The SimpleLoggingObserver will capture events that occur + while constructing the Synapse configuration and log them on the console as follows. +

    +
    +  2009-08-06 14:30:24,578 [-] [main]  INFO SimpleLoggingObserver Simple logging observer initialized...Capturing Synapse events...
    +  2009-08-06 14:30:24,604 [-] [main]  INFO SimpleLoggingObserver Endpoint : a3 was added to the Synapse configuration successfully
    +  2009-08-06 14:30:24,605 [-] [main]  INFO SimpleLoggingObserver Endpoint : a2 was added to the Synapse configuration successfully
    +  2009-08-06 14:30:24,606 [-] [main]  INFO SimpleLoggingObserver Endpoint : null was added to the Synapse configuration successfully
    +  2009-08-06 14:30:24,611 [-] [main]  INFO SimpleLoggingObserver Local entry : a1 was added to the Synapse configuration successfully
    +  2009-08-06 14:30:24,649 [-] [main]  INFO SimpleLoggingObserver Proxy service : StockQuoteProxy2 was added to the Synapse configuration successfully
    +  2009-08-06 14:30:24,661 [-] [main]  INFO SimpleLoggingObserver Proxy service : StockQuoteProxy1 was added to the Synapse configuration successfully
    +  2009-08-06 14:30:24,664 [-] [main]  INFO SimpleLoggingObserver Sequence : main was added to the Synapse configuration successfully
    +  2009-08-06 14:30:24,701 [-] [main]  INFO SimpleLoggingObserver Sequence : fault was added to the Synapse configuration successfully
    + +

    + The SimpleLoggingObserver is implemented as follows. It does not override any of the event handler implementations + in the AbstractSynapseObserver class. The AbstractSynapseObserver logs all the received events by default. +

    +
    + package samples.userguide;
    +
    + import org.apache.synapse.config.AbstractSynapseObserver;
    +
    + public class SimpleLoggingObserver extends AbstractSynapseObserver {
    +
    +     public SimpleLoggingObserver() {
    +         super();
    +         log.info("Simple logging observer initialized...Capturing Synapse events...");
    +     }
    + }
    +
    + +

    + Sample 652: Priority Based Message Mediation +

    +

    +   +

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <priority-executor name="exec">
    +        <queues>
    +            <queue size="100" priority="1"/>
    +            <queue size="100" priority="10"/>
    +        </queues>
    +    </priority-executor>
    +    <proxy name="StockQuoteProxy">
    +        <target>
    +            <inSequence>
    +                <filter source="$trp:priority" regex="1">
    +                    <then>
    +                        <enqueue priority="1" sequence="priority_sequence" executor="exec"/>
    +                    </then>
    +                    <else>
    +                        <enqueue priority="10" sequence="priority_sequence" executor="exec"/>
    +                    </else>
    +                </filter>
    +            </inSequence>
    +            <outSequence>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +    <sequence name="priority_sequence">
    +        <log level="full"/>
    +        <send>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +        </send>
    +    </sequence>
    +</definitions>
    +
    +

    + Objective: Demonstrate the priority based mediation capability of ESB. +

    +

    + Prerequisites: Deploy the + SimpleStockQuoteService in sample Axis2 server and start it on port + 9000. Priority is applied only when ESB is loaded with enough messages to consume its core number of threads. + So to observe the priority based mediation, it is required to use a load testing tool like JMeter, SOAP UI or Apache bench. +

    +

    + Start ESB with the sample configuration 652 (i.e. wso2esb-samples.sh -sn 652). +

    +

    + In this sample, client should send a HTTP header that specifies the priority of the message.This header name is priority. + This header is retrieved in the ESB configuration using the $trp:priority XPath expression. Then it is matched against + the value 1. If it has the value 1, message is executed with priority 1. Otherwise the message is executed with priority 10. +

    +

    + Here are two sample XML files that can be used to invoke the service using a tool like JMeter, or Ab. For SOAP UI, + user can use the WSDL repository/samples/resources/proxy/sample_proxy_1.wsdl to create the request. The only + difference between the two demonstrated requests here is the symbol. One has the symbol as IBM and other has MSFT. For one type of + request set the priority header to 1 and for the next set the priority header to 10. Then load ESB with high + volume of traffic from both types of requests using the load testing tool. In the back end server it prints the + symbol of the incoming requests. User should be able to see more of high priority symbol. +

    +
    +<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    +     <soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
    +        <wsa:To>http://localhost:8281/services/SimpleStockQuoteService</wsa:To>
    +        <wsa:MessageID>urn:uuid:1B57D0B0BF770678DE1261165228620</wsa:MessageID>
    +        <wsa:Action>urn:getQuote</wsa:Action>
    +     </soapenv:Header>
    +     <soapenv:Body>
    +        <m0:getQuote xmlns:m0="http://services.samples">
    +           <m0:request>
    +              <m0:symbol>IBM</m0:symbol>
    +           </m0:request>
    +        </m0:getQuote>
    +     </soapenv:Body>
    +</soapenv:Envelope>
    +           
    +
    +<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    +     <soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
    +        <wsa:To>http://localhost:8281/services/SimpleStockQuoteService</wsa:To>
    +        <wsa:MessageID>urn:uuid:1B57D0B0BF770678DE1261165228620</wsa:MessageID>
    +        <wsa:Action>urn:getQuote</wsa:Action>
    +     </soapenv:Header>
    +     <soapenv:Body>
    +        <m0:getQuote xmlns:m0="http://services.samples">
    +           <m0:request>
    +              <m0:symbol>MSFT</m0:symbol>
    +           </m0:request>
    +        </m0:getQuote>
    +     </soapenv:Body>
    +</soapenv:Envelope>
    +           
    +
    + +

    + Sample 653: NHTTP Transport Priority Based Dispatching +

    +

    +   +

    +

    + Here is the priority configuration file used by the NHTTP transport to determine the priority based on HTTP level properties. +

    +
    <priorityConfiguration>
    +    <priority-executor>
    +        <!-- two priorities specified with priority 10 and 1. Both priority messages has a queue depth of 100 -->
    +        <queues isFixedCapacity="true" nextQueue="org.apache.synapse.commons.executors.PRRNextQueueAlgorithm">
    +            <queue size="100" priority="10"/>
    +            <queue size="100" priority="1"/>
    +        </queues>
    +        <!-- these are the default values, values are put here to show their availability -->
    +        <threads core="20" max="100" keep-alive="5"/>
    +    </priority-executor>
    +
    +    <!-- if a message comes that we cannot determine priority, we set a default priority of 1 -->
    +    <conditions defaultPriority="1">
    +        <condition priority="10">
    +            <!-- check for the header named priority -->
    +            <equal type="header" source="priority" value="5"/>
    +        </condition>
    +        <condition priority="1">
    +            <equal type="header" source="priority" value="1"/>
    +        </condition>
    +    </conditions>
    +</priorityConfiguration>
    +
    +

    + Objective: Demonstrate the priority based dispatching of NHTTP transport. +

    +

    + Prerequisites: Deploy the + SimpleStockQuoteService in sample Axis2 server and start it on port + 9000. Priority is applied only when ESB is loaded with enough messages to consume its core number of threads. + So to observe the priority based dispatching, it is required to use a load testing tool like JMeter, SOAP UI or Apache bench. +

    +

    + Open axis2.xml in repository/conf directory and uncomment the following parameter to the configuration. + priorityConfigFile. Set the value to repository/samples/resources/priority/priority-configuration.xml +

    +

    + We'll use the sample number 150. Start ESB with the sample configuration 150 (i.e. wso2esb-samples.sh -sn 150). +

    +

    + In this sample, client should send a HTTP header that specifies the priority of the message.This header name is priority. + This header is retrieved in the prioirty configuration. Then it is matched against + the value 1 and 10. Depending on this value message is executed with priority 1 or 10. +

    +

    + Here are two sample XML files that can be used to invoke the service using a tool like JMeter, or Apache Ab. For SOAP UI, + user can use the WSDL repository/conf/sample/resources/proxy/sample_proxy_1.wsdl to create the request. The only + difference between the two demonstrated requests here is the symbol. One has the symbol as IBM and other has MSFT. For one type of + request set the priority header to 1 and for the next set the priority header to 10. Then load ESB with high + volume of traffic from both types of requests using the load testing tool. In the back end server it prints the + symbol of the incoming requests. User should be able to see more of high priority symbol. +

    +
    +<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    +     <soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
    +        <wsa:To>http://localhost:8281/services/SimpleStockQuoteService</wsa:To>
    +        <wsa:MessageID>urn:uuid:1B57D0B0BF770678DE1261165228620</wsa:MessageID>
    +        <wsa:Action>urn:getQuote</wsa:Action>
    +     </soapenv:Header>
    +     <soapenv:Body>
    +        <m0:getQuote xmlns:m0="http://services.samples">
    +           <m0:request>
    +              <m0:symbol>IBM</m0:symbol>
    +           </m0:request>
    +        </m0:getQuote>
    +     </soapenv:Body>
    +</soapenv:Envelope>
    +           
    +
    +<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    +     <soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
    +        <wsa:To>http://localhost:8281/services/SimpleStockQuoteService</wsa:To>
    +        <wsa:MessageID>urn:uuid:1B57D0B0BF770678DE1261165228620</wsa:MessageID>
    +        <wsa:Action>urn:getQuote</wsa:Action>
    +     </soapenv:Header>
    +     <soapenv:Body>
    +        <m0:getQuote xmlns:m0="http://services.samples">
    +           <m0:request>
    +              <m0:symbol>MSFT</m0:symbol>
    +           </m0:request>
    +        </m0:getQuote>
    +     </soapenv:Body>
    +</soapenv:Envelope>
    +           
    +
    +

    + Sample 654: Smooks Mediator +

    +

    +   +

    +

    + Here is the sample with smooks mediator. +

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <localEntry key="transform-xslt-key"
    +                src="file:repository/samples/resources/smooks/transform.xslt"/>
    +    <localEntry key="smooks-key" src="file:repository/samples/resources/smooks/smooks-config.xml"/>
    +    <proxy name="StockQuoteProxy" transports="vfs">
    +        <parameter name="transport.vfs.ContentType">text/plain</parameter>
    +        <!--CHANGE-->
    +        <parameter name="transport.vfs.ContentType">text/plain</parameter>
    +       <parameter name="transport.vfs.FileURI">file:///home/user/dev/test/smooks/in</parameter>
    +       <parameter name="transport.vfs.FileNamePattern">.*\.txt</parameter>
    +        <parameter name="transport.PollInterval">5</parameter>
    +        <!--CHANGE-->
    +        <parameter name="transport.vfs.MoveAfterProcess">file:///home/user/dev/test/smooks/original</parameter>
    +        <!--CHANGE-->
    +        <parameter name="transport.vfs.MoveAfterFailure">file:///home/user/dev/test/smooks/original</parameter>
    +        <parameter name="transport.vfs.ActionAfterProcess">MOVE</parameter>
    +        <parameter name="transport.vfs.ActionAfterFailure">MOVE</parameter>
    +        <parameter name="Operation">urn:placeOrder</parameter>
    +        <target>
    +            <inSequence>
    +                <smooks config-key="smooks-key"/>
    +                <xslt key="transform-xslt-key"/>
    +                <iterate expression="//m0:placeOrder/m0:order" preservePayload="true"
    +                         attachPath="//m0:placeOrder" xmlns:m0="http://services.samples">
    +                    <target>
    +                        <sequence>
    +                            <header name="Action" value="urn:placeOrder"/>
    +                            <property action="set" name="OUT_ONLY" value="true"/>
    +                            <send>
    +                                <endpoint>
    +                                    <address format="soap11"
    +                                            uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                                </endpoint>
    +                            </send>
    +                        </sequence>
    +                    </target>
    +                </iterate>
    +            </inSequence>
    +            <outSequence/>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/smooks/PlaceStockOrder.wsdl"/>
    +    </proxy>
    +</definitions>
    +
    +

    + Objective:Demonstrate the smooks mediatot EDI message processing. +

    +

    + Prerequisites: Deploy the + SimpleStockQuoteService in sample Axis2 server and start it on port 9000. Then add the + plain text builder to the messageBuilders section of the axis2.xml found in the + repository/conf directory. Here is the sample configuration. +

    +
    <messageBuilder contentType="text/plain" class="org.apache.axis2.format.PlainTextBuilder"/>
    +

    Enable the vfs transport in axis2.xml by uncomenting the vfs transport sender and receiver configurations in the axis2.xml.

    +

    User has to edit the synapse_sample_654.xml found in the repository/samples directory. These are the configuration parameters that needs to be edited.

    +
      +
    • transport.vfs.FileURI
    • +
    • transport.vfs.MoveAfterProcess
    • +
    • transport.vfs.ActionAfterFailure
    • +
    +

    + Start ESB with the sample configuration 654 (i.e. wso2esb-samples.sh -sn 654). +

    +

    Drop the edi.txt file found in the repository/samples/resources/smooks directory to the transport.vfs.FileURI parameter specified directory.

    +
    + +

    + Sample 655: Message Relay - Basics +

    +

    +   +

    +

    + This sample is similar to sample 150 except we have added two log mediators to show the actual message going through the ESB. +

    +
    <?xml version="1.0"?>
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <proxy name="StockQuoteProxy" startOnLoad="true">
    +        <target>
    +            <inSequence>
    +                <log level="full"/>
    +                <send>
    +                    <endpoint name="epr">
    +                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                    </endpoint>
    +                </send>
    +            </inSequence>
    +            <outSequence>
    +                <log level="full"/>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +    <sequence name="fault">
    +        <log level="full">
    +            <property name="MESSAGE" value="Executing default &quot;fault&quot; sequence"/>
    +            <property name="ERROR_CODE" expression="get-property('ERROR_CODE')"/>
    +            <property name="ERROR_MESSAGE" expression="get-property('ERROR_MESSAGE')"/>
    +        </log>
    +        <drop/>
    +    </sequence>
    +    <sequence name="main">
    +        <log/>
    +        <drop/>
    +    </sequence>
    +</definitions>
    +
    +

    + Objective:Demonstrate the Message Relay. +

    +

    + Prerequisites: Deploy the + SimpleStockQuoteService in sample Axis2 server and start it on port 9000. Then uncomment the Message Relay's Message Builder and Message Formatter in the axis2.xml. + These configurations can be found in the messageFormatters and messageBuilders section of the axis2.xml. + A message formatter or builder is defined for a content type. So make sure you comment + out the normla builders and formatters for a content type when uncomenting the message + relay builders and formatters. +

    +

    Here are the Message Relay Formatter and Builder classes. You need to uncomment the entries containing the following builder and formatter.

    +
    org.wso2.carbon.relay.ExpandingMessageFormatter
    +
    org.wso2.carbon.relay.BinaryRelayBuilder
    +

    Send a message to the sample using the sample axis2 client.

    +
    ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy
    +

    You can see the messages going through the proxy by looking at the console because we have two log mediators in this sample. The actual message is not built and printed as a Base64 encoded string.

    +
    + +

    + Sample 656: Message Relay - Builder Mediator +

    +

    +   +

    +

    + This sample is similar to sample 655. We have added the builder mediator to build the actual message before logging it. +

    +
    +<?xml version="1.0"?>
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +  <proxy name="StockQuoteProxy" startOnLoad="true">
    +    <target>
    +      <inSequence>
    +        <builder/>
    +        <log level="full"/>
    +        <send>
    +          <endpoint name="epr">
    +            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +          </endpoint>
    +        </send>
    +      </inSequence>
    +      <outSequence>
    +        <builder/>
    +        <log level="full"/>
    +        <send/>
    +      </outSequence>
    +    </target>
    +    <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +  </proxy>
    +  <sequence name="fault">
    +    <log level="full">
    +      <property name="MESSAGE" value="Executing default &quot;fault&quot; sequence"/>
    +      <property name="ERROR_CODE" expression="get-property('ERROR_CODE')"/>
    +      <property name="ERROR_MESSAGE" expression="get-property('ERROR_MESSAGE')"/>
    +    </log>
    +    <drop/>
    +  </sequence>
    +  <sequence name="main">
    +    <log/>
    +    <drop/>
    +  </sequence>
    +</definitions>
    +
    +

    + Objective:Demonstrate the Message Relay with Builder mediator. +

    +

    + Prerequisites:Set up is same as sample 655.

    + +
    ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy
    +

    You can see the actual messages going through the proxy by looking at the console because we have + two log mediators in this sample. Becuase we have the builder mediator in place, unlike in sample 655 we have the actual message printed.

    +
    + +

    + Sample 657: Distributed transaction management +

    +

    +   +

    +

    + This sample is similar to sample 655. We have added the builder mediator to build the actual message before logging it. +

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse"
    +             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    +             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">
    +
    +    <sequence name="myFaultHandler">
    +        <log level="custom">
    +            <property name="text" value="** Rollback Transaction**"/>
    +        </log>
    +        <transaction action="rollback"/>
    +        <send/>
    +    </sequence>
    +
    +    <sequence name="main" onError="myFaultHandler">
    +        <in>
    +            <send>
    +                <endpoint>
    +                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                </endpoint>
    +            </send>
    +        </in>
    +
    +        <out>
    +            <transaction action="new"/>
    +
    +            <log level="custom">
    +                <property name="text" value="** Reporting to the Database esbdb**"/>
    +            </log>
    +            <dbreport useTransaction="true" xmlns="http://ws.apache.org/ns/synapse">
    +                <connection>
    +                    <pool>
    +                        <dsName>java:jdbc/XADerbyDS</dsName>
    +                        <icClass>org.jnp.interfaces.NamingContextFactory</icClass>
    +                        <url>localhost:1099</url>
    +                        <user>synapse</user>
    +                        <password>synapse</password>
    +                    </pool>
    +                </connection>
    +                <statement>
    +                    <sql>delete from company where name =?</sql>
    +                    <parameter expression="//m0:return/m1:symbol/child::text()"
    +                               xmlns:m0="http://services.samples"
    +                               xmlns:m1="http://services.samples/xsd"
    +                               type="VARCHAR"/>
    +                </statement>
    +            </dbreport>
    +
    +            <log level="custom">
    +                <property name="text" value="** Reporting to the Database esbdb1**"/>
    +            </log>
    +            <dbreport useTransaction="true" xmlns="http://ws.apache.org/ns/synapse">
    +                <connection>
    +                    <pool>
    +                        <dsName>java:jdbc/XADerbyDS1</dsName>
    +                        <icClass>org.jnp.interfaces.NamingContextFactory</icClass>
    +                        <url>localhost:1099</url>
    +                        <user>synapse</user>
    +                        <password>synapse</password>
    +                    </pool>
    +                </connection>
    +                <statement>
    +                    <sql>INSERT into company values ('IBM','c4',12.0)</sql>
    +                </statement>
    +            </dbreport>
    +            <transaction action="commit"/>
    +            <send/>
    +        </out>
    +    </sequence>
    +
    +</definitions>
    +
    +

    + Objective:Demonstrate the use of the transaction mediator in a distributed transaction +

    +
    + +

    Prerequisites:
    + Start the Synapse configuration numbered 267: i.e. wso2esb-samples -sn 267
    + Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

    +

    + To run this sample it is required to deploy synpase on JBoss application server(This is only tested with JBoss application sever), + you can use the war distribution to deploy synapse on JBoss application server. Use the + synpase_sample_652.xml as the synapse confiuration file and start JBoss with that synpase + configuration file. Also you need to define two XA datasources for above two datasources. + You'll need to refer JBoss documentation to see how to do this.
    It also required to have two database instances, + this will be used by the two XA datasources. Refer the Sample Setup Guide to see how + you can set up the derby database server.
    In this sample a record is delete from one database + and it is added into the second database. If either of the operations(deleting from the + 1st database and adding into the second database) fails everything will be roll backed. + The records will be untouched.
    +

    +

    Invoke the client as follows.

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=SUN/
    + + + \ No newline at end of file diff --git a/docs/xdoc/samples/proxy_samples.xml b/docs/xdoc/samples/proxy_samples.xml new file mode 100644 index 0000000000..8d54e45ef6 --- /dev/null +++ b/docs/xdoc/samples/proxy_samples.xml @@ -0,0 +1,621 @@ + + + + + + + + WSO2 ESB - Proxy Service Samples + + + +

    Running the Proxy Services samples with WSO2 Enterprise Service Bus (ESB)

    + +

    Sample 150: Introduction to proxy services

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <proxy name="StockQuoteProxy">
    +        <target>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +            <outSequence>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +</definitions>
    + +

    Objective: Introduction to ESB proxy services

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 150: i.e. wso2esb-samples -sn 150
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    Once ESB starts, you could go to +http://localhost:8280/services/StockQuoteProxy?wsdl and view the WSDL generated +for the proxy service defined in the configuration. This WSDL is based on the +source WSDL supplied in the proxy service definition, and is updated to +reflect the proxy service EPR.

    + +

    Execute the stock quote client by requesting for a stock quote on the +proxy service as follows:

    +
    ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy
    + +

    An 'inSequence' or 'endpoint' or both of these would decide how the +message would be handled after the proxy service receives the message. In the +above example, the request received is forwarded to the sample service hosted +on Axis2. The 'outSequence' defines how the response is handled before it is +sent back to the client. By default, a proxy service is exposed over all +transports configured for ESB, unless these are specifically mentioned +through the 'transports' attribute.

    + +

    Sample 151: Custom sequences and endpoints with proxy +services

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="proxy_1">
    +        <send>
    +            <endpoint><address uri="http://localhost:9000/services/SimpleStockQuoteService"/></endpoint>
    +        </send>
    +    </sequence>
    +    <sequence name="out">
    +        <send/>
    +    </sequence>
    +    <endpoint name="proxy_2_endpoint">
    +        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +    </endpoint>
    +    <localEntry key="proxy_wsdl" src="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +
    +    <proxy name="StockQuoteProxy1">
    +        <publishWSDL key="proxy_wsdl"/>
    +        <target inSequence="proxy_1" outSequence="out"/>
    +    </proxy>
    +
    +    <proxy name="StockQuoteProxy2">
    +        <publishWSDL key="proxy_wsdl"/>
    +        <target endpoint="proxy_2_endpoint" outSequence="out"/>
    +    </proxy>
    +</definitions>
    + +

    Objective: Using custom sequences and endpoints for message +mediation with proxy services

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 151: i.e. wso2esb-samples -sn 151
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    This configuration creates two proxy services.. The first proxy service +'StockQuoteProxy1' uses the sequence named 'proxy_1' to process incoming +messages and the sequence named "out" to process outgoing responses. The +second proxy service 'StockQuoteProxy2' is set to directly forward messages +that are received to the endpoint named 'proxy_2_endpoint' without any +mediation.

    + +

    You could send a stock quote request to each of these proxy services and +receive the reply generated by the actual service hosted on the Axis2 +instance.

    +
    ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy1
    ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy2
    + +

    Sample 152: Switching transports and message format +from SOAP to REST/POX

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <proxy name="StockQuoteProxy" transports="https">
    +        <target>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService" format="pox"/>
    +            </endpoint>
    +            <outSequence>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +</definitions>
    + +

    Objective: Switching transports and message format from SOAP to REST/POX +

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 152: i.e. wso2esb-samples -sn 152

    + +

    Start the Axis2 server and deploy the SimpleStockQuoteService if not +already done

    + +

    This configuration demonstrates how a proxy service could be exposed on a +subset of available transports, and how it could switch from one transport to +another. This example exposes the created proxy service only on https, and +thus if the user tries to access it over http, would result in a fault.

    +
    ant stockquote -Dtrpurl=http://localhost:8280/services/StockQuoteProxy
    +...
    +     [java] org.apache.axis2.AxisFault: The service cannot be found for the endpoint reference (EPR) /services/StockQuoteProxy
    + +

    Accessing this over https (ant stockquote +-Dtrpurl=https://localhost:8243/services/StockQuoteProxy) causes the proxy +service to access the SimpleStockQuoteService on the sample Axis2 server +using REST/POX. This could be seen if the message exchange was captured using +TCPMon as follows. The REST/POX response is now transformed back into a SOAP +message and returned to the client.

    +
    POST http://localhost:9000/services/SimpleStockQuoteService HTTP/1.1
    +Host: 127.0.0.1
    +SOAPAction: urn:getQuote
    +Content-Type: application/xml; charset=UTF-8;action="urn:getQuote";
    +Transfer-Encoding: chunked
    +Connection: Keep-Alive
    +User-Agent: Synapse-HttpComponents-NIO
    +
    +75
    +<m0:getQuote xmlns:m0="http://services.samples/xsd">
    +   <m0:request>
    +      <m0:symbol>IBM</m0:symbol>
    +   </m0:request>
    +</m0:getQuote>
    +
    HTTP/1.1 200 OK
    +Content-Type: application/xml; charset=UTF-8;action="http://services.samples/SimpleStockQuoteServicePortType/getQuoteResponse";
    +Date: Tue, 24 Apr 2007 14:42:11 GMT
    +Server: Synapse-HttpComponents-NIO
    +Transfer-Encoding: chunked
    +Connection: Keep-Alive
    +
    +2b3
    +<ns:getQuoteResponse xmlns:ns="http://services.samples/xsd">
    +   <ns:return>
    +      <ns:change>3.7730036841862384</ns:change>
    +      <ns:earnings>-9.950236235550818</ns:earnings>
    +      <ns:high>-80.23868444613285</ns:high>
    +      <ns:last>80.50750970812187</ns:last>
    +      <ns:lastTradeTimestamp>Tue Apr 24 20:42:11 LKT 2007</ns:lastTradeTimestamp>
    +      <ns:low>-79.67368355714606</ns:low>
    +      <ns:marketCap>4.502043663670823E7</ns:marketCap>
    +      <ns:name>IBM Company</ns:name>
    +      <ns:open>-80.02229531286982</ns:open>
    +      <ns:peRatio>25.089295161182022</ns:peRatio>
    +      <ns:percentageChange>4.28842665653824</ns:percentageChange>
    +      <ns:prevClose>87.98107059692451</ns:prevClose>
    +      <ns:symbol>IBM</ns:symbol>
    +      <ns:volume>19941</ns:volume>
    +   </ns:return></ns:getQuoteResponse>
    + +

    Sample 153: Routing the messages arrived to a proxy +service without processing the security headers

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <proxy name="StockQuoteProxy">
    +        <target>
    +            <inSequence>
    +		<property name="preserveProcessedHeaders" value="true"/>
    +                <send>
    +                    <endpoint>
    +                        <address uri="http://localhost:9000/services/SecureStockQuoteService"/>
    +                    </endpoint>
    +                </send>
    +            </inSequence>
    +            <outSequence>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +</definitions>
    + +

    Objective: Routing the messages arrived to a proxy service without +processing the MustUnderstand headers (Security header)

    + +

    Prerequisites:
    +You may also need to download and install the unlimited strength policy files +for your JDK before using Apache Rampart (e.g. see +http://java.sun.com/javase/downloads/index_jdk5.jsp)

    + +

    Start the Synapse configuration numbered 153: i.e. wso2esb-samples -sn 153
    +Start the Axis2 server and deploy the SecureStockQuoteService if not already +done

    + +

    The proxy service will receive secure messages with security headers which +are MustUnderstand. But hence element 'engageSec' is not present in the proxy +configuration ESB will not engage that Apache Rampart on this proxy service. +It is expected that an MustUnderstand failure exception on the AxisEngine +would occur before the message arrives ESB. But ESB handles this message and +gets it in by setting all the headers which are MustUnderstand and not +processed to processed state. This will enable ESB to route the messages +without reading the Security headers (just routing the messages from client +to service, both of which are secure). To execute the client, send a stock +quote request to the proxy service, and sign and encrypt the request by +specifying the client side security policy as follows:

    +
    ant stockquote -Dtrpurl=http://localhost:8280/services/StockQuoteProxy -Dpolicy=./../../repository/samples/resources/policy/client_policy_3.xml
    + +

    By following through the debug logs or TCPMon output, you could see that +the request received by the proxy service was signed and encrypted. Also, +looking up the WSDL of the proxy service by requesting the URL +http://localhost:8280/services/StockQuoteProxy?wsdl reveals the security policy +attachments are not there and security is not engaged. When sending the +message to the backend service, you could verify that the security headers +were there as in the original message to ESB from client, and that the +response received does use WS-Security, and forwarded back to the client +without any modification. You should note that this wont be a security hole +because the message inside ESB is signed and encrypted and can only be +forwarded to a secure service to be useful.

    + +

    Sample 154: Load Balancing with Proxy Services

    + +
    +
       <!-- A proxy service with a loadbalace endpoint -->
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <proxy name="LBProxy" transports="https http" startOnLoad="true">
    +        <target faultSequence="errorHandler">
    +            <inSequence>
    +                <send>
    +                    <endpoint>
    +                        <session type="simpleClientSession"/>
    +                        <loadbalance algorithm="org.apache.synapse.endpoints.algorithms.RoundRobin">
    +                            <endpoint>
    +                                <address uri="http://localhost:9001/services/LBService1">
    +                                    <enableAddressing/>
    +                                    <suspendDurationOnFailure>20</suspendDurationOnFailure>
    +                                </address>
    +                            </endpoint>
    +                            <endpoint>
    +                                <address uri="http://localhost:9002/services/LBService1">
    +                                    <enableAddressing/>
    +                                    <suspendDurationOnFailure>20</suspendDurationOnFailure>
    +                                </address>
    +                            </endpoint>
    +                            <endpoint>
    +                                <address uri="http://localhost:9003/services/LBService1">
    +                                    <enableAddressing/>
    +                                    <suspendDurationOnFailure>20</suspendDurationOnFailure>
    +                                </address>
    +                            </endpoint>
    +                        </loadbalance>
    +                    </endpoint>
    +                </send>
    +                <drop/>
    +            </inSequence>
    +            <outSequence>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_2.wsdl"/>
    +    </proxy>
    +    <sequence name="errorHandler">
    +
    +        <makefault>
    +            <code value="tns:Receiver" xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +            <reason value="COULDN'T SEND THE MESSAGE TO THE SERVER."/>
    +        </makefault>
    +
    +        <header name="To" action="remove"/>
    +        <property name="RESPONSE" value="true"/>
    +
    +        <send/>
    +    </sequence>
    +</definitions> 
    +
    + +

    Objective: Load Balancing with Proxy Service

    + +

    Prerequisites:
    +

    + +

    Sample setup is same as LoadBalance endpoints (#53 to #54).

    + +

    Start the Synapse configuration numbered 154: i.e. wso2esb-samples -sn 154
    +Start the Axis2 server and deploy the LoadbalanceFailoverService if not already +done

    + +

    Runs the client with

    +
     ant loadbalancefailover -Dmode=session -Dtrpurl=http://localhost:8280/services/LBProxy
    + +

    Functionality is similar to the sample #54.

    + +

    + Sample 155: Dual channel invocation + on both client side and serverside of synapse with Proxy Services +

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <proxy name="StockQuoteProxy">
    +        <target>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService">
    +                    <enableAddressing separateListener="true"/>
    +                </address>
    +            </endpoint>
    +            <outSequence>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +</definitions>
    +

    + Objective: Demonstrate the dual channel invocation with Synapse proxy services +

    +

    + Prerequisites:
    Start the Synapse + configuration numbered 155: i.e. wso2esb-samples -sn 155
    Start the + Axis2 server and deploy the SimpleStockQuoteService if not already done +

    +

    +

    + This sample will show the action of the dual channel invocation within client and Synapse + as well as within synapse and the actual server. Note that if you want to enable dual + channel invocation you need to set the separateListener attribute to true of the + enableAddressing element of the endpoint. +

    +

    + Execute the stock quote client by requesting for a stock quote on a dual channel from the + proxy service as follows: +

    +
    ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy -Dmode=dualquote
    +

    + In the above example, the request received is forwarded to the sample service + hosted on Axis2 and the endpoint specifies to enable addressing and do the invocation + over a dual channel. If you observe this message flow by using a TCPmon, you could see that + on the channel you send the request to synapse the response has been written as an + HTTP 202 Accepted, where as the real response from synapse will come over a different channel + which cannot be obsesrved unless you use tcpdump to dump all the TCP level messages. +

    +

    + At the same time you can observe the behaviour of the invocation between synapse and + the actual Axis2 service, where you can see a 202 Accepted message being delivered to synapse + as the response to the request. The actual response will be delivered to synapse over a + different channel. +

    + +

    + Sample 156: Service Integration with specifying the receiving sequence +

    +
    <?xml version="1.0" encoding="UTF-8"?>
    +
    +<!-- Service Integration with specifying the receiving sequence -->
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <localEntry key="sec_policy" src="file:repository/conf/sample/resources/policy/policy_3.xml"/>
    +
    +    <proxy name="StockQuoteProxy">
    +        <target>
    +            <inSequence>
    +                <enrich>
    +                    <source type="body"/>
    +                    <target type="property" property="REQUEST"/>
    +                </enrich>
    +
    +                <send receive="SimpleServiceSeq">
    +                    <endpoint name="secure">
    +                        <address uri="http://localhost:9000/services/SecureStockQuoteService">
    +                            <enableSec policy="sec_policy"/>
    +                        </address>
    +                    </endpoint>
    +                </send>
    +            </inSequence>
    +            <outSequence>
    +                <drop/>
    +            </outSequence>
    +        </target>
    +    </proxy>
    +
    +
    +    <sequence name="SimpleServiceSeq">
    +        <property name="SECURE_SER_AMT" expression="//ns:getQuoteResponse/ns:return/ax21:last"
    +                xmlns:ns="http://services.samples" xmlns:ax21="http://services.samples/xsd"/>
    +        <log level="custom">
    +            <property name="SecureStockQuoteService-Amount" expression="get-property('SECURE_SER_AMT')"/>
    +        </log>
    +        <enrich>
    +            <source type="body"/>
    +            <target type="property" property="SecureService_Res"/>
    +        </enrich>
    +        <enrich>
    +            <source type="property" property="REQUEST"/>
    +            <target type="body"/>
    +        </enrich>
    +        <send receive="ClientOutSeq">
    +            <endpoint name="SimpleStockQuoteService">
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +        </send>
    +    </sequence>
    +
    +    <sequence name="ClientOutSeq">
    +        <property name="SIMPLE_SER_AMT" expression="//ns:getQuoteResponse/ns:return/ax21:last"
    +                       xmlns:ns="http://services.samples" xmlns:ax21="http://services.samples/xsd"/>
    +        <log level="custom">
    +            <property name="SimpleStockQuoteService-Amount" expression="get-property('SIMPLE_SER_AMT')"/>
    +        </log>
    +        <enrich>
    +            <source type="body"/>
    +            <target type="property" property="SimpleService_Res"/>
    +        </enrich>
    +
    +        <filter xpath="fn:number(get-property('SIMPLE_SER_AMT')) > fn:number(get-property('SECURE_SER_AMT'))">
    +            <then>
    +                <log>
    +                    <property name="StockQuote" value="SecureStockQuoteService"/>
    +                </log>
    +                <enrich>
    +                    <source type="property" property="SecureService_Res"/>
    +                    <target type="body"/>
    +                </enrich>
    +            </then>
    +            <else>
    +                <log>
    +                    <property name="StockQuote" value="SimpleStockQuoteService"/>
    +                </log>
    +            </else>
    +        </filter>
    +
    +        <send/>
    +    </sequence>
    +
    +</definitions>
    +

    + Objective: Using synapse to integrate services. +

    +

    + Prerequisites:
    We will be using two services in this sample; + i.e. SimpleStockQuoteService and SecureStockQuoteService. Therefore the prerequisites + of sample 100 is also applied here. +

    +

    Start the Synapse + configuration numbered 156: i.e. wso2esb-samples -sn 156
    Start the + Axis2 server and deploy the SimpleStockQuoteService if not already done. +

    +

    + This sample contains a proxy service which provides the seamless integration of + SimpleStockQuoteService and SecureStockQuoteService. Once a client send a + request to this proxy service, it sends the same request to both these services + and resolve the service with cheapest stock quote price. +

    +

    + Execute the stock quote client by requesting for a cheapest stock quote + from the proxy service as follows: +

    +
    ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy
    +

    + Above sample uses the concept of specifying the receiving sequence in the + send mediator. In this case once the message is sent from the in sequence + then the response won't come to out sequence as the receiving sequence is + specified in the send mediator. +

    + + +

    + Sample 157: Conditional Router for Routing Messages based on HTTP URL, HTTP Headers and Query Parameters +

    +
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <proxy name="StockQuoteProxy" transports="https http local" startOnLoad="true" trace="disable">
    +        <target>
    +            <inSequence>
    +                <conditionalRouter continueAfter="false">
    +                    <conditionalRoute breakRoute="false">
    +                        <condition>
    +                            <match xmlns="" type="header" source="foo" regex="bar.*"/>
    +                        </condition>
    +                        <target sequence="cnd1_seq"/>
    +                    </conditionalRoute>
    +
    +                    <conditionalRoute breakRoute="false">
    +                        <condition>
    +                            <and xmlns="">
    +                                <match type="header" source="my_custom_header1" regex="foo.*"/>
    +                                <match type="url" regex="/services/StockQuoteProxy.*"/>
    +                            </and>
    +                        </condition>
    +                        <target sequence="cnd2_seq"/>
    +                    </conditionalRoute>
    +
    +                    <conditionalRoute breakRoute="false">
    +                        <condition>
    +                            <and xmlns="">
    +                                <match type="header" source="my_custom_header2" regex="bar.*"/>
    +                                <equal type="param" source="qparam1" value="qpv_foo"/>
    +                                <or>
    +                                    <match type="url" regex="/services/StockQuoteProxy.*"/>
    +                                    <match type="header" source="my_custom_header3" regex="foo.*"/>
    +                                </or>
    +                                <not>
    +                                    <equal type="param" source="qparam2" value="qpv_bar"/>
    +                                </not>
    +                            </and>
    +                        </condition>
    +                        <target sequence="cnd3_seq"/>
    +                    </conditionalRoute>
    +                </conditionalRouter>
    +            </inSequence>
    +            <outSequence>
    +                <send/>
    +            </outSequence>
    +        </target>
    +    </proxy>
    +
    +    <sequence name="cnd1_seq">
    +        <log level="custom">
    +            <property name="MSG_FLOW" value="Condition (I) Satisfied"/>
    +        </log>
    +        <sequence key="send_seq"/>
    +    </sequence>
    +    <sequence name="cnd2_seq">
    +        <log level="custom">
    +            <property name="MSG_FLOW" value="Condition (II) Satisfied"/>
    +        </log>
    +        <sequence key="send_seq"/>
    +    </sequence>
    +    <sequence name="cnd3_seq">
    +        <log level="custom">
    +            <property name="MSG_FLOW" value="Condition (III) Satisfied"/>
    +        </log>
    +        <sequence key="send_seq"/>
    +    </sequence>
    +
    +    <sequence name="send_seq">
    +        <log level="custom">
    +            <property name="DEBUG" value="Condition Satisfied"/>
    +        </log>
    +        <send>
    +            <endpoint name="simple">
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +        </send>
    +    </sequence>
    +</definitions>
    +
    +    
    +

    + Objective: Routing Messages based on the HTTP Transport properties. +

    +

    + Prerequisites:
    Start the Synapse configuration numbered 157: i.e. wso2esb-samples -sn 157 +
    Start the Axis2 server and deploy the SimpleStockQuoteService if not already done. + For this particular case we will be using 'curl' to send requests with custom HTTP Headers to the proxy service. You may use a similar tool with facilitate those requirements. +

    The request file : stockQuoteReq.xml, should contain the following request. +

    +
    <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:ser="http://services.samples" xmlns:xsd="http://services.samples/xsd">
    +   <soap:Header/>
    +   <soap:Body>
    +      <ser:getQuote>
    +         <ser:request>
    +            <xsd:symbol>IBM</xsd:symbol>
    +         </ser:request>
    +      </ser:getQuote>
    +   </soap:Body>
    +</soap:Envelope>
    + +

    + Condition I : Matching HTTP Header
    +

    +
    curl -d @stockQuoteReq.xml -H "Content-Type: application/soap+xml;charset=UTF-8" -H "foo:bar" "http://localhost:8280/services/StockQuoteProxy"
    +    
    + +

    + Condition II : Matching HTTP Header AND Url
    +

    +
    curl -d @stockQuoteReq.xml -H "Content-Type: application/soap+xml;charset=UTF-8" -H "my_custom_header1:foo1" "http://localhost:8280/services/StockQuoteProxy"
    + +

    + Condition III : Complex conditions with AND, OR and NOT
    +

    +
    curl -d @stockQuoteReq.xml -H "Content-Type: application/soap+xml;charset=UTF-8" -H "my_custom_header2:bar" -H "my_custom_header3:foo" "http://localhost:8280/services/StockQuoteProxy?qparam1=qpv_foo&qparam2=qpv_foo2"
    + + + diff --git a/docs/xdoc/samples/qos_mediation_samples.xml b/docs/xdoc/samples/qos_mediation_samples.xml new file mode 100644 index 0000000000..51d7393c11 --- /dev/null +++ b/docs/xdoc/samples/qos_mediation_samples.xml @@ -0,0 +1,372 @@ + + + + + + + + WSO2 ESB - QoS Samples + + + +

    Running the QoS addition and deduction samples with WSO2 ESB

    + +

    Sample 100: Using WS-Security for outgoing messages +

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <localEntry key="sec_policy" src="file:repository/samples/resources/policy/policy_3.xml"/>
    +
    +    <in>
    +        <send>
    +            <endpoint name="secure">
    +                <address uri="http://localhost:9000/services/SecureStockQuoteService">
    +                    <enableSec policy="sec_policy"/>
    +                    <enableAddressing/>
    +                </address>
    +            </endpoint>
    +        </send>
    +    </in>
    +    <out>
    +        <header name="wsse:Security" action="remove"
    +                xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"/>
    +        <send/>
    +    </out>
    +</definitions>
    + +

    Objective: Connecting to endpoints with WS-Security for outgoing +messages

    + +

    Prerequisites:
    +

    + +

    You may also need to download and install the unlimited strength policy +files for your JDK before using Apache Rampart (e.g. see +http://java.sun.com/javase/downloads/index_jdk5.jsp)

    + +

    Start the Synapse configuration numbered 100: i.e. wso2esb-samples -sn 100
    +Start the Axis2 server and deploy the SecureStockQuoteService if not already +done

    + +

    Use the stock quote client to send a request without WS-Security. ESB is +configured to enable WS-Security as per the policy specified by +'policy_3.xml' for the outgoing messages to the SecureStockQuoteService +endpoint hosted on the Axis2 instance. The debug log messages on ESB shows +the encrypted message flowing to the service and the encrypted response being +received by ESB. The wsse:Security header is then removed from the decrypted +message and the response is delivered back to the client, as expected. You +may execute the client as follows:

    +
    ant stockquote -Dtrpurl=http://localhost:8280/
    + +

    The message sent by ESB to the secure service can be seen as follows, when +TCPMon is used.

    +
    POST http://localhost:9001/services/SecureStockQuoteService HTTP/1.1
    +Host: 127.0.0.1
    +SOAPAction: urn:getQuote
    +Content-Type: text/xml; charset=UTF-8
    +Transfer-Encoding: chunked
    +Connection: Keep-Alive
    +User-Agent: Synapse-HttpComponents-NIO
    +
    +800
    +<?xml version='1.0' encoding='UTF-8'?>
    +   <soapenv:Envelope xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:wsa="http://www.w3.org/2005/08/addressing" ..>
    +      <soapenv:Header>
    +         <wsse:Security ..>
    +            <wsu:Timestamp ..>
    +               ...
    +            </wsu:Timestamp>
    +            <xenc:EncryptedKey..>
    +               ...
    +            </xenc:EncryptedKey>
    +            <wsse:BinarySecurityToken ...>
    +               <ds:SignedInfo>
    +               ...
    +               </ds:SignedInfo>
    +               <ds:SignatureValue>
    +               ...
    +               </ds:SignatureValue>
    +               <ds:KeyInfo Id="KeyId-29551621">
    +                  ...
    +               </ds:KeyInfo>
    +            </ds:Signature>
    +         </wsse:Security>
    +         <wsa:To>http://localhost:9001/services/SecureStockQuoteService</wsa:To>
    +         <wsa:MessageID>urn:uuid:1C4CE88B8A1A9C09D91177500753443</wsa:MessageID>
    +         <wsa:Action>urn:getQuote</wsa:Action>
    +      </soapenv:Header>
    +      <soapenv:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="Id-3789605">
    +         <xenc:EncryptedData Id="EncDataId-3789605" Type="http://www.w3.org/2001/04/xmlenc#Content">
    +            <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc" />
    +            <xenc:CipherData>
    +                <xenc:CipherValue>Layg0xQcnH....6UKm5nKU6Qqr</xenc:CipherValue>
    +            </xenc:CipherData>
    +         </xenc:EncryptedData>
    +      </soapenv:Body>
    +   </soapenv:Envelope>0
    + +

    Sample 101: Reliable message exchange between ESB and +the back-end server using WS-ReliableMessaging

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <in>
    +        <RMSequence single="true" version="1.0"/>
    +        <send>
    +           <endpoint name="reliable">
    +              <address uri="http://localhost:9000/services/ReliableStockQuoteService">
    +                 <enableRM/>
    +                 <enableAddressing/>
    +              </address>
    +           </endpoint>
    +        </send>
    +    </in>
    +    <out>
    +        <header name="wsrm:SequenceAcknowledgement" action="remove"
    +                xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm"/>
    +        <header name="wsrm:Sequence" action="remove"
    +                xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm"/>
    +        <header name="wsrm:AckRequested" action="remove"
    +                xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm"/>
    +        <send/>
    +    </out>
    +
    +</definitions>
    + +

    Objective: Demonstrate the message exchange between ESB and the +server using WS-ReliableMessaging (WS-RM)

    + +

    Prerequisites:

    + +

    Deploy the ReliableStockQuoteService in the sample Axis2 server by +switching to the samples/axis2Server/src/ReliableStockQuoteService directory +and running ant.

    + +

    Start the sample Axis2 server on port 9000.

    + +

    Start ESB with the sample configuration 101 (i.e. wso2esb-samples -sn 101). +

    + +

    In the above configuration, WS-RM is engaged to the endpoint using the +<enableRM/> tag. It is possible to engage WS-RM to both Address and +WSDL endpoints using this tag. In addition to the RM enabled endpoint, +RMSequence mediator is specified before the send mediator. This mediator is +used to specify the set of messages to be sent using a single RM sequence. In +this sample it is specified as single message per sequence. It also specifies +the version of the WS-RM to be used. Refer to the ESB configuration language +documentation for more information about the RMSequence mediator. RM related +SOAP headers are removed from the message in the out mediator as WS-RM +message exchange happens only between the ESB and the server. Now run the +sample client using the following command.

    +
    ant stockquote -Dsymbol=IBM -Dmode=quote -Daddurl=http://localhost:8280
    + +

    You can observe the client output displaying the quote price for IBM as +follows:

    +
    [java] Standard :: Stock price = $189.2521262517493
    + +

    There is no difference to be observed between the normal message exchange +and WS-RM enabled message exchange as far as client and server outputs are +considered. But if you look at the wire level messages, you would observe +additional WS-RM messages and WS-RM elements. ESB, the initiator of the RM +sequence, first try to create a sequence by sending a message with +CreateSequence element.

    +
    ...
    +<soapenv:Body>
    +   <wsrm:CreateSequence xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm">
    +      <wsrm:AcksTo>
    +         <wsa:Address>http://www.w3.org/2005/08/addressing/anonymous</wsa:Address>
    +      </wsrm:AcksTo>
    +      <wsrm:Offer>
    +         <wsrm:Identifier>urn:uuid:546F6F33FB7D8BBE351179807372769</wsrm:Identifier>
    +      </wsrm:Offer>
    +   </wsrm:CreateSequence>
    +</soapenv:Body>
    +...
    + +

    Sample Axis2 server responds to CreateSequence request with the following +message:

    +
    ...
    +<soapenv:Body>
    +   <wsrm:CreateSequenceResponse xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm">
    +      <wsrm:Identifier>urn:uuid:879853A6871A66641C1179807373270</wsrm:Identifier>
    +      <wsrm:Accept>
    +         <wsrm:AcksTo>
    +            <wsa:Address>http://localhost:9000/services/ReliableStockQuoteService</wsa:Address>
    +         </wsrm:AcksTo>
    +      </wsrm:Accept>
    +   </wsrm:CreateSequenceResponse>
    +</soapenv:Body>
    +...
    + +

    Once the sequence is established, ESB sends the request to the server with +the pre-negotiated sequence ID.

    +
    <soapenv:Envelope xmlns:wsa="http://www.w3.org/2005/08/addressing"
    +                  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    +    <soapenv:Header>
    +        <wsa:To>http://localhost:9000/services/ReliableStockQuoteService</wsa:To>
    +        <wsa:MessageID>urn:uuid:DB9A5257B637DDA38B1179807372560712002-1515891720</wsa:MessageID>
    +        <wsa:Action>urn:getQuote</wsa:Action>
    +        <wsrm:Sequence xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm"
    +                       soapenv:mustUnderstand="1">
    +            <wsrm:Identifier>urn:uuid:879853A6871A66641C1179807373270</wsrm:Identifier>
    +            <wsrm:MessageNumber>1</wsrm:MessageNumber>
    +            <wsrm:LastMessage/>
    +        </wsrm:Sequence>
    +    </soapenv:Header>
    +    <soapenv:Body>
    +        <m0:getQuote xmlns:m0="http://services.samples/xsd">
    +            <m0:request>
    +                <m0:symbol>IBM</m0:symbol>
    +            </m0:request>
    +        </m0:getQuote>
    +    </soapenv:Body>
    +</soapenv:Envelope>
    + +

    ESB keeps on sending above message till the server responds with a valid +response message with 200 OK HTTP header. If the server is not ready with a +response, it will respond with 202 Accepted HTTP header for all requests. +Once the server is ready with a response it will send the response message +with sequence ID as follows.

    +
    <soapenv:Envelope xmlns:wsa="http://www.w3.org/2005/08/addressing"
    +                  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    +    <soapenv:Header>
    +        <wsa:MessageID>urn:uuid:879853A6871A66641C1179807373804</wsa:MessageID>
    +        <wsa:Action>http://services.samples/ReliableStockQuoteServicePortType/getQuoteResponse
    +        </wsa:Action>
    +        <wsa:RelatesTo>urn:uuid:DB9A5257B637DDA38B1179807372560712002-1515891720</wsa:RelatesTo>
    +        <wsrm:Sequence xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm"
    +                       soapenv:mustUnderstand="1">
    +            <wsrm:Identifier>urn:uuid:546F6F33FB7D8BBE351179807372769</wsrm:Identifier>
    +            <wsrm:MessageNumber>1</wsrm:MessageNumber>
    +            <wsrm:LastMessage/>
    +        </wsrm:Sequence>
    +        <wsrm:SequenceAcknowledgement xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm"
    +                                      soapenv:mustUnderstand="1">
    +            <wsrm:Identifier>urn:uuid:879853A6871A66641C1179807373270</wsrm:Identifier>
    +            <wsrm:AcknowledgementRange Lower="1" Upper="1"/>
    +        </wsrm:SequenceAcknowledgement>
    +    </soapenv:Header>
    +    <soapenv:Body>
    +        <ns:getQuoteResponse xmlns:ns="http://services.samples/xsd">
    +...
    + +

    Now both ESB and the server are done with the actual message exchange. +Then ESB sends a request to terminate the sequence as follows:

    +
    <soapenv:Envelope xmlns:wsa="http://www.w3.org/2005/08/addressing"
    +                  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    +    <soapenv:Header>
    +        <wsa:To>http://localhost:9000/services/ReliableStockQuoteService</wsa:To>
    +        <wsa:MessageID>urn:uuid:546F6F33FB7D8BBE351179807379591</wsa:MessageID>
    +        <wsa:Action>http://schemas.xmlsoap.org/ws/2005/02/rm/TerminateSequence</wsa:Action>
    +        <wsrm:SequenceAcknowledgement xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm"
    +                                      soapenv:mustUnderstand="1">
    +            <wsrm:Identifier>urn:uuid:546F6F33FB7D8BBE351179807372769</wsrm:Identifier>
    +            <wsrm:AcknowledgementRange Lower="1" Upper="1"/>
    +        </wsrm:SequenceAcknowledgement>
    +    </soapenv:Header>
    +    <soapenv:Body>
    +        <wsrm:TerminateSequence xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm">
    +            <wsrm:Identifier>urn:uuid:879853A6871A66641C1179807373270</wsrm:Identifier>
    +        </wsrm:TerminateSequence>
    +    </soapenv:Body>
    +</soapenv:Envelope>
    + +

    Server responds to the sequence termination message, accepting to +terminate the sequence as follows.

    +
    <soapenv:Envelope xmlns:wsa="http://www.w3.org/2005/08/addressing"
    +                  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    +    <soapenv:Header>
    +        <wsa:ReplyTo>
    +            <wsa:Address>http://localhost:9000/services/ReliableStockQuoteService</wsa:Address>
    +        </wsa:ReplyTo>
    +        <wsa:MessageID>urn:uuid:879853A6871A66641C1179807380190</wsa:MessageID>
    +        <wsa:Action>http://schemas.xmlsoap.org/ws/2005/02/rm/TerminateSequence</wsa:Action>
    +    </soapenv:Header>
    +    <soapenv:Body>
    +        <wsrm:TerminateSequence xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm">
    +            <wsrm:Identifier>urn:uuid:546F6F33FB7D8BBE351179807372769</wsrm:Identifier>
    +        </wsrm:TerminateSequence>
    +    </soapenv:Body>
    +</soapenv:Envelope>
    + +

    Note that although each of above messages are separate SOAP messages, in +most cases they will be exchanged in a single socket connection as HTTP +Keep-Alive header is used.

    + +

    Sample 102: Reliable message exchange between ESB and +the back-end server using WS-ReliableMessaging 1.1

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <in>
    +        <RMSequence single="true" version="1.1"/>
    +        <send>
    +            <endpoint name="reliable">
    +    		<address uri="http://localhost:9000/services/ReliableStockQuoteService">
    +	   	    <enableRM/>
    +		    <enableAddressing/>
    +                </address>
    +            </endpoint>
    +        </send>
    +    </in>
    +    <out>
    +        <header name="wsrm:SequenceAcknowledgement" action="remove"
    +                xmlns:wsrm="http://docs.oasis-open.org/ws-rx/wsrm/200702"/>
    +        <header name="wsrm:Sequence" action="remove"
    +                xmlns:wsrm="http://docs.oasis-open.org/ws-rx/wsrm/200702"/>
    +        <header name="wsrm:AckRequested" action="remove"
    +                xmlns:wsrm="http://docs.oasis-open.org/ws-rx/wsrm/200702"/>
    +        <send/>
    +    </out>
    +</definitions>
    + +

    Objective: Demonstrate the message exchange between ESB and the +server using WS-ReliableMessaging 1.1 Specification (WS-RM).This sample is similar + to sample 101 except it uses the RM 1.1 for the communication.

    + +

    Prerequisites:

    + +

    Deploy the ReliableStockQuoteService in the sample Axis2 server by +switching to the samples/axis2Server/src/ReliableStockQuoteService directory +and running ant.

    + +

    Start the sample Axis2 server on port 9000.

    + +

    Start ESB with the sample configuration 102 (i.e. wso2esb-samples -sn 102). +

    + +

    In the above configuration, WS-RM is engaged to the endpoint using the +<enableRM/> tag. It is possible to engage WS-RM to both Address and +WSDL endpoints using this tag. In addition to the RM enabled endpoint, +RMSequence mediator is specified before the send mediator. This mediator is +used to specify the set of messages to be sent using a single RM sequence. Also it specifies the RM version. In +this sample it is specified as single message per sequence. It also specifies +the version of the WS-RM to be used. Refer to the ESB configuration language +documentation for more information about the RMSequence mediator. RM related +SOAP headers are removed from the message in the out mediator as WS-RM +message exchange happens only between the ESB and the server. Now run the +sample client using the following command.

    +
    ant stockquote -Dsymbol=IBM -Dmode=quote -Daddurl=http://localhost:8280
    + +

    You can observe the client output displaying the quote price for IBM as +follows:

    +
    [java] Standard :: Stock price = $189.2521262517493
    +

    You can observer the set of messages exchnaged between ESB and back end service using a tool like TCPMon

    + + + \ No newline at end of file diff --git a/docs/xdoc/samples/qos_proxy_samples.xml b/docs/xdoc/samples/qos_proxy_samples.xml new file mode 100644 index 0000000000..03d7b98240 --- /dev/null +++ b/docs/xdoc/samples/qos_proxy_samples.xml @@ -0,0 +1,194 @@ + + + + + + + + WSO2 ESB - QoS Proxy Service Samples + + + +

    Running QoS addition and deduction proxy service samples with WSO2 ESB

    +

    Sample 200: Using WS-Security with policy attachments +for proxy services

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <localEntry key="sec_policy" src="file:repository/samples/resources/policy/policy_3.xml"/>
    +    <proxy name="StockQuoteProxy">
    +        <target>
    +            <inSequence>
    +                <header name="wsse:Security" action="remove"
    +                        xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"/>
    +                <send>
    +                    <endpoint>
    +                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                    </endpoint>
    +                </send>
    +            </inSequence>
    +            <outSequence>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +        <policy key="sec_policy"/>
    +        <enableSec/>
    +    </proxy>
    +</definitions>
    + +

    Objective: Using WS-Security signing and encryption with proxy +services through WS-Policy

    + +

    Prerequisites:
    +You may also need to download and install the unlimited strength policy files +for your JDK before using Apache Rampart (e.g. see +http://java.sun.com/javase/downloads/index_jdk5.jsp)

    + +

    Start the Synapse configuration numbered 200: i.e. wso2esb-samples -sn 200
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    The proxy service expects to receive a signed and encrypted message as +specified by the security policy. Please see Apache Rampart and Axis2 +documentation on the format of the policy file. The element 'engageSec' +specifies that Apache Rampart should be engaged on this proxy service. Hence +if Rampart rejects any request messages that does not conform to the +specified policy, those messages will never reach the 'inSequence' to be +processed. Since the proxy service is forwarding the received request to the +simple stock quote service that does not use WS-Security, we are instructing +ESB to remove the wsse:Security header from the outgoing message. To execute +the client, send a stock quote request to the proxy service, and sign and +encrypt the request by specifying the client side security policy as follows: +

    +
    ant stockquote -Dtrpurl=http://localhost:8280/services/StockQuoteProxy -Dpolicy=./../../repository/samples/resources/policy/client_policy_3.xml
    + +

    By following through the debug logs or TCPMon output, you could see that +the request received by the proxy service was signed and encrypted. Also, +looking up the WSDL of the proxy service by requesting the +URLhttp://localhost:8280/services/StockQuoteProxy?wsdl reveals the security +policy attachment to the supplied base WSDL. When sending the message to the +backend service, you could verify that the security headers were removed, and +that the response received does not use WS-Security, but that the response +being forwarded back to the client is signed and encrypted as expected by the +client.

    + +

    Sample 201: Reliable message exchange between the +client and proxy services using WS-ReliableMessaging

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <proxy name="StockQuoteProxy">
    +        <target>
    +            <inSequence>
    +                <header name="wsrm:SequenceAcknowledgement" action="remove"
    +                        xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm"/>
    +                <header name="wsrm:Sequence" action="remove"
    +                        xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm"/>
    +                <send>
    +                    <endpoint>
    +                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                    </endpoint>
    +                </send>
    +            </inSequence>
    +            <outSequence>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +        <enableRM/>
    +    </proxy>
    +</definitions>
    + +

    Objective: Demonstrate the reliable message exchange between the +client and ESB using WS-ReliableMessaging (WS-RM)

    + +

    Prerequisites:

    + +

    Deploy the SimpleStockQuoteService in the sample Axis2 server and start it +on port 9000.

    + +

    Start ESB with the sample configuration number 201 (i.e. wso2esb-samples -sn 201).

    + +

    In the above configuration, a proxy service is created with WS-RM enabled +using the <enableRM/> tag. Therefore, this proxy service is capable of +communicating with a WS-RM client. It also removes the WS-RM headers in the +In Sequence before the message is sent to the back end server. This is +required as the reliable messaging is applicable only between the client and +ESB. Now start the client with WS-RM as follows:

    +
    ant stockquote -Dsymbol=IBM -Dmode=quote -Daddurl=http://localhost:8280/services/StockQuoteProxy -Dwsrm=true
    + +

    In this case, client sends WS-RM enabled request to ESB where ESB sends +normal request to the server. This can be observed by examining the wire +level messages between the client and ESB. These messages would be similar to +the wire level messages shown in sample 101. Each message would perform a +similar function to the messages discussed in sample 53.

    + +

    Sample 202: Reliable message exchange between the +client and proxy services using WS-ReliableMessaging 1.1

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <proxy name="StockQuoteProxy">
    +        <target>
    +            <inSequence>
    +                <header name="wsrm:SequenceAcknowledgement" action="remove"
    +                        xmlns:wsrm="http://docs.oasis-open.org/ws-rx/wsrm/200702"/>
    +                <header name="wsrm:Sequence" action="remove"
    +                        xmlns:wsrm="http://docs.oasis-open.org/ws-rx/wsrm/200702"/>
    +                <header name="wsrm:AckRequested" action="remove"
    +                        xmlns:wsrm="http://docs.oasis-open.org/ws-rx/wsrm/200702"/>
    +                <send>
    +                    <endpoint>
    +                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                    </endpoint>
    +                </send>
    +            </inSequence>
    +			<outSequence>
    +				<send/>
    +			</outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +        <enableRM/>
    +    </proxy>
    +</definitions>
    +
    + +

    Objective: Demonstrate the reliable message exchange between the +client and ESB using WS-ReliableMessaging (WS-RM)

    + +

    Prerequisites:

    + +

    Deploy the SimpleStockQuoteService in the sample Axis2 server and start it +on port 9000.

    + +

    Start ESB with the sample configuration number 202 (i.e. wso2esb-samples -sn 202).

    + +

    In the above configuration, a proxy service is created with WS-RM enabled +using the <enableRM/> tag. Therefore, this proxy service is capable of +communicating with a WS-RM client. It also removes the WS-RM 1.1 headers in the +In Sequence before the message is sent to the back end server. This is +required as the reliable messaging is applicable only between the client and +ESB. Now start the client with WS-RM as follows:

    +
    ant stockquote -Dsymbol=IBM -Dmode=quote -Daddurl=http://localhost:8280/services/StockQuoteProxy -Dwsrm11=true
    + +

    In this case, client sends WS-RM enabled request to ESB where ESB sends +normal request to the server. This can be observed by examining the wire +level messages between the client and ESB. These messages would be similar to +the wire level messages shown in sample 102. Each message would perform a +similar function to the messages discussed in sample 53.

    + + \ No newline at end of file diff --git a/docs/xdoc/samples/rest_api_samples.xml b/docs/xdoc/samples/rest_api_samples.xml new file mode 100644 index 0000000000..b7007b9275 --- /dev/null +++ b/docs/xdoc/samples/rest_api_samples.xml @@ -0,0 +1,102 @@ + + + + + + + + WSO2 ESB - REST API Samples + + + +

    Running the REST API Samples with WSO2 Enterprise Service Bus (ESB)

    +

    Sample 800: Introduction to REST API

    +
    <!-- An empty flat synapse configuration shipped with the WSO2 ESB -->
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <!-- You can add any flat sequences, endpoints, etc.. to this synapse.xml file if you do
    +    *not* want to keep the artifacts in several files -->
    +<api name="StockQuoteAPI" context="/stockquote">
    +   <resource uri-template="/view/{symbol}" methods="GET">
    +      <inSequence>
    +         <payloadFactory>
    +	    <format>
    +		<m0:getQuote xmlns:m0="http://services.samples">
    +	            <m0:request>
    +        	       <m0:symbol>$1</m0:symbol>
    +	            </m0:request>
    +        	 </m0:getQuote>
    +	    </format>
    +	    <args>
    +		<arg expression="get-property('uri.var.symbol')"/>
    +	    </args>
    +	 </payloadFactory>
    +	 <send>
    +	    <endpoint>
    +		<address uri="http://localhost:9000/services/SimpleStockQuoteService" format="soap11"/>
    +	    </endpoint>
    +	 </send>
    +      </inSequence>
    +      <outSequence>
    +	 <send/>
    +      </outSequence>
    +   </resource>
    +   <resource url-pattern="/order/*" methods="POST">
    +      <inSequence>
    +        <property name="FORCE_SC_ACCEPTED" value="true" scope="axis2"/>
    +	<property name="OUT_ONLY" value="true"/>
    +	<send>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService" format="soap11"/>
    +            </endpoint>
    +         </send>
    +      </inSequence>      
    +   </resource>
    +</api>
    +</definitions>
    + +

    Objective: Introduction to REST API

    + +

    Prerequisites:
    +Start the Axis2 server and deploy the SimpleStockQuoteService
    +Start the Synapse configuration numbered 800: i.e. wso2esb-samples -sn 800
    +You might need a REST client like curl to test this

    +
    curl -v http://127.0.0.1:8280/stockquote/view/IBM
    +
    curl -v http://127.0.0.1:8280/stockquote/view/MSFT
    + +

    The above GET calls will be handled by the first resource in the StockQuoteAPI. These REST calls will get converted into SOAP calls and will be sent to the Axis2 server. Response will be sent to the client in POX format.

    + +

    The following command POSTs a simple XML to the ESB. Save following sample place order request as "placeorder.xml" file in your local file system and execute the command. That is used to invoke a SOAP service. ESB returns the 202 response back to the client.

    + +
    curl -v -d @placeorder.xml -H "Content-type: application/xml" http://127.0.0.1:8280/stockquote/order/
    + +
    +<placeOrder xmlns="http://services.samples">
    +  <order>
    +     <price>50</price>
    +     <quantity>10</quantity>
    +     <symbol>IBM</symbol>
    +  </order>
    +</placeOrder>
    +
    + + + diff --git a/docs/xdoc/samples/rule_samples.xml b/docs/xdoc/samples/rule_samples.xml new file mode 100644 index 0000000000..91c009810f --- /dev/null +++ b/docs/xdoc/samples/rule_samples.xml @@ -0,0 +1,954 @@ + + + + + + + WSO2 ESB - Rule Samples + + + +

    Running the Rule samples with WSO2 Enterprise Service Bus (ESB)

    + +

    Introduction

    + +

    Rule mediator integrates the WSO2 rules component into the WSO2 ESB to +provide you with a suitable capability to define your organization's +dynamic integration decisions in terms of rules.This guide provides you with a +seven samples, which are quite simple. The goal of the samples is to make you +an expertise in using rule mediator. Please follow the configuration guide of +the rule mediator before proceeding with the samples if you have not already +done so.

    + +

    Sample 600 : Rule Mediator as a Filter - Simple Rule Based +Routing

    +
    <!-- Simple rule based routing  of messages - same as filter mediator -->
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <in>
    +        <rule>
    +            <ruleset >
    +                <source>
    +                    <package name="SimpleRoutingRules"
    +                             xmlns="http://drools.org/drools-5.0"
    +                             xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
    +                             xs:schemaLocation="http://drools.org/drools-5.0 drools-4.0.xsd">
    +                        <import name="org.apache.synapse.MessageContext"/>
    +                        <rule name="Invoke IBM ">
    +                            <lhs>
    +                                <pattern object-type="MessageContext" identifier="mc"></pattern>
    +                                <pattern object-type="String" identifier="symbol"></pattern>
    +                                <eval>symbol.equals("IBM")</eval>
    +                            </lhs>
    +                            <rhs>mc.setProperty("execute_children","true");</rhs>
    +                        </rule>
    +                    </package>
    +                </source>
    +                <creation>
    +                    <property name="source" value="xml"/>
    +                </creation>
    +            </ruleset>
    +            <session type="stateless"/>
    +            <facts>
    +                <fact name="mc" type="context"/>
    +                <fact name="symbol" type="java.lang.String"
    +                      expression="//m0:getQuote/m0:request/m0:symbol/child::text()"
    +                      xmlns:m0="http://services.samples"/>
    +            </facts>
    +            <childMediators>
    +                <send>
    +                    <endpoint>
    +                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                    </endpoint>
    +                </send>
    +                <drop/>
    +            </childMediators>
    +        </rule>
    +    </in>
    +    <out>
    +        <send/>
    +    </out>
    +
    +</definitions>
    +
    + +

    Objective: Introduction to simple rule based routing

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 600: (i.e. ./wso2esb-samples.sh -sn +600)

    + +

    Start the Axis2 server and deploy the SimpleStockQuoteService if not already +deployed.

    + +

    Run the client as

    +
     ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/
    + +
    +

    Or as

    +
    +
     ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=IBM
    + +

    Then, you will get stock quote price in the client side.

    + +

    In this sample , with in the rule mediator , the value, which is extracted +from the SOAP envelope using XPath +'//m0:getQuote/m0:request/m0:symbol', is added to the rule +engine as a string fact . The message context property named +"execute_children" is to indicate it is need to execute the +child mediators of rule mediator. That property is set only if the symbol is +IBM.

    + +

    Now use following commands

    +
     ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=SUN
    + +
    +
    + +

    and

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=MSFT
    + +
    + +
    +

    Then , you will get errors . This is because , 'symbol' is not equal to +"IBM".

    +
    + +

    Sample 601: Rule Mediator as a Filter - Simple Rule Based +Routing (Keeping Ruleset in the Registry)

    +
    <!-- Simple rule based routing  of messages - same as filter mediator -->
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <!-- the SimpleURLRegistry allows access to a URL based registry (e.g. file:/// or http://) -->
    +    <registry provider="org.wso2.carbon.mediation.registry.ESBRegistry">
    +        <!-- the root property of the simple URL registry helps resolve a resource URL as root + key -->
    +        <parameter name="root">file:repository/samples/resources/</parameter>
    +        <!-- all resources loaded from the URL registry would be cached for this number of milli seconds -->
    +        <parameter name="cachableDuration">15000</parameter>
    +    </registry>
    +
    +
    +    <localEntry key="rule-script-key"
    +                src="file:repository/samples/resources/rule/simple_rule_base.xml"/>
    +
    +    <in>
    +
    +        <rule>
    +            <ruleset >
    +                <source key="rule-script-key"/>
    +                <creation>
    +                    <property name="source" value="xml"/>
    +                </creation>
    +            </ruleset>
    +            <session type="stateless"/>
    +            <facts>
    +                <fact name="mc" type="context"/>
    +                <fact name="symbol" type="java.lang.String"
    +                      expression="//m0:getQuote/m0:request/m0:symbol/child::text()"
    +                      xmlns:m0="http://services.samples"/>
    +            </facts>
    +
    +            <childMediators>
    +                <send>
    +                    <endpoint>
    +                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                    </endpoint>
    +                </send>
    +                <drop/>
    +            </childMediators>
    +
    +        </rule>
    +
    +    </in>
    +
    +    <out>
    +        <send/>
    +    </out>
    +
    +</definitions>
    +
    + +

    rule script - simple_rule_base.xml

    +
    <package name="SimpleRoutingRules"
    +         xmlns="http://drools.org/drools-5.0"
    +         xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
    +         xs:schemaLocation="http://drools.org/drools-5.0 drools-4.0.xsd">
    +    <import name="org.apache.synapse.MessageContext"/>
    +    <rule name="Invoke IBM ">
    +        <lhs>
    +            <pattern object-type="MessageContext" identifier="mc">
    +            </pattern>
    +            <pattern object-type="String" identifier="symbol">
    +            </pattern>
    +            <eval>symbol.equals("IBM")</eval>
    +        </lhs>
    +        <rhs>
    +            mc.setProperty("execute_children","true");
    +        </rhs>
    +    </rule>
    +</package>
    + +

    Objective: Introduction to simple rule based routing

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 601: (i.e. ./wso2esb-samples.sh -sn +601)
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +deployed

    + +

    Please tests this sample same as above (600) sample because this has same +functionality as above one.

    + +

    Sample 602 : Rule Mediator as a Filter - Simple rule based +routing (Using the Drools Native Language )

    +
    <!--  Simple rule based routing  of messages - same as filter mediator -->
    +<!-- The use of Drools native language -->
    +
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <!-- the SimpleURLRegistry allows access to a URL based registry (e.g. file:/// or http://) -->
    +    <registry provider="org.wso2.carbon.mediation.registry.ESBRegistry">
    +        <!-- the root property of the simple URL registry helps resolve a resource URL as root + key -->
    +        <parameter name="root">file:repository/samples/resources/</parameter>
    +        <!-- all resources loaded from the URL registry would be cached for this number of milli seconds -->
    +        <parameter name="cachableDuration">15000</parameter>
    +    </registry>
    +
    +
    +    <localEntry key="rule-script-key"
    +                src="file:repository/samples/resources/rule/simple_rule_base.drl"/>
    +
    +    <in>
    +
    +        <rule>
    +            <ruleset >
    +                <source key="rule-script-key"/>
    +            </ruleset>
    +            <session type="stateless"/>
    +            <facts>
    +                <fact name="mc" type="context"/>
    +                <fact name="symbol" type="java.lang.String"
    +                      expression="//m0:getQuote/m0:request/m0:symbol/child::text()"
    +                      xmlns:m0="http://services.samples"/>
    +            </facts>
    +            <childMediators>
    +                <send>
    +                    <endpoint>
    +                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                    </endpoint>
    +                </send>
    +                <drop/>
    +            </childMediators>
    +
    +        </rule>
    +
    +    </in>
    +
    +    <out>
    +        <send/>
    +    </out>
    +
    +</definitions>
    + +

    rule script - simple_rule_base.drl +

    +
    <drl>
    +    <![CDATA[
    +package SimpleRoutingRules;
    +
    +import org.apache.synapse.MessageContext;
    +
    +rule InvokeIBM
    +
    +when
    +
    +mc : MessageContext()
    +symbol: String()
    +eval( symbol.equals("IBM") )
    +
    +then
    +
    +mc.setProperty("execute_children","true");
    +
    +end
    +
    +]]>
    +</drl>
    + +

    Objective: Introduction to simple rule based routing (Using +Drools native language )

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 602: (i.e. ./wso2esb-samples.sh -sn +602)
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +deployed

    + +

    Please tests this sample same as sample 600 because this has same +functionality as it.

    + +

    Sample 603 : Advance Rule Based Routing - Switching Routing +Decision According to the Rules - Rule Mediator as Switch mediator

    +
    <!-- Advance rule based routing - Switching routing decision from rules  -->
    +
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <!-- the SimpleURLRegistry allows access to a URL based registry (e.g. file:/// or http://) -->
    +    <registry provider="org.wso2.carbon.mediation.registry.ESBRegistry">
    +        <!-- the root property of the simple URL registry helps resolve a resource URL as root + key -->
    +        <parameter name="root">file:repository/samples/resources/</parameter>
    +        <!-- all resources loaded from the URL registry would be cached for this number of milli seconds -->
    +        <parameter name="cachableDuration">15000</parameter>
    +    </registry>
    +
    +
    +    <localEntry key="rule-script-key"
    +                src="file:repository/samples/resources/rule/advanced_rule_base.xml"/>
    +
    +    <sequence name="ibmSequence">
    +        <send>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +        </send>
    +    </sequence>
    +
    +    <sequence name="myFaultHandler">
    +        <makefault>
    +            <code value="tns:Receiver" xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +            <reason expression="get-property('ERROR_MESSAGE')"/>
    +        </makefault>
    +
    +        <property name="RESPONSE" value="true"/>
    +        <header name="To" expression="get-property('ReplyTo')"/>
    +        <send/>
    +    </sequence>
    +
    +    <sequence name="sunSequence" onError="myFaultHandler">
    +
    +        <send>
    +            <endpoint>
    +                <address uri="http://localhost:9009/services/NonExistentStockQuoteService"/>
    +            </endpoint>
    +        </send>
    +        <drop/>
    +
    +    </sequence>
    +
    +    <sequence name="msftSequence" onError="myFaultHandler">
    +
    +        <send>
    +            <endpoint>
    +                <address uri="http://bogus:9000/services/NonExistentStockQuoteService"/>
    +            </endpoint>
    +        </send>
    +        <drop/>
    +
    +    </sequence>
    +
    +    <in>
    +        <rule>
    +            <ruleset ">
    +                <source key="rule-script-key"/>
    +                <creation>
    +                    <property name="source" value="xml"/>
    +                </creation>
    +            </ruleset>
    +            <session type="stateless"/>
    +            <facts>
    +                <fact name="mc" type="context"/>
    +                <fact name="ibmSeq" key="ibmSequence" type="mediator"/>
    +                <fact name="sunSeq" key="sunSequence" type="mediator"/>
    +                <fact name="msftSeq" key="msftSequence" type="mediator"/>
    +                <fact name="symbol" type="java.lang.String"
    +                      expression="//m0:getQuote/m0:request/m0:symbol/child::text()"
    +                      xmlns:m0="http://services.samples"/>
    +            </facts>
    +        </rule>
    +
    +        <drop/>
    +
    +    </in>
    +
    +    <out>
    +        <send/>
    +    </out>
    +</definitions>
    + +

    rule script - advanced_rule_base.xml

    +
    <package name="AdvancedRoutingRules"
    +         xmlns="http://drools.org/drools-5.0"
    +         xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
    +         xs:schemaLocation="http://drools.org/drools-5.0 drools-4.0.xsd">
    +
    +    <import name="org.apache.synapse.MessageContext"/>
    +    <import name="org.apache.synapse.Mediator"/>
    +    <import name="org.apache.synapse.mediators.base.SequenceMediator"/>
    +
    +    <rule name="Invoke IBM ">
    +        <lhs>
    +            <pattern object-type="MessageContext" identifier="mc">
    +            </pattern>
    +            <pattern object-type="String" identifier="symbol">
    +            </pattern>
    +            <pattern identifier="seq" object-type="SequenceMediator">
    +                <field-binding field-name="name" identifier="a4"/>
    +                <field-constraint field-name="name">
    +                    <literal-restriction evaluator="==" value="ibmSequence"/>
    +                </field-constraint>
    +            </pattern>
    +            <eval>symbol.equals("IBM")</eval>
    +        </lhs>
    +
    +        <rhs>
    +            ((Mediator)seq).mediate(mc);
    +        </rhs>
    +    </rule>
    +
    +    <rule name="Invoke SUN ">
    +        <lhs>
    +            <pattern object-type="MessageContext" identifier="mc">
    +            </pattern>
    +            <pattern object-type="String" identifier="symbol">
    +            </pattern>
    +            <pattern identifier="seq" object-type="SequenceMediator">
    +                <field-binding field-name="name" identifier="a4"/>
    +                <field-constraint field-name="name">
    +                    <literal-restriction evaluator="==" value="sunSequence"/>
    +                </field-constraint>
    +            </pattern>
    +            <eval>symbol.equals("SUN")</eval>
    +        </lhs>
    +
    +        <rhs>
    +            ((Mediator)seq).mediate(mc);
    +        </rhs>
    +    </rule>
    +
    +    <rule name="Invoke MFST ">
    +        <lhs>
    +            <pattern object-type="MessageContext" identifier="mc">
    +            </pattern>
    +            <pattern object-type="String" identifier="symbol">
    +            </pattern>
    +            <pattern identifier="seq" object-type="SequenceMediator">
    +                <field-binding field-name="name" identifier="a4"/>
    +                <field-constraint field-name="name">
    +                    <literal-restriction evaluator="==" value="msftSequence"/>
    +                </field-constraint>
    +            </pattern>
    +            <eval>symbol.equals("MSFT")</eval>
    +        </lhs>
    +
    +        <rhs>
    +            ((Mediator)seq).mediate(mc);
    +        </rhs>
    +    </rule>
    +
    +</package>
    +       
    + +

    Objective: Advance rule based routing - Switching routing +decision according to the rules - Rule mediator as Switch mediator.

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 603: i.e. (i.e. ./wso2esb-samples.sh +-sn 603)

    + +

    Start the Axis2 server and deploy the SimpleStockQuoteService if not already +deployed

    + +

    This sample shows how can rule mediator act as Switch mediator. In this +sample, the use of input with type 'sequence' is being +introducing. The type 'sequence' indicates the synapse sequences. This enables +to use defined sequences (reference or in-lined) with in rule script.

    + +

    In rule script , there are three cases each for 'IBM','SUN' and 'MSFT'. When +condition is match , then corresponding rule will be got fire.

    + +

    Invoke IBM rule by running client as

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ 
    + +
    +
    + +

    You will get stock quote price successfully

    + +

    Then invoke SUN rule by running client as

    +
     ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=SUN
    + +
    +
    + +

    Then will get

    +
    <soapenv:Fault xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><faultcode>soapenv:Server</faultcode><faultstring>java.net.ConnectException: Connection refused</faultstring><detail /></soapenv:Fault>
    + +
    +
    + +

    Then invoke MSFT rule by running client as

    +
     ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=MSFT
    + +
    +
    + +

    Then will get

    +
    <soapenv:Fault xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><faultcode>soapenv:Server</faultcode><faultstring>java.net.UnknownHostException: bogus</faultstring><detail /></soapenv:Fault>
    + +
    +
    + +

    Sample 604 : Simple Message Transformation - Rule Mediator +for Message Transformation

    +
    <!-- Simple rule based transformation (changing message )  -->
    +
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <!-- the SimpleURLRegistry allows access to a URL based registry (e.g. file:/// or http://) -->
    +    <registry provider="org.wso2.carbon.mediation.registry.ESBRegistry">
    +        <!-- the root property of the simple URL registry helps resolve a resource URL as root + key -->
    +        <parameter name="root">file:repository/samples/resources/</parameter>
    +        <!-- all resources loaded from the URL registry would be cached for this number of milliseconds -->
    +        <parameter name="cachableDuration">15000</parameter>
    +    </registry>
    +
    +
    +    <localEntry key="rule-script-key"
    +                src="file:repository/samples/resources/rule/always_ibm.xml"/>
    +    <in>
    +
    +        <rule>
    +
    +            <ruleset >
    +                <source key="rule-script-key"/>
    +                <creation>
    +                        <property name="source" value="xml"/>
    +                </creation>
    +            </ruleset>
    +            <session type="stateless"/>
    +            <facts>
    +                <fact name="symbol" expression="//m0:getQuote/m0:request/m0:symbol/child::text()"
    +                      type="java.lang.String" xmlns:m0="http://services.samples"/>
    +            </facts>
    +            <results>
    +                <result name="symbol" expression="//m0:getQuote/m0:request/m0:symbol"
    +                        type="java.lang.String" xmlns:m0="http://services.samples"/>
    +            </results>
    +
    +        </rule>
    +
    +        <send>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +        </send>
    +
    +    </in>
    +
    +    <out>
    +        <send/>
    +    </out>
    +
    +</definitions>
    + +

    rule script - always_ibm.xml

    +
    <package name="SimpleMessageTransformationRules"
    +         xmlns="http://drools.org/drools-5.0"
    +         xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
    +         xs:schemaLocation="http://drools.org/drools-5.0 drools-4.0.xsd">
    +    <rule name="Invoke Always IBM ">
    +        <lhs>
    +            <pattern object-type="String" identifier="symbol">
    +            </pattern>
    +            <eval>symbol.equals("MSFT") || symbol.equals("SUN")</eval>
    +        </lhs>
    +        <rhs>
    +            update(drools.getWorkingMemory().getFactHandle(symbol),"IBM");
    +        </rhs>
    +    </rule>
    +
    +</package>
    + +

    Objective: Simple message transformation - Rule mediator +for message transformation.

    + +

    Prerequisites:

    + +

    Start the Synapse configuration numbered 604: (i.e. ./wso2esb-samples.sh -sn +604)

    + +

    Start the Axis2 server and deploy the SimpleStockQuoteService if not already +deployed

    + +

    In this sample , a simple transformation is happened . If the symbol is +either SUN or MSFT , then it will changed into IBM in the SOAP envelope and +then invoke the external service.

    + +

    Run client as

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=MSFT
    + +

    Or as

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=SUN
    + +
    +
    + +

    Then check the axis2server log or console .

    +
    Mon Mar 03 16:33:05 IST 2008 samples.services.SimpleStockQuoteService :: Generating quote for : IBM
    + +

    Sample 605 : Simple Message Transformation

    +
    <!-- Simple rule based transformation (changing message ) -->
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <!-- the SimpleURLRegistry allows access to a URL based registry (e.g. file:/// or http://) -->
    +    <registry provider="org.wso2.carbon.mediation.registry.ESBRegistry">
    +        <!-- the root property of the simple URL registry helps resolve a resource URL as root + key -->
    +        <parameter name="root">file:repository/samples/resources/</parameter>
    +        <!-- all resources loaded from the URL registry would be cached for this number of milli seconds -->
    +        <parameter name="cachableDuration">15000</parameter>
    +    </registry>
    +
    +    <localEntry key="rule-script-key"
    +                src="file:repository/samples/resources/rule/commission_rule.xml"/>
    +    <in>
    +        <send>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +        </send>
    +    </in>
    +
    +    <out>
    +        <rule>
    +            <ruleset >
    +                <source key="rule-script-key"/>
    +                <creation>
    +                        <property name="source" value="xml"/>
    +                </creation>
    +            </ruleset>
    +            <session type="stateless"/>
    +            <facts>
    +                <fact name="symbol" type="java.lang.String"
    +                      expression="self::node()//m0:return/m1:symbol/child::text()"
    +                      xmlns:m0="http://services.samples"
    +                      xmlns:m1="http://services.samples/xsd"/>
    +                <fact name="price" type="java.lang.Double"
    +                      expression="self::node()//m0:return/m1:last/child::text()"
    +                      xmlns:m0="http://services.samples"
    +                      xmlns:m1="http://services.samples/xsd"/>
    +            </facts>
    +            <results>
    +                <result name="price" type="java.lang.Double"
    +                        expression="self::node()//m0:return/m1:last"
    +                        xmlns:m0="http://services.samples"
    +                        xmlns:m1="http://services.samples/xsd"/>
    +            </results>
    +        </rule>
    +        <send/>
    +    </out>
    +</definitions>
    + +

    rule script - commission_rule.xml

    +
    <package name="SimpleMessageTransformationRules"
    +         xmlns="http://drools.org/drools-5.0"
    +         xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
    +         xs:schemaLocation="http://drools.org/drools-5.0 drools-4.0.xsd">
    +
    +    <rule name="Get commission form SUN and MSFT but not from IBM ">
    +
    +        <lhs>
    +            <pattern object-type="String" identifier="symbol">
    +            </pattern>
    +            <pattern object-type="Double" identifier="price">
    +            </pattern>
    +            <eval>symbol.equals("MSFT") || symbol.equals("SUN")</eval>
    +        </lhs>
    +
    +        <rhs>
    +            Double newPrice = price.doubleValue()+ 3000.68;
    +            update(drools.getWorkingMemory().getFactHandle(price),newPrice);
    +            retract(drools.getWorkingMemory().getFactHandle(symbol));
    +        </rhs>
    +    </rule>
    +
    +</package>
    + +

    Objective: Simple message transformation - Rule mediator +for message transformation.

    + +

    Prerequisites:

    + +

    Start the Synapse configuration numbered 605: (i.e. ./wso2esb-samples.sh -sn +605)
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +deployed.

    + +

    This sample also illustrates a simple transformation using rule mediator. In +here, for MSFT and SUN a commission is added to the price.(3000.68).

    + +

    Invoke synapse(esb) with symbol IBM as

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ 
    + +

    Then you will get the price as usual value .

    +
    Standard :: Stock price = $81.35674789750315
    + +

    Then invoke synapse(esb) with symbol MSFT or SUN as

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=SUN
    + +
    +

    Then you will get the price whic is always above 3000.

    +
     Standard :: Stock price = $3082.1975970450094
    +
    + +

    Sample 606 : Advanced Transformation and Use of Custom Java +Objects

    +
    <!-- Transformation with custom Java object -->
    +
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <!-- the SimpleURLRegistry allows access to a URL based registry (e.g. file:/// or http://) -->
    +    <registry provider="org.wso2.carbon.mediation.registry.ESBRegistry">
    +        <!-- the root property of the simple URL registry helps resolve a resource URL as root + key -->
    +        <parameter name="root">file:repository/samples/resources/</parameter>
    +        <!-- all resources loaded from the URL registry would be cached for this number of milliseconds -->
    +        <parameter name="cachableDuration">15000</parameter>
    +    </registry>
    +
    +    <localEntry key="rule-script-forward-key"
    +                src="file:repository/samples/resources/rule/tranform_forward_rule.drl"/>
    +    <localEntry key="rule-script-back-key"
    +                src="file:repository/samples/resources/rule/tranform_back_rule.drl"/>
    +
    +    <in>
    +
    +        <rule>
    +            <ruleset>
    +                <source key="rule-script-forward-key"/>
    +            </ruleset>
    +            <session type="stateless"/>
    +            <facts>
    +                <fact name="mc" type="context"/>
    +                <fact name="symbol"
    +                      expression="self::node()//m0:CheckPriceRequest/m0:Code/child::text()"
    +                      xmlns:m0="http://services.samples" type="java.lang.String"/>
    +                
    +            </facts>
    +            <results>
    +                <result name="CheckPriceRequest" expression="self::node()//m0:CheckPriceRequest"
    +                      xmlns:m0="http://services.samples"
    +                      type="org.wso2.carbon.rule.samples.GetQuoteRequest"/>
    +            </results>
    +
    +            <childMediators>
    +                <send>
    +                    <endpoint>
    +                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                    </endpoint>
    +                </send>
    +                <drop/>
    +            </childMediators>
    +        </rule>
    +
    +    </in>
    +
    +    <out>
    +
    +        <rule>
    +            <ruleset>
    +                <source key="rule-script-back-key"/>
    +            </ruleset>
    +            <session type="stateless"/>
    +            <facts>
    +                <fact name="symbol" type="java.lang.String"
    +                      expression="self::node()//m0:return/m1:symbol/child::text()"
    +                      xmlns:m0="http://services.samples"
    +                      xmlns:m1="http://services.samples/xsd"/>
    +                <fact name="price" type="java.lang.Double"
    +                      expression="self::node()//m0:return/m1:last/child::text()"
    +                      xmlns:m0="http://services.samples"
    +                      xmlns:m1="http://services.samples/xsd"/>
    +            </facts>
    +
    +            <results>
    +                <result name="response" expression="self::node()//m0:return"
    +                        type="org.wso2.carbon.rule.samples.CheckPriceResponse"
    +                        xmlns:m0="http://services.samples"/>
    +            </results>
    +
    +        </rule>
    +
    +        <send/>
    +
    +    </out>
    +</definitions>
    +
    + +

    rule script for request transformation - +tranform_forward_rule.drl

    +
    <drl>
    +    <![CDATA[
    +package ForwardTransformation;
    +
    +import org.wso2.carbon.rule.samples.GetQuoteRequest ;
    +import org.apache.synapse.MessageContext;
    +
    +rule ForwardTransformation
    +
    +when
    +
    +symbol : String()
    +mc : MessageContext()
    +eval(symbol != null )
    +
    +then
    +
    +GetQuoteRequest request = new GetQuoteRequest();
    +
    +request.setSymbol(symbol);
    +insert(request);
    +mc.setProperty("execute_children","true");
    +end
    +
    +]]>
    +</drl>
    + +

    rule script for response transformation - +tranform_back_rule.drl

    +
    <drl>
    +    <![CDATA[
    +package BackwardTransformation;
    +
    +import org.wso2.carbon.rule.samples.CheckPriceResponse;
    +
    +rule BackwardTransformation
    +
    +when
    +
    +price : Double()
    +symbol : String()
    +eval( price != null && symbol != null )
    +
    +then
    +
    +CheckPriceResponse response = new CheckPriceResponse();
    +
    +response.setCode(symbol);
    +response.setPrice(price);
    +
    +insert(response);
    +
    +end
    +
    +]]>
    +</drl>
    + +

    Objective: Advanced transformation using rule mediator.

    + +

    Prerequisites:

    + +

    Start the Synapse configuration numbered 606: (i.e. ./wso2esb-samples.sh -sn +606)
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +deployed.

    + +

    The classes GetQuoteRequest.java and +CheckPriceResponse.java which are shown in bellow, have to be +compiled and put in classpath. Easy way may be putting as a jar inside +repository/components/lib. Pleas note that these classes need +to be group to package org.wso2.carbon.rule.samples.

    + +

    This sample also illustrates a advanced transformation using rule mediator. +

    + +

    This sample illustrates the functionality offered by XSLT sample (sample 8 +in the synapse (esb) samples). Both of the request and response are +transformed.

    + +

    In this sample , use Java objects to archive the easy transformation. if the +a toXML() method returns a valid XML , it is possible to +attached it into SOPA envelope. It is same concepts as serializing object into +XML . if there is no method of toXML , then Java Object is +serialized into an XML based Axis2 POJO to XML binding.

    + +

    For input transformation

    +
     package org.wso2.carbon.rule.samples;
    +
    +/**
    + *
    + */
    +public class GetQuoteRequest {
    +    private String symbol;
    +
    +    public String getSymbol() {
    +        return symbol;
    +    }
    +
    +    public void setSymbol(String symbol) {
    +        this.symbol = symbol;
    +    }
    +
    +    public String toXML() {
    +        return "<m:getQuote xmlns:m=\"http://services.samples\">" +
    +                "<m:request>" +
    +                "<m:symbol>" + symbol + "</m:symbol>" +
    +                "</m:request>" +
    +                "</m:getQuote>";
    +    }
    +}
    + +

    For output transformation

    +
     package org.wso2.carbon.rule.samples;
    +
    +/**
    + *
    + */
    +public class CheckPriceResponse {
    +    private String code;
    +    private Double price;
    +
    +    public String getCode() {
    +        return code;
    +    }
    +
    +    public void setCode(String code) {
    +        this.code = code;
    +    }
    +
    +    public Double getPrice() {
    +        return price;
    +    }
    +
    +    public void setPrice(Double price) {
    +        this.price = price;
    +    }
    +
    +    public String toXML() {
    +        return "<m:CheckPriceResponse xmlns:m=\"http://services.samples\" " +
    +                "xmlns:m1=\"http://services.samples/xsd\">" +
    +                "<m1:Code>" + code + "</m1:Code>" +
    +                "<m1:Price>" + price + "</m1:Price>" +
    +                "</m:CheckPriceResponse>";
    +    }
    +}
    + +

    This is just a example to show what kind of cool thing can be done using +rule mediator.

    + +

    Runs the client in custom mode as follows

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dmode=customquote
    + + diff --git a/docs/xdoc/samples/store_n_forward_samples.xml b/docs/xdoc/samples/store_n_forward_samples.xml new file mode 100644 index 0000000000..3c4d642a67 --- /dev/null +++ b/docs/xdoc/samples/store_n_forward_samples.xml @@ -0,0 +1,210 @@ + + + + + + + + WSO2 ESB - Store and Forward Messaging patterns with Message Stores and Message Processors + + + +

    Store and Forward Messaging patterns with Message Stores and Message Processors

    +

    + Message Stores and Message Processors can be used to implement different store + and forward messaging patterns. + This can be use to cater different SLA s and other QoS aspects. +

    +

    + Sample 700: Introduction to Message Store

    +
    +            <!-- Introduction to the  Message Store -->
    +            <definitions xmlns="http://ws.apache.org/ns/synapse">
    +            <sequence name="fault">
    +            <log level="full">
    +            <property name="MESSAGE" value="Executing default 'fault' sequence"/>
    +            <property name="ERROR_CODE" expression="get-property('ERROR_CODE')"/>
    +            <property name="ERROR_MESSAGE" expression="get-property('ERROR_MESSAGE')"/>
    +            </log>
    +            <drop/>
    +            </sequence>
    +            <sequence name="onStoreSequence">
    +            <log>
    +            <property name="On-Store" value="Storing message"/>
    +            </log>
    +            </sequence>
    +            <sequence name="main">
    +            <in>
    +            <log level="full"/>
    +            <property name="FORCE_SC_ACCEPTED" value="true" scope="axis2"/>
    +            <store messageStore="MyStore" sequence="onStoreSequence"/>
    +            </in>
    +            <description>The main sequence for the message mediation</description>
    +            </sequence>
    +            <messageStore name="MyStore"/>
    +            </definitions>
    +        
    +

    + Objective: Introduction to Message Stores

    +

    Prerequisites: +
    Start the configuration numbered 700: i.e. wso2esb-samples -sn 700 +

    +

    To Execute the Client :

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dmode=placeorder
    +    
    +

    When you execute the client the message will be dispatched to the main sequence. + In the Main sequence store mediator will store the placeOrder request message in the "MyStore" Message Store

    + +

    Before Storing the message store mediator will invoke the sequence :onStoreSequence. See the log

    +

    INFO - LogMediator To: http://localhost:9000/services/SimpleStockQuoteService, WSAction: urn:placeOrder, SOAPAction: urn:placeOrder, ReplyTo: http://www.w3.org/2005/08/addressing/none, MessageID: urn:uuid:54f0e7c6-7b43-437c-837e-a825d819688c, Direction: request, On-Store = Storing message +

    + + +

    You can then use the JMX view of Synapse Message Store by using the jconsole and view the stored + Messages and delete them. +

    +

    + Sample 701: Introduction to Message Sampling Processor

    +
    +            <!-- Introduction to  Message Sampling Processor -->
    +
    +            <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +            <sequence name="send_seq">
    +            <send>
    +            <endpoint>
    +            <address uri="http://localhost:9000/services/SimpleStockQuoteService">
    +            <suspendOnFailure>
    +            <errorCodes>-1</errorCodes>
    +            <progressionFactor>1.0</progressionFactor>
    +            </suspendOnFailure>
    +            </address>
    +            </endpoint>
    +            </send>
    +            </sequence>
    +            <sequence name="main">
    +            <in>
    +            <log level="full"/>
    +            <property name="FORCE_SC_ACCEPTED" value="true" scope="axis2"/>
    +            <property name="OUT_ONLY" value="true"/>
    +            <store messageStore="MyStore"/>
    +            </in>
    +            <description>The main sequence for the message mediation</description>
    +            </sequence>
    +            <messageStore name="MyStore"/>
    +            <messageProcessor
    +            class="org.apache.synapse.message.processors.sampler.SamplingProcessor"
    +            name="SamplingProcessor" messageStore="MyStore">
    +            <parameter name="interval">20000</parameter>
    +            <parameter name="sequence">send_seq</parameter>
    +            </messageProcessor>
    +            </definitions>
    +        
    +

    + Objective:Introduction to Message Sampling Processor +

    +

    Prerequisites: +
    Start the configuration numbered 701: i.e. wso2esb-samples -sn 701

    +

    Start the SimpleStockQuoteService if its not already started

    +

    To Execute the Client few times:

    +
    ant stockquote
    +            -Daddurl=http://localhost:9000/services/SimpleStockQuoteService
    +            -Dtrpurl=http://localhost:8280/ -Dmode=placeorder
    +        
    +

    When you execute the client the message will be dispatched to the main sequence. + In the Main sequence store mediator will store the placeOrder request message in the + "MyStore" Message Store +

    + +

    Message Processor will consume the messages and forward to the send_seq sequence in + configured rate. +

    +

    You will observe that service invocation rate is not changing when increasing the rate we + execute the client. +

    +

    + Sample 702: Introduction to Message Forwarding Processor

    +
    +
    +            <!-- Introduction to Scheduled Message Forwarding Processor -->
    +
    +            <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +            <endpoint name="StockQuoteServiceEp">
    +            <address uri="http://localhost:9000/services/SimpleStockQuoteService">
    +            <suspendOnFailure>
    +            <errorCodes>-1</errorCodes>
    +            <progressionFactor>1.0</progressionFactor>
    +            </suspendOnFailure>
    +            </address>
    +            </endpoint>
    +            <sequence name="fault">
    +            <log level="full">
    +            <property name="MESSAGE" value="Executing default 'fault' sequence"/>
    +            <property name="ERROR_CODE" expression="get-property('ERROR_CODE')"/>
    +            <property name="ERROR_MESSAGE" expression="get-property('ERROR_MESSAGE')"/>
    +            </log>
    +            <drop/>
    +            </sequence>
    +            <sequence name="main">
    +            <in>
    +            <log level="full"/>
    +            <property name="FORCE_SC_ACCEPTED" value="true" scope="axis2"/>
    +            <property name="OUT_ONLY" value="true"/>
    +            <property name="target.endpoint" value="StockQuoteServiceEp"/>
    +            <store messageStore="MyStore"/>
    +            </in>
    +            <description>The main sequence for the message mediation</description>
    +            </sequence>
    +            <messageStore name="MyStore"/>
    +            <messageProcessor
    +            class="org.apache.synapse.message.processors.forward.ScheduledMessageForwardingProcessor"
    +            name="ScheduledProcessor" messageStore="MyStore">
    +            <parameter name="interval">10000</parameter>
    +            </messageProcessor>
    +            </definitions>
    +        
    +

    + Objective:Introduction to Message Forwarding Processor

    +

    Prerequisites: + +
    + Start the configuration numbered 702: i.e. wso2esb-samples -sn 702

    + +

    To Execute the Client:

    +
    ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dmode=placeorder
    +
    + +

    Now Start the SimpleStockQuoteService

    +

    When you Start the service you will see message getting delivered to the service. Even + though service is down when we invoke it from the client +

    +

    Here in the Main sequence store mediator will store the placeOrder request message in the + "MyStore" Message Store +

    +

    Message Processor will send the message to the endpoint configured as a message context + property. +

    +

    Message processor will remove the message from the store only if message delivered + successfully +

    + + diff --git a/docs/xdoc/samples/task_samples.xml b/docs/xdoc/samples/task_samples.xml new file mode 100644 index 0000000000..a9d0045bb9 --- /dev/null +++ b/docs/xdoc/samples/task_samples.xml @@ -0,0 +1,81 @@ + + + + + + + + WSO2 ESB - Tasks Samples + + + +

    Running the Tasks samples with WSO2 Enterprise Service Bus (ESB)

    + +

    Sample 300: Introduction to tasks with simple + trigger

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +        <task class="org.apache.synapse.startup.tasks.MessageInjector" name="CheckPrice">
    +            <property name="to" value="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            <property name="soapAction" value="urn:getQuote"/>
    +            <property name="message">
    +                <m0:getQuote xmlns:m0="http://services.samples">
    +                    <m0:request>
    +                        <m0:symbol>IBM</m0:symbol>
    +                    </m0:request>
    +                </m0:getQuote>
    +            </property>
    +            <trigger interval="5"/>
    +        </task>
    +
    +        <in>
    +            <send/>
    +        </in>
    +        <out>
    +            <log level="custom">
    +                <property name="Stock_Quote_on" expression="//ns:return/ax21:lastTradeTimestamp/child::text()" xmlns:ax21="http://services.samples/xsd" xmlns:ns="http://services.samples"/>
    +                <property name="For_the_organization" expression="//ns:return/ax21:name/child::text()" xmlns:ax21="http://services.samples/xsd" xmlns:ns="http://services.samples"/>
    +                <property name="Last_Value" expression="//ns:return/ax21:last/child::text()" xmlns:ax21="http://services.samples/xsd" xmlns:ns="http://services.samples"/>
    +            </log>
    +        </out>
    +
    +    </definitions>
    + +

    Objective: Introduce the concept of tasks and how simple trigger + works

    + +

    Prerequisites:
    + You will need access to build the SimpleStockQuoteService as mentioned in the + above and start the sample axis2 server before staring ESB.

    + +

    When ever ESB gets started with this configuration (i.e. ./wso2esb-samples -sn 300), this task will run + periodically in 5 second intervals. You could limit the number of times that + you want to run this task by adding a count attribute with an integer as the + value, if the count is not present as in this sample this task will run + forever.

    + +

    One can write his own task class implementing the + org.apache.synapse.startup.Task interface and implementing the execute method + to do the task. For this particular sample we have used the MessageInjector + which just injects a message specified into the ESB environment.

    + + + diff --git a/docs/xdoc/samples/templates_samples.xml b/docs/xdoc/samples/templates_samples.xml new file mode 100644 index 0000000000..df86dbe01f --- /dev/null +++ b/docs/xdoc/samples/templates_samples.xml @@ -0,0 +1,259 @@ + + + + + + + + WSO2 ESB - Templates Samples + + + +

    Running Templates with WSO2 Enterprise Service Bus (ESB)

    + +

    Sample 750: Stereotyping XSLT Transformations with Templates

    +
    <?xml version="1.0" encoding="UTF-8"?>
    +    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +        <proxy name="StockQuoteProxy">
    +            <target>
    +            <inSequence>
    +            <!--use sequence template to trasnform incoming request-->
    +            <call-template target="xslt_func">
    +                            <with-param name="xslt_key" value="xslt-key-req"/>
    +                    </call-template>
    +            <send>
    +                <endpoint>
    +                                  <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                            </endpoint>
    +                    </send>
    +                </inSequence>
    +
    +                <outSequence>
    +            <!--use sequence template to trasnform incoming response-->
    +            <call-template target="xslt_func">
    +                            <with-param name="xslt_key" value="xslt-key-back"/>
    +                    </call-template>
    +                    <send/>
    +                </outSequence>
    +            </target>
    +        </proxy>
    +
    +        <!--this sequence template will trasnform requests with the given xslt local entry key And will log
    +        the message before and after. Takes Iterate local entry key as an argument-->
    +        <template xmlns="http://ws.apache.org/ns/synapse" name="xslt_func">
    +            <parameter name="xslt_key"/>
    +            <sequence>
    +                    <log level="full">
    +                <property name="BEFORE_TRANSFORM" value="true" />
    +            </log>
    +                 <xslt key="{$func:xslt_key}"/>
    +            <log level="full">
    +                <property name="AFTER_TRANSFORM" value="true" />
    +            </log>
    +            </sequence>
    +        </template>
    +
    +        <localEntry key="xslt-key-req" src="file:repository/samples/resources/transform/transform.xslt"/>
    +        <localEntry key="xslt-key-back" src="file:repository/samples/resources/transform/transform_back.xslt"/>
    +    </definitions>
    + +

    Objective: Introduction to ESB Sequence Templates

    + +

    Prerequisites:
    + Start the Synapse configuration numbered 750: i.e. wso2esb-samples -sn 750
    + Start the Axis2 server and deploy the SimpleStockQuoteService if not already + done

    + +

    Execute the stock quote client by requesting for a stock quote on the + proxy service as follows:

    +
    ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy  -Dmode=customquote
    + +

    ESB Sequence Template can act a reusable function. Here proxy service reuses template xslt_func which will transform requests with the given xslt local entry key And will log + the message before and after. It takes xslt transformation corresponding to local entry key as an + argument (for insequence this key is xslt-key-req and out sequence it is xslt-key-back). We use + call-template mediator for passing the xslt key parameter to a sequence template. ESB console + will display how the custom stockquote is transformed and the transformed response from the service.

    + + +

    Sample 751: Message Split Aggregate Using Templates

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <proxy name="SplitAggregateProxy">
    +        <target>
    +            <inSequence>
    +		<!--use iterate sequence template to split incoming request and send-->
    +                <call-template target="iter_func">
    +                        <with-param xmlns:m0="http://services.samples" name="iter_expr" value="{{//m0:getQuote/m0:request}}"/>
    + 			<with-param xmlns:m0="http://services.samples" name="attach_path" value="{{//m0:getQuote}}"/>
    +                </call-template>
    +            </inSequence>
    +            <outSequence>
    +		<!--use aggregate sequence template to combine the responses and send back-->
    +                <call-template target="aggr_func">
    +                        <with-param xmlns:m0="http://services.samples" name="aggr_expr" value="{{//m0:getQuoteResponse}}"/>
    +                </call-template>
    +            </outSequence>
    +        </target>
    +    </proxy>
    +
    +    <!--this sequence template will aggregate the responses , merge and send back to the client. This takes aggregate
    +	expression as an argument-->
    +    <template xmlns="http://ws.apache.org/ns/synapse" name="aggr_func">
    +        <parameter name="aggr_expr"/>
    +        <sequence>
    +            <log level="full"/>
    +            <aggregate>
    +                <completeCondition>
    +                    <messageCount min="-1" max="-1"/>
    +                </completeCondition>
    +                <onComplete expression="$func:aggr_expr">
    +                    <log level="full" />
    +                    <send/>
    +                </onComplete>
    +            </aggregate>
    +        </sequence>
    +    </template>
    +
    +    <!--this sequence template will iterate through stock quote symbols ,split and send them to endpoints. Takes Iterate
    +	expression and soap attaach path as arguments -->
    +    <template xmlns="http://ws.apache.org/ns/synapse" name="iter_func">
    +        <parameter name="iter_expr"/>
    +        <parameter name="attach_path"/>
    +        <sequence>
    +
    +            <iterate  xmlns:m0="http://services.samples" preservePayload="true" attachPath="$func:attach_path" expression="$func:iter_expr">
    +                <target>
    +                    <sequence>
    +                        <send>
    +                            <endpoint>
    +                                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                            </endpoint>
    +                        </send>
    +                    </sequence>
    +                </target>
    +            </iterate>
    +        </sequence>
    +    </template>
    +</definitions>
    + +

    Objective: Demonstrate the use of tempaltes in Split/Aggregate scenario .

    + +

    Prerequisites:Deploy the SimpleStockQuoteService in sample + Axis2 server and start it on port 9000.

    + +

    Start ESB with the sample configuration 751 (i.e. wso2esb-samples -sn 751). +

    + +

    This will be the same sample demonstrated in advanced mediation with Iterate mediator used to split the + messages in to parts and process them asynchronously and then aggregate the + responses coming in to ESB. Only addition will be two sequence templates 'iter_func' and + 'aggr_func' which will split the message and aggregate the responses back , respectively.

    + +

    Invoke the client as follows.

    +
    ant stockquote -Daddurl=http://localhost:8280/services/SplitAggregateProxy -Ditr=4
    + +

    Sequence Template 'iter_func' takes iterate expressions and attach path as arguments.

    + +

    Sequence Template 'aggr_func' takes aggregate expression as argument.

    + +

    In this sample we are using special dynamic xpath expressions(in double curly braces {{expr}}) in call-template mediator so that + they are evaluated only when iteration and aggregation is done. Note that function scope (ie:-$func) is used to access template + parameters in 'iter_func' and 'aggr_func'. +

    + +

    Sample 752: Load balancing Between three Endpoints With Endpoint Templates

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <proxy name="LBProxy" transports="https http" startOnLoad="true">
    +        <target faultSequence="errorHandler">
    +            <inSequence>
    +                <send>
    +                    <endpoint>
    +                        <session type="simpleClientSession"/>
    +                        <loadbalance algorithm="org.apache.synapse.endpoints.algorithms.RoundRobin">
    +                            <endpoint name="templ_ep1" template="endpoint_template" uri="http://localhost:9001/services/LBService1">
    +				<parameter name="suspend_duration" value="5"/>
    +                            </endpoint>
    +			    <endpoint name="templ_ep2" template="endpoint_template" uri="http://localhost:9002/services/LBService1">
    +				<parameter name="suspend_duration" value="20"/>
    +                            </endpoint>
    +			    <endpoint name="templ_ep3" template="endpoint_template" uri="http://localhost:9003/services/LBService1">
    +				<parameter name="suspend_duration" value="200"/>
    +                            </endpoint>
    +                        </loadbalance>
    +                    </endpoint>
    +                </send>
    +                <drop/>
    +            </inSequence>
    +            <outSequence>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_2.wsdl"/>
    +    </proxy>
    +
    +    <sequence name="errorHandler">
    +        <makefault>
    +            <code value="tns:Receiver" xmlns:tns="http://www.w3.org/2003/05/soap-envelope"/>
    +            <reason value="COULDN'T SEND THE MESSAGE TO THE SERVER."/>
    +        </makefault>
    +        <send/>
    +    </sequence>
    +
    +
    +
    +    <template name="endpoint_template">
    +	    <parameter name="suspend_duration"/>
    +	    <endpoint name="annonymous">
    +		<address uri="$uri">
    +		    <enableAddressing/>
    +                    <suspendDurationOnFailure>$suspend_duration</suspendDurationOnFailure>
    +		</address>
    +	    </endpoint>
    +    </template>
    +
    +</definitions>
    + +

    Objective: Demonstrate how to use endpoint templates in a load balance configuration .

    + +

    Prerequisites:Sample setup is same as LoadBalance endpoint scenario (#154). + +Start the Synapse configuration numbered 752: i.e. wso2esb-samples -sn 752 +Start the Axis2 server and deploy the LoadbalanceFailoverService if not already done + +

    + +

    Configuration demonstrates a single endpoint template named 'endpoint_template'. Three endpoint templates + are created inside loadbalance endpoint which will point to this template. Note different parameters passed + on to the same template ie:- service url and suspend duration as parameters

    + +

    Invoke the client as follows.

    +
     ant loadbalancefailover -Dmode=session -Dtrpurl=http://localhost:8280/services/LBProxy
    + + +

    As in the previous loadbalance samples client console will show loadbalance requests going towards three endpoints + created from the same template. Notice differnt suspension times for three services in a failed + endpoint scenario as well. (reflects different parameters passed onto the template) +

    + + + diff --git a/docs/xdoc/samples/transport_samples.xml b/docs/xdoc/samples/transport_samples.xml new file mode 100644 index 0000000000..7b70df879b --- /dev/null +++ b/docs/xdoc/samples/transport_samples.xml @@ -0,0 +1,1348 @@ + + + + + + + + WSO2 ESB - Transport Switching Samples + + + +

    Running the Transport samples with WSO2 Enterprise Service Bus (ESB)

    +

    Sample 250: Introduction to switching transports - JMS +to http/s

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <proxy name="StockQuoteProxy" transports="jms">
    +        <target>
    +            <inSequence>
    +                <property action="set" name="OUT_ONLY" value="true"/>
    +            </inSequence>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +            <outSequence>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +        <parameter name="transport.jms.ContentType">
    +            <rules>
    +                <jmsProperty>contentType</jmsProperty>
    +                <default>application/xml</default>
    +            </rules>
    +        </parameter>
    +    </proxy>
    +
    +</definitions>
    + +

    Objective: Introduction to switching transports with proxy +services

    + +

    Prerequisites:
    +Start the Axis2 server and deploy the SimpleStockQuoteService (Refer steps +above)
    +Download, install and start a JMS server, and configure ESB to listen on JMS +(refer notes below)
    +Start the Synapse configuration numbered 250: i.e. wso2esb-samples -sn 250
    +For this example we would use ActiveMQ as the JMS provider. Once ActiveMQ is +installed and started you should get a message as follows:

    +
    INFO BrokerService - ActiveMQ JMS Message Broker (localhost) started
    + +

    You will now need to configure the Axis2 instance used by ESB (not the +sample Axis2 server) to enable JMS support using the above provider. Refer to +the Axis2 documentation on setting up JMS for more details +(http://ws.apache.org/axis2/1_1/jms-transport.html). You will also need to +copy the ActiveMQ client jar files +activemq-core-5.2.0.jar and geronimo-j2ee-management_1.0_spec-1.0.jar into +the repository/components/lib directory to allow ESB to connect to the JMS provider.

    + +

    For a default ActiveMQ v4.0 installation, you may uncomment the Axis2 +transport listener configuration found at repository/conf/axis2.xml as

    +
    <transportReceiver name="jms" class="org.apache.axis2.transport.jms.JMSListener"> ...
    + +

    You need to enable the JMS transport sender for the ESB to be able to send +messages over the JMS transport. To enable the JMS transport sender uncomment +the Axis2 transport sender configuration found at repository/conf/axis2.xml as

    +
    <transportSender name="jms" class="org.apache.axis2.transport.jms.JMSSender" />
    + +

    Once you start the Synapse configuration and request for the WSDL of the +proxy service (http://localhost:8280/services/StockQuoteProxy?wsdl) you will +notice that its exposed only on the JMS transport. This is because the +configuration specified this requirement in the proxy service definition.

    + +

    Now lets send a place order request on JMS, using the dumb stock quote +client as follows:

    +
    ant jmsclient -Djms_type=pox -Djms_dest=dynamicQueues/StockQuoteProxy -Djms_payload=MSFT
    + +

    On the ESB debug log you will notice that the JMS listener received the +request message as:

    +
    [JMSWorker-1] DEBUG ProxyServiceMessageReceiver -Proxy Service StockQuoteProxy received a new message...
    + +

    Now if you examine the console running the sample Axis2 server, you will +see a message indicating that the server has accepted an order as follows: +

    +
    Accepted order for : 16517 stocks of MSFT at $ 169.14622538721846
    + +

    In this sample, client sends the request message to the proxy service +exposed over JMS in Synapse. ESB forwards this message to the HTTP EPR of the +simple stock quote service hosted on the sample Axis2 server, which sends a +202 Accepted response back to the ESB. Since the placeOrder operation is an +in-only service operation the JMS client does not receive any response in this +sample.

    + +

    e.g.

    +
    <property name="transport.jms.Destination" value="dynamicTopics/something.TestTopic"/>
    + +

    Sample 251: Switching from http/s to JMS

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <proxy name="StockQuoteProxy" transports="http">
    +        <target>
    +            <endpoint>
    +                <address uri="jms:/SimpleStockQuoteService?transport.jms.ConnectionFactoryJNDIName=QueueConnectionFactory&amp;
    +                   java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&amp;java.naming.provider.url=tcp://localhost:61616"/>
    +            </endpoint>
    +            <inSequence>
    +                <property action="set" name="OUT_ONLY" value="true"/>
    +            </inSequence>
    +            <outSequence>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +
    +</definitions>
    + +

    Objective: Demonstrate switching from HTTP to JMS

    + +

    Prerequisites:
    +Download, install and start a JMS server

    + +

    Configure sample Axis2 server for JMS (refer notes above)
    +Start the Axis2 server and deploy the SimpleStockQuoteService (see below)
    +Configure the Synapse JMS transport (refer notes above - sample 250)
    +Start the Synapse configuration numbered 251: i.e. wso2esb-samples -sn 251

    + +

    To switch from HTTP to JMS, edit the +samples/axis2Server/repository/conf/axis2.xml for the sample Axis2 server and +enable JMS (refer notes above), and restart the server. Now you can see that +the simple stock quote service is available in both JMS and HTTP in the +sample Axis2 server. To see this, point your browser to the WSDL of the +service at http://localhost:9000/services/SimpleStockQuoteService?wsdl. JMS URL +for the service is mentioned as below:

    +
    jms:/SimpleStockQuoteService?transport.jms.ConnectionFactoryJNDIName=
    +QueueConnectionFactory&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&
    +java.naming.provider.url=tcp://localhost:61616
    + +

    You may also notice that the simple stock quote proxy service exposed in +ESB is now available only in HTTP as we have specified transport for that +service as HTTP. To observe this, access the WSDL of stock quote proxy +service at http://localhost:8280/services/StockQuoteProxy?wsdl.

    + +

    This ESB configuration creates a proxy service over HTTP and forwards +received messages to the above EPR using JMS. To test this, send a place +order request to ESB using HTTP as follows:

    +
    ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy -Dmode=placeorder -Dsymbol=MSFT
    + +

    The sample Axis2 server console will print a message indicating that it +has accepted the order as follows:

    +
    Accepted order for : 18406 stocks of MSFT at $ 83.58806051152119
    + +

    Sample 252: Pure text/binary and POX message support +with JMS

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <sequence name="text_proxy">
    +        <header name="Action" value="urn:placeOrder"/>
    +        <script language="js"><![CDATA[
    +            var args = mc.getPayloadXML().toString().split(" ");
    +            mc.setPayloadXML(
    +            <m:placeOrder xmlns:m="http://services.samples/xsd">
    +                <m:order>
    +                    <m:price>{args[0]}</m:price>
    +                    <m:quantity>{args[1]}</m:quantity>
    +                    <m:symbol>{args[2]}</m:symbol>
    +                </m:order>
    +            </m:placeOrder>);
    +        ]]></script>
    +        <property action="set" name="OUT_ONLY" value="true"/>
    +        <send>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +        </send>
    +    </sequence>
    +
    +    <sequence name="mtom_proxy">
    +        <property action="set" name="OUT_ONLY" value="true"/>
    +        <header name="Action" value="urn:oneWayUploadUsingMTOM"/>
    +        <send>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/MTOMSwASampleService" optimize="mtom"/>
    +            </endpoint>
    +        </send>
    +    </sequence>
    +
    +    <sequence name="pox_proxy">
    +        <property action="set" name="OUT_ONLY" value="true"/>
    +        <header name="Action" value="urn:placeOrder"/>
    +        <send>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService" format="soap11"/>
    +            </endpoint>
    +        </send>
    +    </sequence>
    +
    +    <sequence name="out">
    +        <send/>
    +    </sequence>
    +
    +    <proxy name="JMSFileUploadProxy" transports="jms">
    +        <target inSequence="mtom_proxy" outSequence="out"/>
    +        <parameter name="transport.jms.Wrapper">{http://services.samples/xsd}element</parameter>
    +    </proxy>
    +    <proxy name="JMSTextProxy" transports="jms">
    +        <target inSequence="text_proxy" outSequence="out"/>
    +        <parameter name="transport.jms.Wrapper">{http://services.samples/xsd}text</parameter>
    +    </proxy>
    +    <proxy name="JMSPoxProxy" transports="jms">
    +        <target inSequence="pox_proxy" outSequence="out"/>
    +        <parameter name="transport.jms.ContentType">application/xml</parameter>
    +    </proxy>
    +</definitions>
    + +

    Objective: Pure POX/Text and Binary JMS Proxy services - including +MTOM

    + +

    Prerequisites:
    +Configure JMS for ESB (Refer notes)
    +Start the Synapse configuration numbered 252: i.e. wso2esb-samples -sn 252
    +Start the Axis2 server and deploy the SimpleStockQuoteService and the +MTOMSwASampleService if not already done

    + +

    This configuration creates three JMS proxy services named +JMSFileUploadProxy, JMSTextProxy and JMSPoxProxy exposed over JMS queues with +the same names as the services. The first part of this example demonstrates +the pure text message support with JMS, where a user sends a space separated +text JMS message of the form "<price> <qty> <symbol>". ESB +converts this message into a SOAP message and sends this to the +SimpleStockQuoteServices' placeOrder operation. ESB uses the script mediator +to transform the text message into a XML payload using the Javascript support +available to tokenize the string. The proxy service property named +"transport.jms.Wrapper" defines a custom wrapper element QName, to be used +when wrapping text/binary content into a SOAP envelope.

    + +

    Execute JMS client as follows. This will post a pure text JMS message with +the content defined (e.g. "12.33 1000 ACP") to the specified JMS destination +- dynamicQueues/JMSTextProxy

    +
    ant jmsclient -Djms_type=text -Djms_payload="12.33 1000 ACP" -Djms_dest=dynamicQueues/JMSTextProxy
    + +

    Following the debug logs, you could notice that ESB received the JMS text +message and transformed it into a SOAP payload as follows. Notice that the +wrapper element "{http://services.samples/xsd}text" has been used to hold the +text message content.

    +
    [JMSWorker-1] DEBUG ProxyServiceMessageReceiver - Body :
    +<?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    +  <soapenv:Body><axis2ns1:text xmlns:axis2ns1="http://services.samples/xsd">12.33 1000 ACP</axis2ns1:text></soapenv:Body>
    +</soapenv:Envelope>
    + +

    Now, you could see how the script mediator created a stock quote request +by tokenizing the text as follows, and sent the message to the placeOrder +operation of the SimpleStockQuoteService.

    +
    [JMSWorker-1] DEBUG AddressEndpoint - Sending message to endpoint :: name = AnonymousEndpoints resolved address = http://localhost:9000/services/SimpleStockQuoteService
    +[JMSWorker-1] DEBUG AddressEndpoint - SOAPAction: urn:placeOrder
    +[JMSWorker-1] DEBUG AddressEndpoint - WSA-Action: urn:placeOrder
    +[JMSWorker-1] DEBUG AddressEndpoint - Body :
    +<?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body>
    +  <m:placeOrder xmlns:m="http://services.samples/xsd"><m:order><m:price>12.33</m:price><m:quantity>1000</m:quantity><m:symbol>ACP</m:symbol></m:order>
    +</m:placeOrder></soapenv:Body></soapenv:Envelope>
    + +

    The sample Axis2 server would now accept the one way message and issue the +following message:

    +
    Wed Apr 25 19:50:56 LKT 2007 samples.services.SimpleStockQuoteService :: Accepted order for : 1000 stocks of ACP at $ 12.33
    + +

    The next section of this example demonstrates how a pure binary JMS +message could be received and processed through ESB. The configuration +creates a proxy service named 'JMSFileUploadProxy' that accepts binary +messages and wraps them into a custom element +'{http://services.samples/xsd}element'. The received message is then +forwarded to the MTOMSwASampleService using the SOAP action +'urn:oneWayUploadUsingMTOM' and optimizing binary conent using MTOM. To +execute this sample, use the JMS client to publish a pure binary JMS message +containing the file +'./../../repository/samples/resources/mtom/asf-logo.gif' to the JMS +destination 'dynamicQueues/JMSFileUploadProxy' as follows:

    +
    ant jmsclient -Djms_type=binary -Djms_dest=dynamicQueues/JMSFileUploadProxy -Djms_payload=./../../repository/samples/resources/mtom/asf-logo.gif
    + +

    Examining the ESB debug logs reveals that the binary content was received +over JMS and wrapped with the specified element into a SOAP infoset as +follows:

    +
    [JMSWorker-1] DEBUG ProxyServiceMessageReceiver - Proxy Service JMSFileUploadProxy received a new message...
    +...
    +[JMSWorker-1] DEBUG ProxyServiceMessageReceiver - Body :
    +<?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    +<soapenv:Body><axis2ns1:element xmlns:axis2ns1="http://services.samples/xsd">R0lGODlhgw...AAOw==</axis2ns1:element></soapenv:Body>
    +</soapenv:Envelope>
    + +

    Thereafter the message was sent as a MTOM optimized message as specified +by the 'format=mtom' attribute of the endpoint, to the MTOMSwASampleService +using the SOAP action 'urn:oneWayUploadUsingMTOM'. Once received by the +sample service, it is saved into a temporary file and could be verified for +correctness.

    +
    Wrote to file : ./../../work/temp/sampleServer/mtom-29208.gif
    + +

    The final section of this example shows how a POX JMS message received by +ESB is sent to the SimpleStockQuoteService as a SOAP message. Use the JMS +client as follows to create a POX (Plain Old XML) message with a stock quote +request payload (without a SOAP envelope), and send it to the JMS destination +'dynamicQueues/JMSPoxProxy' as follows:

    +
    ant jmsclient -Djms_type=pox -Djms_dest=dynamicQueues/JMSPoxProxy -Djms_payload=MSFT
    + +

    You can see that ESB received the POX message and displays it as follows +in the debug logs, and then converts it into a SOAP payload and sends to the +SimpleStockQuoteService after setting the SOAP action as 'urn:placeOrder'. +

    + +
    [JMSWorker-1] DEBUG ProxyServiceMessageReceiver - Proxy Service JMSPoxProxy received a new message...
    +...
    +[JMSWorker-1] DEBUG ProxyServiceMessageReceiver - Body :
    +<?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><m:placeOrder xmlns:m="http://services.samples/xsd">
    +    <m:order>
    +        <m:price>172.39703010684752</m:price>
    +        <m:quantity>19211</m:quantity>
    +        <m:symbol>MSFT</m:symbol>
    +    </m:order>
    +</m:placeOrder></soapenv:Body></soapenv:Envelope>
    +[JMSWorker-1] DEBUG ProxyServiceMessageReceiver - Using the sequence named pox_proxy for message mediation
    +...
    +[JMSWorker-1] DEBUG HeaderMediator - Setting header : Action to : urn:placeOrder
    +...
    +[JMSWorker-1] DEBUG AddressEndpoint - Sending message to endpoint :: name = AnonymousEndpoints resolved address = http://localhost:9000/services/SimpleStockQuoteService
    +[JMSWorker-1] DEBUG AddressEndpoint - SOAPAction: urn:placeOrder
    +[JMSWorker-1] DEBUG AddressEndpoint - Body :
    +<?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><m:placeOrder xmlns:m="http://services.samples/xsd">
    +    <m:order>
    +        <m:price>172.39703010684752</m:price>
    +        <m:quantity>19211</m:quantity>
    +        <m:symbol>MSFT</m:symbol>
    +    </m:order>
    +</m:placeOrder></soapenv:Body></soapenv:Envelope>
    +[JMSWorker-1] DEBUG Axis2FlexibleMEPClient - sending [add = false] [sec = false] [rm = false] [ mtom = false] [ swa = false] [ force soap=true; pox=false] [ to null] 
    + +

    The sample Axis2 server displays a successful message on the receipt of +the message as:

    +
    Wed Apr 25 20:24:50 LKT 2007 samples.services.SimpleStockQuoteService :: Accepted order for : 19211 stocks of MSFT at $ 172.39703010684752
    + +

    Sample 253: One way bridging from JMS to http and +replying with a 202 Accepted response

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +
    +    <proxy name="JMStoHTTPStockQuoteProxy" transports="jms">
    +        <target>
    +            <inSequence>
    +                <property action="set" name="OUT_ONLY" value="true"/>
    +            </inSequence>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +            <outSequence>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +
    +    <proxy name="OneWayProxy" transports="http">
    +        <target>
    +            <inSequence>
    +                <log level="full"/>
    +            </inSequence>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +            <outSequence>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +
    +</definitions>
    + +

    Objective: Demonstrate one way message bridging from JMS to http +and replying with a http 202 Accepted response

    + +

    Prerequisites:
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already +done

    + +

    Start the Synapse configuration numbered 253: i.e. wso2esb-samples -sn 253 +

    + +

    This example invokes the one-way 'placeOrder' operation on the +SimpleStockQuoteService using the Axis2 ServiceClient.fireAndForget() API at +the client. To test this, use 'ant -Dmode=placeorder...' and you will notice +the one way JMS message flowing through ESB into the sample Axis2 server +instance over http, and Axis2 acknowledging it with a http 202 Accepted +response.

    +
    ant stockquote -Dmode=placeorder -Dtrpurl="jms:/JMStoHTTPStockQuoteProxy?transport.jms.ConnectionFactoryJNDIName=QueueConnectionFactory&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&java.naming.provider.url=tcp://localhost:61616&transport.jms.ContentTypeProperty=Content-Type&transport.jms.DestinationType=queue"
    +
    SimpleStockQuoteService :: Accepted order for : 7482 stocks of IBM at $ 169.27205579038733
    + +

    The second example shows how ESB could be made to respond with a http 202 +Accepted response to a request received. The proxy service simply logs the +message received and acknowledges it. On the ESB console you could see the +logged message, and if TCPMon was used at the client, you would see the 202 +Accepted response sent back to the client from ESB

    +
    ant stockquote -Dmode=placeorder -Dtrpurl=http://localhost:8280/services/OneWayProxy
    +
    HTTP/1.1 202 Accepted
    +Content-Type: text/xml; charset=UTF-8
    +Host: 127.0.0.1
    +SOAPAction: "urn:placeOrder"
    +Date: Sun, 06 May 2007 17:20:19 GMT
    +Server: Synapse-HttpComponents-NIO
    +Transfer-Encoding: chunked
    +
    +0
    + +

    Sample 254: Using the file system as transport medium +using VFS transport listener and sender

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +        <proxy name="StockQuoteProxy" transports="vfs">
    +                <parameter name="transport.vfs.FileURI">file:///home/user/test/in</parameter> <!--CHANGE-->
    +                <parameter name="transport.vfs.ContentType">text/xml</parameter>
    +                <parameter name="transport.vfs.FileNamePattern">.*\.xml</parameter>
    +                <parameter name="transport.PollInterval">15</parameter>
    +                <parameter name="transport.vfs.MoveAfterProcess">file:///home/user/test/original</parameter> <!--CHANGE-->
    +                <parameter name="transport.vfs.MoveAfterFailure">file:///home/user/test/original</parameter> <!--CHANGE-->
    +                <parameter name="transport.vfs.ActionAfterProcess">MOVE</parameter>
    +                <parameter name="transport.vfs.ActionAfterFailure">MOVE</parameter>
    +
    +                <target>
    +                        <endpoint>
    +                                <address format="soap12" uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                        </endpoint>
    +                        <outSequence>
    +                                <property name="transport.vfs.ReplyFileName"
    +                                          expression="fn:concat(fn:substring-after(get-property('MessageID'), 'urn:uuid:'), '.xml')" scope="transport"/>
    +                                <property action="set" name="OUT_ONLY" value="true"/> 
    +                                <send>
    +                                        <endpoint>
    +                                                <address uri="vfs:file:///home/user/test/out"/> <!--CHANGE-->
    +                                        </endpoint>
    +                                </send>
    +                        </outSequence>
    +                </target>
    +                <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +        </proxy>
    +</definitions> 
    + +

    Objective: Using the file system as transport medium using VFS +transport listener and sender

    + +

    Start the Axis2 server and deploy the SimpleStockQuoteService if not +already done

    + +

    Create three new directories in a test directory. e.g. in, out, original +in /home/user/test. Open +ESB_HOME/repository/samples/synapse_sample_254.xml and edit the following +values. Change transport.vfs.FileURI, transport.vfs.MoveAfterProcess, +transport.vfs.MoveAfterFailure parameter values to the above in, original, +original directories respectively. Change outSequence endpoint address uri to +out directory with the prefix vfs:. Values you have to change are +marked with <!--CHANGE-->.

    + +

    In the axis2.xml uncomment the VFS transport listener and sender.

    + +

    Start the Synapse configuration numbered 254: i.e. wso2esb-samples -sn 254 +

    + +

    Copy ESB_HOME/repository/samples/resources/vfs/test.xml to the +directory given in transport.vfs.FileURI above.

    + +

    test.xml file content is as follows

    +
    <?xml version='1.0' encoding='UTF-8'?>
    +        <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://www.w3.org/2005/08/addressing">
    +        <soapenv:Body>
    +                <m0:getQuote xmlns:m0="http://services.samples">
    +                        <m0:request>
    +                                <m0:symbol>IBM</m0:symbol>
    +                        </m0:request>
    +                </m0:getQuote>
    +        </soapenv:Body>
    +</soapenv:Envelope>
    + +

    VFS transport listener will pick the file from in directory and +send it to the Axis2 service. The request XML file will be moved to +original directory. The response from the Axis2 server will be saved +to out directory.

    +

    Note: Please make sure to uncomment "VFSTransportListener" and "VFSTransportSender" in the axis2 configuration.(axis2.xml)

    + +

    Sample 255: Switching from ftp transport listener to +mail transport sender

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +        <proxy name="StockQuoteProxy" transports="vfs">
    +                <parameter name="transport.vfs.FileURI">vfs:ftp://guest:guest@localhost/test?vfs.passive=true</parameter> <!--CHANGE-->
    +                <parameter name="transport.vfs.ContentType">text/xml</parameter>
    +                <parameter name="transport.vfs.FileNamePattern">.*\.xml</parameter>
    +                <parameter name="transport.PollInterval">15</parameter>
    +
    +                <target>
    +                        <inSequence>
    +                                <header name="Action" value="urn:getQuote"/>
    +                        </inSequence>
    +                        <endpoint>
    +                                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                        </endpoint>
    +                        <outSequence>
    +                                <property action="set" name="OUT_ONLY" value="true"/>
    +                                <send>
    +                                        <endpoint>
    +                                                <address uri="mailto:user@host"/> <!--CHANGE-->
    +                                        </endpoint>
    +                                </send>
    +                        </outSequence>
    +                </target>
    +                <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +        </proxy>
    +</definitions> 
    + +

    Objective: Switching from ftp transport listener to mail transport +sender

    + +

    Prerequisites:
    +You will need access to an FTP server and an SMTP server to try this sample. +

    + +

    Start the Axis2 server and deploy the SimpleStockQuoteService if not +already done

    + +

    Enable mail transport sender in the ESB axis2.xml. See Setting up mail transport sender +

    + +

    Create a new test directory in the FTP server. Open +ESB_HOME/repository/samples/synapse_sample_255.xml and edit the following +values. Change transport.vfs.FileURI parameter value point to the test +directory at the FTP server. Change outSequence endpoint address uri email +address to a working email address. Values you have to change are marked with +<!--CHANGE-->.

    + +

    Start the Synapse configuration numbered 255: i.e. wso2esb-samples -sn 255 +

    + +

    Copy ESB_HOME/repository/samples/resources/vfs/test.xml to the ftp +directory given in transport.vfs.FileURI above.

    + +

    VFS transport listener will pick the file from the directory in the ftp +server and send it to the Axis2 service. The file in the ftp directory will +be deleted. The response will be sent to the given email address.

    + +

    Sample 256: Proxy services with the mail transport +

    +
    <!-- Using the mail transport -->
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <proxy name="StockQuoteProxy" transports="mailto">
    +
    +        <parameter name="transport.mail.Address">synapse.demo.1@gmail.com</parameter>
    +        <parameter name="transport.mail.Protocol">pop3</parameter>
    +        <parameter name="transport.PollInterval">5</parameter>
    +        <parameter name="mail.pop3.host">pop.gmail.com</parameter>
    +        <parameter name="mail.pop3.port">995</parameter>
    +        <parameter name="mail.pop3.user">synapse.demo.1</parameter>
    +        <parameter name="mail.pop3.password">mailpassword</parameter>
    +        <parameter name="mail.pop3.socketFactory.class">javax.net.ssl.SSLSocketFactory</parameter>
    +        <parameter name="mail.pop3.socketFactory.fallback">false</parameter>
    +        <parameter name="mail.pop3.socketFactory.port">995</parameter>
    +        <parameter name="transport.mail.ContentType">application/xml</parameter>
    +
    +        <target>
    +            <inSequence>
    +                <property name="senderAddress" expression="get-property('transport', 'From')"/>
    +                <log level="full">
    +                    <property name="Sender Address" expression="get-property('senderAddress')"/>
    +                </log>
    +                <send>
    +                    <endpoint>
    +                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +                    </endpoint>
    +                </send>
    +            </inSequence>
    +            <outSequence>
    +                <property name="Subject" value="Custom Subject for Response" scope="transport"/>
    +                <header name="To" expression="fn:concat('mailto:', get-property('senderAddress'))"/>
    +                <log level="full">
    +                    <property name="message" value="Response message"/>
    +                    <property name="Sender Address" expression="get-property('senderAddress')"/>
    +                </log>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +</definitions> 
    + +

    Objective: Using the mail transport with Proxy services +

    + +

    Prerequisites:
    +You will need access to an email account

    + +

    Start the Axis2 server and deploy the SimpleStockQuoteService if not +already done

    + +

    Enable mail transport listener in the ESB axis2.xml. Simply uncomment the relevant +transport receiver entry in the file.

    + +

    Enable mail transport sender in the ESB axis2.xml. See Setting up mail transport sender +

    + +

    Enable mail transport receiver in the ESB axis2.xml. See Setting up mail transport listener +

    + +

    Start the Synapse configuration numbered 256: i.e. wso2esb-samples -sn 256 +

    + +

    Send a plain/text email with the following body and any custom Subject +from your mail account.

    +
    <m0:getQuote xmlns:m0="http://services.samples"><m0:request><m0:symbol>IBM</m0:symbol></m0:request></m0:getQuote> 
    + +

    After a few seconds (e.g. 30s), you should receive a POX response in your +email account with the stock quote reply.

    +

    Note that in this sample we used the transport.mail.ContentType property to make sure +that the transport parses the request message as POX. If you remove this property, you may still +be able to send requests using a standard mail client if instead of writing the XML in the body of +the message, you add it as an attachment. In that case, you should use .xml as a suffix +for the attachment and format the request as a SOAP 1.1 message. Indeed, for a file with suffix +.xml the mail client will most likely use text/xml as the content type, exactly +as required for SOAP 1.1. Sending a POX message using this approach will be a lot trickier, +because most standard mail clients don't allow the user to explicitly set the content type.

    + +

    + Sample 257: Proxy services with the + FIX transport +

    +
    <!-- Using the FIX transport -->
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <proxy name="FIXProxy" transports="fix">
    +
    +        <parameter name="transport.fix.AcceptorConfigURL">file:/home/synapse_user/fix-config/fix-synapse.cfg</parameter>
    +        <parameter name="transport.fix.InitiatorConfigURL">file:/home/synapse_user/fix-config/synapse-sender.cfg</parameter>
    +        <parameter name="transport.fix.AcceptorMessageStore">file</parameter>
    +        <parameter name="transport.fix.InitiatorMessageStore">file</parameter>
    +
    +        <target>
    +            <endpoint>
    +                <address uri="fix://localhost:19876?BeginString=FIX.4.0&amp;SenderCompID=SYNAPSE&amp;TargetCompID=EXEC"/>
    +            </endpoint>
    +	    <inSequence>
    +		<log level="full"/>
    +	    </inSequence>
    +            <outSequence>
    +                <log level="full"/>
    +		<send/>
    +            </outSequence>
    +        </target>
    +    </proxy>
    +</definitions> 
    +

    + Objective: Demonstrate the usage of the FIX (Financial Information eXchange) transport with proxy services +

    +

    + Prerequisites:
    + You will need the two sample FIX applications that come with Quickfix/J + (Banzai and Executor). Configure the two applications to establish + sessions with the ESB. See + Configuring Sample FIX Applications +

    +

    + Start Banzai and Executor +

    +

    + Enable FIX transport in the Synapse axis2.xml. See Setting up FIX transport + +

    +

    + Configure Synapse for FIX samples. See + Configuring WSO2 ESB for FIX Samples +

    +

    + Open up the ESB_HOME/repository/samples/synapse_sample_257.xml file + and make sure that transport.fix.AcceptorConfigURL property points to the + fix-synapse.cfg file you created. Also make sure that transport.fix. + InitiatorConfigURL property points to the synapse-sender.cfg file you + created. Once done you can start the Synapse configuration numbered 257: + i.e. wso2esb-samples -sn 257. Note that the ESB creates a new FIX session with + Banzai at this point. +

    +

    + Send an order request from Banzai to the ESB. +

    +

    + WSO2 ESB will create a session with Executor and forward the order request. The + responses coming from the Executor will be sent back to Banzai. +

    +

    + Sample 258: Switching from HTTP to FIX +

    +
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <proxy name="FIXProxy">
    +
    +        <parameter name="transport.fix.InitiatorConfigURL">file:/home/synapse_user/fix-config/synapse-sender.cfg</parameter>
    +        <parameter name="transport.fix.InitiatorMessageStore">file</parameter>
    +        <parameter name="transport.fix.SendAllToInSequence">false</parameter>
    +        <parameter name="transport.fix.DropExtraResponses">true</parameter>
    +
    +        <target>
    +            <endpoint>
    +                <address uri="fix://localhost:19876?BeginString=FIX.4.0&amp;SenderCompID=SYNAPSE&amp;TargetCompID=EXEC"/>
    +            </endpoint>
    +	    <inSequence>
    +	    	<property name="transport.fix.ServiceName" value="FIXProxy" scope="axis2-client"/>
    +			<log level="full"/>
    +	    </inSequence>
    +        <outSequence>
    +            <log level="full"/>
    +			<send/>
    +        </outSequence>
    +        </target>
    +    </proxy>
    +</definitions> 
    +

    + Objective: Demonstrate switching from HTTP to FIX +

    +

    + Prerequisites:
    + You will need the Executor sample application that comes with Quickfix/J. + Configure Executor to establish a session with Synapse. See Configuring Sample FIX + Applications +

    +

    + Start Executor. +

    +

    + Enable FIX transport sender in the Synapse axis2.xml. See Setting up FIX transport + +

    +

    + Configure Synapse for FIX samples. See + Configuring Synapse for FIX Samples. There is no need to create the fix-synapse.cfg + file for this sample. Having only the synapse-sender.cfg file is sufficient. +

    +

    + Go to the ESB_HOME/repository/samples/synapse_sample_258.xml + file and make sure that transport.fix.InitiatorConfigURL property + points to the synapse-sender.cfg file you created. Once done you can + start the Synapse configuration numbered 258: i.e. wso2esb-samples -sn 258 +

    +

    + Invoke the FIX Client as follows. This command sends a FIX message + embedded in a SOAP message over HTTP. +

    +
    ant fixclient -Dsymbol=IBM -Dqty=5 -Dmode=buy -Daddurl=http://localhost:8280/services/FIXProxy
    +

    + Synapse will create a session with Executor and forward the order request. The + first response coming from the Executor will be sent back over HTTP. Executor + generally sends two responses for each incoming order request. But since the + response has to be forwarded over HTTP only one can be sent back to the client. +

    +

    +Sample 259: Switch from FIX to HTTP

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <localEntry key="xslt-key-req" src="file:repository/conf/sample/resources/transform/transform_fix_to_http.xslt" />
    +    <proxy name="FIXProxy" transports="fix">
    +        <target>
    +            <endpoint>
    +                <address
    +                    uri="http://localhost:9000/services/SimpleStockQuoteService" />
    +            </endpoint>
    +            <inSequence>
    +                <log level="full" />
    +                <xslt key="xslt-key-req" />
    +                <log level="full" />
    +            </inSequence>
    +            <outSequence>
    +                <log level="full" />
    +            </outSequence>
    +        </target>
    +    <parameter name="transport.fix.AcceptorConfigURL">
    +        file:repository/conf/sample/resources/fix/fix-synapse.cfg
    +    </parameter>
    +    <parameter name="transport.fix.AcceptorMessageStore">
    +        file
    +    </parameter>
    +   </proxy>
    +</definitions>
    +      
    +

    +Objective: Demonstrate the capability of switching between FIX to HTTP

    +

    +Prerequisites: +

    You will need the sample FIX blotter that come with Quickfix/J (Banzai). Configure the blotter to establish sessions with Synapse. See +Configuring Sample FIX Applications

    +

    Start the Axis2 server and deploy the SimpleStockQuoteService if not already deployed

    +

    Start Banzai

    +

    Enable FIX transport in the Synapse axis2.xml. See +Setting up FIX transport

    +

    Configure ESB for FIX samples. See +Configuring the ESB for FIX Samples

    +

    Open up the ESB_HOME/repository/samples/synapse_sample_259.xml file and make sure that transport.fix.AcceptorConfigURL property points to the fix-synapse.cfg file you created. Once done you can start the Synapse configuration numbered 259: i.e. wso2esb-samples -sn 259. Note that Synapse creates a new FIX session with Banzai at this point.

    +

    Send an order request from Banzai to Synapse. e.g. Buy DELL 1000 @ 100. User has to send a 'Limit' Order because price is a mandatory field for 'placeOrder' operation.

    +

    ESB will forward the order request to one-way 'placeOrder' operation on the SimpleStockQuoteService. ESB uses a simple XSLT mediator to transform the incoming FIX to a SOAP message.

    +
    <xsl:stylesheet version="2.0"
    +    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    +    xmlns:fn="http://www.w3.org/2005/02/xpath-functions">
    +    <xsl:output method="xml" omit-xml-declaration="yes" indent="yes" />
    +  <xsl:template match="/">
    +    <m0:placeOrder xmlns:m0="http://services.samples">
    +        <m0:order>
    +            <m0:price><xsl:value-of select="//message/body/field[@id='44']"/></m0:price>
    +            <m0:quantity><xsl:value-of select="//message/body/field[@id='38']"/></m0:quantity>
    +            <m0:symbol><xsl:value-of select="//message/body/field[@id='55']"/></m0:symbol>
    +        </m0:order>
    +    </m0:placeOrder>
    +   </xsl:template>
    +</xsl:stylesheet>
    +      
    +

    To get an idea about the various transport parameters being used in this sample see +FIX Transport Parameters.

    + +

    +Sample 260: Switch from FIX to AMQP

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <proxy name="FIXProxy" transports="fix">
    +        <target>
    +            <endpoint>
    +                <address uri="jms:/QpidStockQuoteService?transport.jms.ConnectionFactoryJNDIName=qpidConnectionfactory&amp;java.naming.factory.initial=org.apache.qpid.jndi.PropertiesFileInitialContextFactory&amp;java.naming.provider.url=repository/conf/sample/resources/fix/con.properties&amp;transport.jms.ReplyDestination=replyQueue"/>
    +            </endpoint>
    +            <inSequence>
    +                <log level="full" />
    +            </inSequence>
    +            <outSequence>
    +                <property name="transport.fix.ServiceName"
    +                    value="FIXProxy" scope="axis2-client" />
    +                <log level="full" />
    +                        <send />
    +            </outSequence>
    +        </target>
    +        <parameter name="transport.fix.AcceptorConfigURL">
    +            file:repository/conf/sample/resources/fix/fix-synapse.cfg
    +        </parameter>
    +        <parameter name="transport.fix.AcceptorMessageStore">
    +            file
    +        </parameter>
    +    </proxy>
    +</definitions>
    +

    +Objective: Demonstrate the capability of switching between FIX and AMQP protocols

    +

    +Prerequisites: +

    You will need the sample FIX blotter that comes with Quickfix/J (Banzai). Configure the blotter to establish sessions with Synapse. See +Configuring Sample FIX Applications

    +

    Configure the AMQP transport for WSO2 ESB. See +Configure ESB for AMQP Transport

    +

    Start the AMQP consumer, by switching to samples/axis2Client directory and running the consumer using the following command. Consumer will listen to the queue 'QpidStockQuoteService', accept the orders and reply to the queue 'replyQueue'.

    +
    ant amqpconsumer -Dpropfile=$ESB_HOME/repository/samples/resources/fix/direct.properties
    +

    Start Banzai

    +

    Enable FIX transport in the Synapse axis2.xml. See +Setting up FIX transport

    +

    Configure Synapse for FIX samples. See +Configuring Synapse for FIX Samples

    +

    Open up the ESB_HOME/repository/samples/synapse_sample_260.xml file and make sure that the transport.fix.AcceptorConfigURL property points to the fix-synapse.cfg file you created. Once done you can start the Synapse configuration numbered 260: i.e. wso2esb-samples -sn 260. Note that Synapse creates a new FIX session with Banzai at this point.

    +

    Send an order request from Banzai to Synapse. e.g. Buy DELL 1000 @ MKT.

    +

    Synapse will forward the order request by binding it to a JMS message payload and sending it to the AMQP consumer. AMQP consumer will send a execution back to Banzai.

    + +

    +Sample 261: Switch between FIX versions

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +     <proxy name="OrderProcesserProxy41" transports="fix">
    +        <target>
    +           <endpoint>
    +              <address uri="fix://localhost:19877?BeginString=FIX.4.1&amp;SenderCompID=SYNAPSE&amp;TargetCompID=EXEC"/>
    +           </endpoint>
    +           <inSequence><log level="full"/></inSequence>
    +           <outSequence><log level="full"/><send/></outSequence>
    +        </target>
    +        <parameter name="transport.fix.AcceptorConfigURL">file:repository/conf/sample/resources/fix/fix-synapse-m40.cfg</parameter>
    +        <parameter name="transport.fix.AcceptorMessageStore">file</parameter>
    +        <parameter name="transport.fix.InitiatorConfigURL">file:repository/conf/sample/resources/fix/synapse-sender-m.cfg</parameter>
    +        <parameter name="transport.fix.InitiatorMessageStore">file</parameter>
    +     </proxy>
    +</definitions>
    +

    +Objective: Demonstrate the capability of switching between FIX versions e.g. FIX4.0 to FIX4.1

    +

    +Prerequisites: +

    You will need the two sample FIX applications that come with Quickfix/J (Banzai and Executor). Configure the two applications to establish sessions with Synapse. See +Configuring Sample FIX Applications.

    +

    Add the following lines to the Banzai configuration file (banzai.cfg).

    +
    DataDictionary=~/etc/spec/FIX40-synapse.xml
    +

    Note: FIX40-synapse.xml can be found at $ESB_HOME/repository/sampless/resources/fix. This is a custom FIX data dictionary file that has added tag 150,151 to the execution messages (35=8) of FIX4.0. Make sure the DataDictionary property of the banzai.cfg points to this data dictionary file.

    +

    Add the following lines to the Executor configuration file (executor.cfg).

    +
    [session]
    +BeginString=FIX.4.1
    +SocketAcceptPort=19877
    +

    Start Banzai and Executor using the custom configuration files.

    +

    Enable FIX transport in the Synapse axis2.xml. See +Setting up FIX transport

    +

    Configure Synapse for FIX samples. We will be using two custom configuration files for Synapse in this sample. These two custom configuration files can be found at ESB_HOME/repository/conf/sample/resources/fix directory. The two files are called fix-synapse-m40.cfg and synapse-sender-m.cfg. You can point your Synapse configuration to these two files (this is already done in the supplied synapse_sample_261.xml file) or you may create copies of them and point the Synapse configuration to the copies. In either case make sure that the properties like FileStorePath and FileLogPath in the two files point to valid locations in your local file system.

    +

    Open up the $ESB_HOME/repository/samples/synapse_sample_261.xml file and make sure that transport.fix.AcceptorConfigURL property points to the fix-synapse-m40.cfg file described above and transport.fix.InitiatorConfigURL points to the synapse-sender-m.cfg file described above. Once done you can start the Synapse configuration numbered 261: i.e. wso2esb-samples -sn 261. Note that Synapse creates a new FIX session with Banzai at this point.

    +

    Send an order request from Banzai to Synapse. e.g. Buy DELL 1000 @ MKT.

    +

    Synapse will forward the order request from FIX4.0 to the Executor that accepts FIX4.1 messages. Executor will send an ack and an execution back to Banzai.

    + +

    +Sample 262: CBR of FIX messages

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <sequence name="CBR_SEQ">
    +        <in>
    +            <switch source="//message/body/field[@id='55']">
    +                <case regex="GOOG">
    +                    <send>
    +                        <endpoint>
    +                            <address
    +                                uri="fix://localhost:19876?BeginString=FIX.4.0&amp;SenderCompID=SYNAPSE&amp;TargetCompID=EXEC" />
    +                        </endpoint>
    +                    </send>
    +                </case>
    +                <case regex="MSFT">
    +                    <send>
    +                        <endpoint>
    +                            <address
    +                                uri="fix://localhost:19877?BeginString=FIX.4.1&amp;SenderCompID=SYNAPSE&amp;TargetCompID=EXEC" />
    +                        </endpoint>
    +                    </send>
    +                </case>
    +                <default></default>
    +            </switch>
    +        </in>
    +        <out>
    +            <send />
    +        </out>
    +    </sequence>
    +    <proxy name="FIXProxy" transports="fix">
    +        <target inSequence="CBR_SEQ" />
    +        <parameter name="transport.fix.AcceptorConfigURL">
    +            file:repository/conf/sample/resources/fix/fix-synapse.cfg
    +        </parameter>
    +        <parameter name="transport.fix.AcceptorMessageStore">
    +            file
    +        </parameter>
    +        <parameter name="transport.fix.InitiatorConfigURL">
    +            file:repository/conf/sample/resources/fix/synapse-sender.cfg
    +        </parameter>
    +        <parameter name="transport.fix.InitiatorMessageStore">
    +            file
    +        </parameter>
    +    </proxy>
    +</definitions>
    +

    +Objective: Demonstrate the capability of CBR FIX messages

    +

    +Prerequisites: +

    You will need the two sample FIX applications that come with Quickfix/J (Banzai and Executor). Configure the two applications to establish sessions with Synapse. See +Configuring Sample FIX Applications

    +

    Add the following lines to banzai.cfg.

    +
    DataDictionary=~/etc/spec/FIX40-synapse.xml
    +

    Note: FIX40-synapse.xml can be found at $ESB_HOME/repository/samples/resources/fix. This is a custom FIX data dictionary file that has added tag 150,151 to the execution messages (35=8) of FIX4.0. Make sure the DataDictionary property of the banzai.cfg points to this data dictionary file.

    +

    Add the following lines to executor.cfg

    +
    [session]
    +BeginString=FIX.4.1
    +SocketAcceptPort=19877
    +

    Start Banzai and Executor using the custom config files.

    +

    Enable FIX transport in the Synapse axis2.xml. See +Setting up FIX transport

    +

    Configure Synapse for FIX samples. See +Configuring Synapse for FIX Samples

    +

    Open up the ESB_HOME/repository/samples/synapse_sample_262.xml file and make sure that transport.fix.AcceptorConfigURL property points to the fix-synapse.cfg file you created and transport.fix.InitiatorConfigURL points to the synapse-sender.cfg file you created. Once done you can start the Synapse configuration numbered 262: i.e. wso2esb-samples -sn 262. Note that Synapse creates a new FIX session with Banzai at this point.

    +

    Send an order request from Banzai to Synapse. e.g. Buy GOOG 1000 @ MKT, Buy MSFT 3000 @ MKT, Buy SUNW 500 @ 100.20

    +

    Synapse will forward the order requests with symbol 'GOOG' to FIX endpoint FIX-4.0 @ localhost:19876.

    +

    Synapse will forward the order requests with symbol 'MSFT' to FIX endpoint FIX-4.1 @ localhost:19877.

    +

    Synapse will not forward the orders with other symbols to any endpoint. (default case has kept blank in the configuration)

    + + +

    +Sample 263: Transport switching - JMS to http/s using JBoss Messaging(JBM)

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <proxy name="StockQuoteProxy" transports="jms">
    +        <target>
    +            <inSequence>
    +                <property action="set" name="OUT_ONLY" value="true"/>
    +            </inSequence>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +            <outSequence>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    +        <parameter name="transport.jms.ContentType">
    +            <rules>
    +                <jmsProperty>contentType</jmsProperty>
    +                <default>application/xml</default>
    +            </rules>
    +        </parameter>
    +    </proxy>
    +</definitions>
    +

    +Objective: Introduction to switching transports with proxy services. The JMS provider will be JBoss Messaging(JBM).

    +

    +Prerequisites: +

    Start the Axis2 server and deploy the SimpleStockQuoteService (Refer steps above) +

    Download, install and start JBM server, and configure Synapse to listen on JBM (refer notes below) +

    Start the ESB configuration numbered 263: i.e. wso2esb-samples -sn 263 +

    We need to configure the required queues in JBM. Add the following entry to JBM jms configuration inside file-config/stand-alone/non-clustered/jbm-jms.xml. +

    +
    +<queue name="StockQuoteProxy">
    +    <entry name="StockQuoteProxy"/>
    +</queue>
    +
    +

    Once you started the JBM server with the above changes you'll be able to see the following on STDOUT.

    +
    10:18:02,673 INFO [org.jboss.messaging.core.server.impl.MessagingServerImpl]  JBoss Messaging Server version 2.0.0.BETA3 (maggot, 104) started 
    +

    You also need to copy the jbm-core-client.jar, jbm-jms-client.jar, jnp-client.jar(these jars are inside $JBOSS_MESSAGING/client folder) and + jbm-transports.jar, netty.jar(these jars are from $JBOSS_MESSAGING/lib folder) jars from JBM into the $ESB_HOME/repository/components/lib directory. This was tested with JBM 2.0.0.BETA3

    + +

    You need to add the following configuration for Axis2 JMS transport listener in axis2.xml found at repository/conf/axis2.xml.

    +
    +<transportReceiver name="jms" class="org.apache.axis2.transport.jms.JMSListener">
    +    <parameter name="default" locked="false">
    +        <parameter name="java.naming.factory.initial">org.jnp.interfaces.NamingContextFactory</parameter>
    +        <parameter name="java.naming.provider.url">jnp://localhost:1099</parameter>
    +        <parameter name="java.naming.factory.url.pkgs">org.jboss.naming:org.jnp.interfaces</parameter>
    +        <parameter name="transport.jms.ConnectionFactoryJNDIName">ConnectionFactory</parameter>
    +    </parameter>
    +</transportReceiver>
    +
    +

    Once you start ESB configuration 263 and request for the WSDL of the proxy service (http://localhost:8280/services/StockQuoteProxy?wsdl) you will notice that its exposed only on the JMS transport. This is because the configuration specified this requirement in the proxy service definition.

    +

    Before running the JMS client you need to open the build.xml ant script and uncomment the following block under the +jmsclient target.

    +<!--<sysproperty key="java.naming.provider.url" value="${java.naming.provider.url}"/> +<sysproperty key="java.naming.factory.initial" value="${java.naming.factory.initial}"/> +<sysproperty key="java.naming.factory.url.pkg" value="${java.naming.factory.url.pkg}"/>--> +

    Now lets send a stock quote request on JMS, using the dumb stock quote client as follows:

    +
    ant jmsclient -Djms_type=pox -Djms_dest=StockQuoteProxy -Djms_payload=MSFT -Djava.naming.provider.url=jnp://localhost:1099 -Djava.naming.factory.initial=org.jnp.interfaces.NamingContextFactory -Djava.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
    +

    On the ESB debug(you'll need to enable debug log in ESB) log you will notice that the JMS listener received the request message as:

    +
    [JMSWorker-1] DEBUG ProxyServiceMessageReceiver -Proxy Service StockQuoteProxy received a new message...
    +

    Now if you examine the console running the sample Axis2 server, you will see a message indicating that the server has accepted an order as follows:

    +
    Accepted order for : 16517 stocks of MSFT at $ 169.14622538721846
    +

    In this sample, the client sends the request message to the proxy service exposed over JMS in Synsape. Synapse forwards this message to the HTTP EPR of the simple stock quote service hosted on the sample Axis2 server. +Note that the operation is out-only and no response is sent back to the client. The transport.jms.ContentType property +is necessary to allow the JMS transport to determine the content type of incoming messages. With the given configuration +it will first try to read the content type from the 'contentType' message property and fall back to 'application/xml' +(i.e. POX) if this property is not set. Note that the JMS client used in this example doesn't send any content type information.

    +

    Note: It is possible to instruct a JMS proxy service to listen to an already existing destination without creating a new one. To do this, use the parameter elements on the proxy service definition to specify the destination and connection factory etc.

    +

    e.g.

    +
    <parameter name="transport.jms.Destination">dynamicTopics/something.TestTopic</parameter>
    + +

    + Sample 264: Sending Two-Way Messages Using JMS transport +

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +   <proxy name="StockQuoteProxy" transports="http">
    +       <target>
    +           <endpoint>
    +                   <address uri="jms:/SimpleStockQuoteService?transport.jms.ConnectionFactoryJNDIName=QueueConnectionFactory&
    +                 java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&java.naming.provider.url=tcp://localhost:61616&transport.jms.DestinationType=queue"/>
    +           </endpoint>
    +           <inSequence>
    +               <property action="set" name="transport.jms.ContentTypeProperty" value="Content-Type" scope="axis2"/>
    +           </inSequence>
    +           <outSequence>
    +               <property action="remove" name="TRANSPORT_HEADERS" scope="axis2"/>
    +               <send/>
    +           </outSequence>
    +       <target>
    +       <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    +   </proxy>
    +</definitions>
    +

    + Objective: Demonstrate sending request response scenario with JMS transport +

    +

    + Prerequisites: +

    You need to set up ESB and axis2 server to use the JMS transport. See + Sample 251 for more details. +

    +

    + This sample is similar to the Sample 251. Only difference is we are expecting a response from the server. JMS transport uses transport.jms.ContentTypeProperty to + determine the content type of the response message. If this property is not set JMS transport treats the incoming message as plain text. +

    +

    + In the out path we remove the message context property TRANSPORT_HEADERS. If these property is not removed JMS headers will be passed to the client. +

    +

    Start ESB using sample 264.

    +
    wso2esb-samples -sn 264
    +

    Start Axis2 server with SimpleStockService deployed

    +

    Invoke the stockquote client using the following command.

    +
    ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy -Dsymbol=MSFT
    +

    The sample Axis2 server console will print a message indicating that it has received the request:

    +
    Generating quote for : MSFT
    +

    In the client side it shoud print a message indicating it has received the price.

    +
     Standard :: Stock price = $154.31851804993238
    + +

    Sample 265: Using vfs transport to access a windows share +

    +
    <!-- Using the vfs transport to access a windows share -->
    +<definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <proxy name="StockQuoteProxy" transports="vfs">
    +		<parameter name="transport.vfs.FileURI">smb://host/test/in</parameter> <!--CHANGE-->
    +        <parameter name="transport.vfs.ContentType">text/xml</parameter>
    +        <parameter name="transport.vfs.FileNamePattern">.*\.xml</parameter>
    +        <parameter name="transport.PollInterval">15</parameter>
    +		<parameter name="transport.vfs.MoveAfterProcess">smb://host/test/original</parameter> <!--CHANGE-->
    +		<parameter name="transport.vfs.MoveAfterFailure">smb://host/test/original</parameter> <!--CHANGE-->
    +        <parameter name="transport.vfs.ActionAfterProcess">MOVE</parameter>
    +        <parameter name="transport.vfs.ActionAfterFailure">MOVE</parameter>
    +
    +        <target>
    +            <endpoint>
    +                <address format="soap12" uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +            <outSequence>
    +                <property name="transport.vfs.ReplyFileName"
    +                          expression="fn:concat(fn:substring-after(get-property('MessageID'), 'urn:uuid:'), '.xml')" scope="transport"/>
    +                <property action="set" name="OUT_ONLY" value="true"/>
    +                <send>
    +                    <endpoint>
    +						<address uri="vfs:smb://host/test/out"/> <!--CHANGE-->
    +                    </endpoint>
    +                </send>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +</definitions>
    +
    + +

    Objective: Using vfs transport to access a windows share +

    + +

    Prerequisites:
    +You will need access a windows shared folder. Just create a folder(called 'test') on a windows machine +and create three sub folders in, out and original inside that folder.Then assign the permission +to the network users to read and write into the root 'test' folder and the folders inside that directory.

    +

    +Open ESB_HOME/repository/samples/synapse_sample_265.xml and edit the following values. Change transport.vfs.FileURI, +transport.vfs.MoveAfterProcess, transport.vfs.MoveAfterFailure parameter values to the above in, original, original +directories respectively. Change outSequence endpoint address uri to out directory with the prefix vfs:. +Values you have to change are marked with <!--CHANGE-->. +

    + +

    Copy ESB_HOME/repository/samples/resources/vfs/test.xml to the directory given in transport.vfs.FileURI above.

    + +

    Start the Axis2 server and deploy the SimpleStockQuoteService if not +already done

    + +

    Enable vfs transport receiver and the vfs transport sender in the ESB axis2.xml. Just uncomment the + VFSTransportListener and the VFSTransportSender in axis2.xml

    + +

    Start the Synapse configuration numbered 265: i.e. wso2esb-samples -sn 265 +

    + +

    VFS transport listener will pick the file from in directory and send it to the Axis2 service. The request XML +file will be moved to original directory. The response from the Axis2 server will be saved to out directory.

    + + + + + + +

    Sample 266: Switching from TCP to HTTP/S +

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse"
    +             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    +             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">
    +
    +    <proxy name="StockQuoteProxy" transports="tcp">
    +        <target>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +            <inSequence>
    +                <log level="full"/>
    +                <property name="OUT_ONLY" value="true"/>
    +            </inSequence>
    +        </target>
    +    </proxy>
    +
    +</definitions>
    +
    + +

    Objective: Demonstrate receiving SOAP messages over TCP and forwarding them over HTTP +

    + +

    Prerequisites:
    +You need to configure Synpase to use the TCP transport.The sample Axis2 client should also be setup to send TCP requests. Refer Setting Up the TCP Transport section in the sample setup guide for more details. +Start Synpase using sample 266: ie synapse -sample 266
    +Start Axis2 server with SimpleStockService deployed +

    +

    + This sample is similar to Sample 250 . Only difference is instead of the JMS transport we will be using the TCP transport to receive messages. TCP is not an application layer protocol. Hence there are no application level headers available in the requests. Synapse has to simply read the XML content coming through the socket and dispatch it to the right proxy service based on the information available in the message payload itself. The TCP transport is capable of dispatching requests based on addressing headers or the first element in the SOAP body. In this sample, we will get the sample client to send WS-Addressing headers in the request. Therefore the dispatching will take place based on the addressing header values. + +Invoke the stockquote client using the following command. Note the TCP URL in the command. +

    +
    ant stockquote -Daddurl=tcp://localhost:6060/services/StockQuoteProxy -Dmode=placeorder
    +

    + The TCP transport will receive the message and hand it over to the mediation engine. Synapse will dispatch the request to the StockQuoteProxy service based on the addressing header values. +
    The sample Axis2 server console will print a message indicating that it has received the request: +

    +
    Thu May 20 12:25:01 IST 2010 samples.services.SimpleStockQuoteService  :: Accepted order #1 for : 17621 stocks of IBM at $ 73.48068475255796
    + + +

    Sample 267: Switching from UDP to HTTP/S +

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse"
    +             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    +             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">
    +
    +    <proxy name="StockQuoteProxy" transports="udp">
    +        <target>
    +            <endpoint>
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +            <inSequence>
    +                <log level="full"/>
    +                <property name="OUT_ONLY" value="true"/>
    +            </inSequence>
    +        </target>
    +        <parameter name="transport.udp.port">9999</parameter>
    +        <parameter name="transport.udp.contentType">text/xml</parameter>
    +        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +</definitions>
    +
    + +

    Objective: Demonstrate receiving SOAP messages over UDP and forwarding them over HTTP +

    + +

    Prerequisites:
    +You need to configure Synpase to use the TCP transport.The sample Axis2 client should also be setup to send TCP requests. Refer Setting Up the TCP Transport section in the sample setup guide for more details. +Start Synpase using sample 267: ie synapse -sample 267
    +Start Axis2 server with SimpleStockService deployed +

    +

    + This sample is similar to Sample 266. Only difference is instead of the TCP transport we will be using the UDP transport to receive messages. + +Invoke the stockquote client using the following command. Note the TCP URL in the command. +

    +
    ant stockquote -Daddurl=udp://localhost:9999?contentType=text/xml -Dmode=placeorder
    +

    + Since we have configured the content type as text/xml for the proxy service, incoming messages will be processed as SOAP 1.1 messages. +
    The sample Axis2 server console will print a message indicating that it has received the request: +

    +
    Thu May 20 12:25:01 IST 2010 samples.services.SimpleStockQuoteService  :: Accepted order #1 for : 17621 stocks of IBM at $ 73.48068475255796
    +
    + + +

    Sample 268: Proxy services with the Local transport +

    +
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    +    <proxy xmlns="http://ws.apache.org/ns/synapse" name="LocalTransportProxy"
    +           transports="https http" startOnLoad="true" trace="disable">
    +        <target>
    +            <endpoint name="ep1">
    +                <address uri="local://localhost/services/SecondProxy"/>
    +            </endpoint>
    +            <inSequence>
    +                <log level="full"/>
    +                <log level="custom">
    +                    <property name="LocalTransportProxy" value="In sequence of LocalTransportProxy invoked!"/>
    +                </log>
    +            </inSequence>
    +            <outSequence>
    +                <log level="custom">
    +                    <property name="LocalTransportProxy" value="Out sequence of LocalTransportProxy invoked!"/>
    +                </log>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +    <proxy xmlns="http://ws.apache.org/ns/synapse" name="SecondProxy"
    +           transports="https http" startOnLoad="true" trace="disable">
    +        <target>
    +            <endpoint name="ep2">
    +                <address uri="local://localhost/services/StockQuoteProxy"/>
    +            </endpoint>
    +            <inSequence>
    +                <log level="full"/>
    +                <log level="custom">
    +                    <property name="SecondProxy" value="In sequence of Second proxy invoked!"/>
    +                </log>
    +            </inSequence>
    +            <outSequence>
    +                <log level="custom">
    +                    <property name="SecondProxy" value="Out sequence of Second proxy invoked!"/>
    +                </log>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +    <proxy xmlns="http://ws.apache.org/ns/synapse" name="StockQuoteProxy"
    +           startOnLoad="true">
    +        <target>
    +            <endpoint name="ep3">
    +                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    +            </endpoint>
    +            <outSequence>
    +                <log level="custom">
    +                    <property name="StockQuoteProxy"
    +                              value="Out sequence of StockQuote proxy invoked!"/>
    +                </log>
    +                <send/>
    +            </outSequence>
    +        </target>
    +        <publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
    +    </proxy>
    +</definitions>
    +
    + +

    Objective: Proxy services with the Local transport +

    + +

    This sample contains three proxy services. The stockquote client invokes the LocalTransportProxy. + Then the message will be sent to the SecondProxy and then it will be sent to the StockQuoteProxy. + The StockQuoteProxy will invoke the backend service and return the response to the client. + In this sample, the communication between proxy services are done through the Local transport. + Since Local transport calls are in-JVM calls, it will reduce the time taken for the communication + between proxy services.

    + +

    Prerequisites:
    +Start the Synapse configuration numbered 268: i.e. wso2esb-samples -sn 268
    +Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

    + +

    Execute the stock quote client by requesting for a stock quote on the +proxy service as follows:

    +
    ant stockquote -Daddurl=http://localhost:8280/services/LocalTransportProxy
    + + + diff --git a/docs/xdoc/samples_index.xml b/docs/xdoc/samples_index.xml new file mode 100644 index 0000000000..98e3c0238e --- /dev/null +++ b/docs/xdoc/samples_index.xml @@ -0,0 +1,414 @@ + + + + + + + + + WSO2 ESB - Samples Guide Index + + + + + [ Documentation Index ] +

    Running the WSO2 Enterprise Service Bus (ESB) Samples

    + +

    While the Samples Setup Guide +document above gives you a generic description on how to set up and run +the WSO2 ESB samples, this document takes each sample, one by one and +discusses the objective of the sample, its prerequisites, and its expected +behavior when the sample is built.

    + +

    Note: The ESB configurations listed below, with each +sample, is the raw source XML serialization of the sample configuration. This +may be viewed graphically through the WSO2 ESB administration console after +logging into the console.

    + +

    Table of Contents

    + +
    + +
    + + + diff --git a/docs/xdoc/samples_setup_guide.xml b/docs/xdoc/samples_setup_guide.xml new file mode 100644 index 0000000000..041ef5f2b9 --- /dev/null +++ b/docs/xdoc/samples_setup_guide.xml @@ -0,0 +1,846 @@ + + + + + + + + + WSO2 ESB - Samples Setup Guide + + + + + [ Documentation Index ] +

    WSO2 Enterprise Service Bus (ESB) Samples Setup Guide

    + +

    Overview

    + +

    The WSO2 ESB ships with a set of working examples that demonstrate some of +the basic features and capabilities of itself. A set of sample clients and +services are provided in addition to the sample configurations. Scripts are +provided to execute the sample scenarios as explained below.

    + +

    This document provides step-by-step instructions on how to install the +pre-requisites, and set up the samples - generic instructions on how to start +the sample server, deploy a service, and run the client.

    + +

    Table of Contents

    + + + +

    Prerequisites

    + +

    You will need a Java development kit / JRE version 1.5.x or later and +Apache Ant 1.7.0 or later, at a minimum, to try out the samples. Ant can be +downloaded from http://ant.apache.org. +The JMS examples can be executed against an ActiveMQ installation by default +(or another JMS provider with configuration) and any HTTPS examples would +require a JDK version 1.5 or later.

    + +

    Once you setup ant go to the bin directory of the distribution and run +the build.xml file which resides in that directory using ant. You could do this +by typing 'ant' on a console in this directory.

    + +

    Note*: The samples and the documentation assumes that you are running the +ESB in DEBUG mode. You can switch from the default INFO log messages to DEBUG +log messages by changing the line "log4j.category.org.apache.synapse=INFO" as +"log4j.category.org.apache.synapse=DEBUG" in the +lib/log4j.properties file.

    + +

    Understanding the Samples

    + + + + + + + + + + + + + + + + + + + +
    Client WSO2 ESB Service
    ant stockquote ./wso2esb-samples.sh -sn <n> SimpleStockQuoteService
    SecureStockQuoteService etc.
    + +

    The above table depicts the interactions between the clients, the ESB +and services at a high level. The Clients are able to send SOAP/REST or POX +messages over transports such as HTTP/HTTPS or JMS with WS-Addressing, +WS-Security, or WS-Reliable messaging. They could send binary optimized +content using MTOM or SwA or binary or plain text JMS messages. After +mediation through the ESB, the requests are passed over to the sample +services. The sample clients and services are explained below.

    + +

    Using the Sample Clients

    + +

    The sample clients can be executed from the samples/axis2Client directory +through the provided Ant script. Simply executing 'ant' displays the +available clients and some of the sample options used to configure them. The +sample clients available are listed below:

    + +

    1. Stock Quote Client

    + +

    This is a simple SOAP client that could send stock quote requests, and +receive and display the last sale price for a stock symbol.

    +
    ant stockquote [-Dsymbol=IBM|MSFT|SUN|..]
    +  [-Dmode=quote | customquote | fullquote | placeorder | marketactivity]
    +  [-Daddurl=http://localhost:9000/services/SimpleStockQuoteService]
    +  [-Dtrpurl=http://localhost:8280/] [-Dprxurl=http://localhost:8280/]
    +  [-Dpolicy=../../repository/samples/resources/policy/policy_1.xml]
    + +

    The client is able to operate in the following modes, and send the +payloads listed below as SOAP messages:

    + +
      +
    • quote - sends a quote request for a single stock as follows. The + response contains the last sales price for the stock which would be + displayed. +
      <m:getQuote xmlns:m="http://services.samples/xsd">
      +  <m:request>
      +    <m:symbol>IBM</m:symbol>
      +  </m:request>
      +</m:getQuote>
      +
    • +
    • customquote - sends a quote request in a custom format. The ESB would + transform this custom request into the standard stock quote request + format and send it to the service. Upon receipt of the response, it would + be transformed again to a custom response format and returned to the + client, which will then display the last sales price. +
      <m0:checkPriceRequest xmlns:m0="http://services.samples/xsd">
      +  <m0:Code>symbol</m0:Code>
      +</m0:checkPriceRequest>
      +
    • +
    • fullquote - gets quote reports for the stock over a number of days + (i.e., last 100 days of the year). +
      <m:getFullQuote xmlns:m="http://services.samples/xsd">
      +  <m:request>
      +    <m:symbol>IBM</m:symbol>
      +  </m:request>
      +</m:getFullQuote>
      +
    • +
    • placeorder - places an order for stocks using a one way request +
      <m:placeOrder xmlns:m="http://services.samples/xsd">
      +  <m:order>
      +    <m:price>3.141593E0</m:price>
      +    <m:quantity>4</m:quantity>
      +    <m:symbol>IBM</m:symbol>
      +  </m:order>
      +</m:placeOrder>
      +
    • +
    • marketactivity - gets a market activity report for the day (i.e., + quotes for multiple symbols) +
      <m:getMarketActivity xmlns:m="http://services.samples/xsd">
      +  <m:request>
      +    <m:symbol>IBM</m:symbol>
      +    ...
      +    <m:symbol>MSFT</m:symbol>
      +  </m:request>
      +</m:getMarketActivity>
      +
    • +
    + +

    Note : See samples/axis2Client/src/samples/common/StockQuoteHandler.java +for sample responses expected by the clients.

    + +

    Smart Client Mode:

    + +

    The 'addurl' property sets the WS-Addressing EPR, and the 'trpurl' sets a +transport URL for a message. Thus by specifying both properties, the client +can operate in the 'smart client' mode, where the addressing EPR could +specify the ultimate receiver, while the transport URL set to the ESB ensures +that any necessary mediation takes place before the message is delivered to +the ultimate reciver.

    + +
    e.g: ant stockquote -Daddurl=<addressingEPR> -Dtrpurl=<esb>
    + +

    Gateway / Dumb Client Mode:

    + +

    By specifying only a transport URL, the client operates in the 'dumb +client' mode, where it sends the message to the ESB and depends on the ESB +rules for proper mediation and routing of the message to the ultimate +destination.

    + +
    e.g: ant stockquote -Dtrpurl=<esb>
    + +

    Proxy Client Mode:

    + +

    In this mode, the client uses the 'prxurl' as an HTTP proxy to send the +request. Thus by setting the 'prxurl' to the ESB, the client could ensure +that the message would reach the ESB for mediation. The client could +optionally set a WS-Addressing EPR if required.

    + +
    e.g: ant stockquote -Dprxurl=<esb> [-Daddurl=<addressingEPR>]
    + +

    Specifying a Policy

    + +

    By specifying a WS-Policy using the 'policy' property, QoS aspects such as +WS-Security could be enforced on the request. The policy specifies details +such as timestamps, signatures, and encryption. See Apache Axis2 and Apache +Rampart documentation for more information.

    + +

    2. Generic JMS Client

    + +

    The JMS client is able to send plain text, plain binary content, or POX +content by directly publishing a JMS message to the specified destination. +The JMS destination name should be specified with the 'jms_dest' property. +The 'jms_type' property could specify 'text', 'binary' or 'pox' to specify +the type of message payload.

    + +

    The plain text payload for a 'text' message can be specified through the +'payload' property. For binary messages, the 'payload' property would contain +the path to the binary file. For POX messages, the 'payload' property will +hold a stock symbol name to be used within the POX request for stock order +placement request.

    + +

    e.g.,

    + +
    ant jmsclient -Djms_type=text -Djms_dest=dynamicQueues/JMSTextProxy -Djms_payload="24.34 100 IBM"
    +ant jmsclient -Djms_type=pox -Djms_dest=dynamicQueues/JMSPoxProxy -Djms_payload=MSFT
    +ant jmsclient -Djms_type=binary -Djms_dest=dynamicQueues/JMSFileUploadProxy
    +                     -Djms_payload=./../../repository/samples/resources/mtom/asf-logo.gif
    + +

    Note: The JMS client assumes the existence of a default ActiveMQ (5.2.0) installation on the + local machine.

    + +

    3. MTOM / SwA Client

    + +

    The MTOM / SwA client can send a binary image file as a MTOM or SwA +optimized message, and receive the same file again through the response and +save it as a temporary file. The 'opt_mode' can specify 'mtom' or 'swa' +respectively for the above mentioned optimizations. Optionally, the path to a +custom file can be specified through the 'opt_file' property, and the +destination address can be changed through the 'opt_url' property if +required.

    + +
    e.g. ant optimizeclient -Dopt_mode=[mtom | swa]
    + +

    Starting the Sample Services

    + +

    The sample services ship with a pre-configured Axis2 server, and +demonstrates in-only and in-out SOAP/REST or POX messaging over HTTP/HTTPS +and JMS transports using WS-Addressing, WS-Security, and WS-Reliable +Messaging. It also handles binary content using MTOM and SwA.

    + +

    The sample services can be found in the samples/axis2Server/src directory +and can be built and deployed using Ant from each service directory.

    + +
    user@host:/tmp/wso2esb-2.0/samples/axis2Server/src/SimpleStockQuoteService$ ant
    +Buildfile: build.xml
    + ...
    +build-service:
    +   ....
    +      [jar] Building jar: /tmp/wso2esb-2.0/samples/axis2Server/repository/services/SimpleStockQuoteService.aar
    +
    +BUILD SUCCESSFUL
    +Total time: 3 seconds
    + +

    To start the Axis2 server, go to the samples/axis2Server directory and +execute the axis2server.sh or axis2server.bat script. This starts the Axis2 +server with the HTTP transport listener on port 9000 and HTTPS on 9002 +respectively. To enable JMS transport, you will need to set up and start a +JMS provider. An ActiveMQ 5.2.0 JMS server on the local machine is +supported by default, and can be easily enabled by uncommenting the JMS +transport from the repository/conf/axis2.xml

    + +

    The Sample services are as follows:

    + +

    1. SimpleStockQuoteService

    + +

    This service has four operations, getQuote (in-out), getFullQuote(in-out), +getMarketActivity(in-out) and placeOrder (in-only). The getQuote operation +will generate a sample stock quote for a given symbol. The getFullQuote +operation will generate a history of stock quotes for the symbol for a number +of days, and the getMarketActivity operation returns stock quotes for a list +of given symbols. The placeOrder operation will accept a one way message for +an order.

    + +

    2. SecureStockQuoteService

    + +

    This service is a clone of the SimpleStockQuoteService, but has +WS-Security enabled and an attached security policy for signing and +encrypting messages.

    + +

    3. MTOMSwASampleService

    + +

    This service has three operations: uploadFileUsingMTOM(in-out), +uploadFileUsingSwA(in-out) and oneWayUploadUsingMTOM(in-only), and also +demonstrates the use of MTOM and SwA. The uploadFileUsingMTOM and +uploadFileUsingSwA operations accept a binary image from the SOAP request as +MTOM and SwA, and returns this image back again as the response, while the +oneWayUploadUsingMTOM saves the request message to the disk.

    + +

    Starting Sample ESB Configurations

    + +

    To start the WSO2 ESB with the sample default configuration, execute the +wso2server.bat or wso2server.sh script found in the /bin directory. This starts +up an instance of the ESB using the Synapse and Axis2 configuration files +located in the conf directory. The repository/samples directory contains +the sample configurations available as synapse_sample_<n>.xml files. To +start a specific sample configuration of the ESB, use the wso2esb-samples.sh or +wso2esb-samples.bat as follows:

    + +
    wso2esb-samples.bat -sn <n>
    + ./wso2esb-samples.sh -sn <n>
    + +

    Setting up the JMS Listener

    + +

    The samples used in this guide assumes the existence of a local +ActiveMQ (5.1.0 or higher) installation, which is properly installed and started.

    + +

    To enable the JMS transport, you need to uncomment the JMS transport +listener configuration. If you are using a JMS provider other than ActiveMQ, +this configuration should be updated to reflect your environment. Once +uncommented, the default configuration should be as follows. To enable JMS +for the ESB, the repository/conf/axis2.xml must be updated. To +enable JMS support for the sample Axis2 server, the +samples/axis2Server/repository/conf/axis2.xml file must be updated.

    + +
        <!--Uncomment this and configure as appropriate for JMS transport support, after setting up your JMS environment (e.g. ActiveMQ)-->
    +    <transportReceiver name="jms" class="org.apache.axis2.transport.jms.JMSListener">
    +        <parameter name="myTopicConnectionFactory" locked="false">
    +                <parameter name="java.naming.factory.initial" locked="false">org.apache.activemq.jndi.ActiveMQInitialContextFactory</parameter>
    +                <parameter name="java.naming.provider.url" locked="false">tcp://localhost:61616</parameter>
    +                <parameter name="transport.jms.ConnectionFactoryJNDIName" locked="false">TopicConnectionFactory</parameter>
    +        </parameter>
    +
    +        <parameter name="myQueueConnectionFactory" locked="false">
    +                <parameter name="java.naming.factory.initial" locked="false">org.apache.activemq.jndi.ActiveMQInitialContextFactory</parameter>
    +                <parameter name="java.naming.provider.url" locked="false">tcp://localhost:61616</parameter>
    +                <parameter name="transport.jms.ConnectionFactoryJNDIName" locked="false">QueueConnectionFactory</parameter>
    +        </parameter>
    +
    +        <parameter name="default" locked="false">
    +                <parameter name="java.naming.factory.initial" locked="false">org.apache.activemq.jndi.ActiveMQInitialContextFactory</parameter>
    +                <parameter name="java.naming.provider.url" locked="false">tcp://localhost:61616</parameter>
    +                <parameter name="transport.jms.ConnectionFactoryJNDIName" locked="false">QueueConnectionFactory</parameter>
    +        </parameter>
    +    </transportReceiver>
    + +

    Setting up Mail Transport Sender

    + +

    To enable the mail transport sender for samples, you need to uncomment the mail +transport sender configuration in the repository/conf/axis2.xml. +Uncomment the mail transport sender sample configuration and make sure it +points to a valid SMTP configuration for any actual scenarios.

    + +
        <transportSender name="mailto" class="org.apache.synapse.transport.mail.MailTransportSender">
    +        <parameter name="mail.smtp.host">smtp.gmail.com</parameter>
    +        <parameter name="mail.smtp.port">587</parameter>
    +        <parameter name="mail.smtp.starttls.enable">true</parameter>
    +        <parameter name="mail.smtp.auth">true</parameter>
    +        <parameter name="mail.smtp.user">synapse.demo.0</parameter>
    +        <parameter name="mail.smtp.password">mailpassword</parameter>
    +        <parameter name="mail.smtp.from">synapse.demo.0@gmail.com</parameter>
    +    </transportSender>
    + +

    Setting up Mail Transport Receiver

    + +

    To enable the mail transport receiver for samples, you need to uncomment the mail +transport receiver configuration in the repository/conf/axis2.xml. +Uncomment the mail transport receiver sample configuration. Note: you need to provide +correct parameters for a valid mail account at service level.

    + +
        <transportReceiver name="mailto" class="org.apache.axis2.transport.mail.MailTransportListener">
    +    </transportReceiver>
    + +

    + Configuring WSO2 ESB for the FIX Transport +

    +

    + Setting up the FIX Transport +

    +

    + To run the FIX samples used in this guide you need a local + Quickfix/J installation. + Download Quickfix/J from here. +

    +

    + Simply uncomment the FIX transport sender and FIX transport receiver configurations + in the repository/conf/axis2.xml. Alternatively if the + FIX transport management bundle is in use you can enable the FIX transport + listener and the sender from the WSO2 ESB management console. Login to the + console and navigate to 'Transports' on management menu. Scroll down to + locate the sections related to the FIX transport. Simply click on 'Enable' + links to enable the FIX listener and the sender. +

    +

    +

    + Configuring the ESB for FIX Samples +

    +

    + In order to configure WSO2 ESB to run the FIX samples given in this + guide you will need to create some FIX configuration files as + specified below (You can find the config files from + $ESB_HOME/repository/conf/sample/resources/fix folder. +

    +

    + The FileStorePath property in the following two files should point + to two directories in your local file system. Once the samples + are executed, Synapse will create FIX message stores in these two + directories. +

    +

    + Put the following entries in a file called fix-synapse.cfg +

    +
    +	[default]
    +	FileStorePath=repository/logs/fix/data
    +	ConnectionType=acceptor
    +	StartTime=00:00:00
    +	EndTime=00:00:00
    +	HeartBtInt=30
    +	ValidOrderTypes=1,2,F
    +	SenderCompID=SYNAPSE
    +	TargetCompID=BANZAI
    +	UseDataDictionary=Y
    +	DefaultMarketPrice=12.30
    +
    +	[session]
    +	BeginString=FIX.4.0
    +	SocketAcceptPort=9876
    +      
    +

    + Put the following entries in a file called synapse-sender.cfg +

    +
    +	[default]
    +	FileStorePath=repository/logs/fix/data
    +	SocketConnectHost=localhost
    +	StartTime=00:00:00
    +	EndTime=00:00:00
    +	HeartBtInt=30
    +	ReconnectInterval=5
    +    SenderCompID=SYNAPSE
    +    TargetCompID=EXEC
    +    ConnectionType=initiator
    +
    +    [session]
    +    BeginString=FIX.4.0
    +    SocketConnectPort=19876
    +      
    +

    + Configuring Sample FIX Applications +

    + +

    + If you are using a binary distribution of Quickfix/J, the two + samples and their configuration files are all packed to a + single jar file called quickfixj-examples.jar. You will have to + extract the jar file, modify the configuration files and pack + them to a jar file again under the same name. +

    +

    + You can pass the new configuration file as a command line parameter too, in that case you don't + need to modify the quickfixj-examples.jar. + You can copy the config files from $ESB_HOME/repository/conf/sample/resources/fix folder to + $QFJ_HOME/etc folder. Execute the sample apps from $QFJ_HOME/bin, ./banzai.sh/bat ../etc/banzai.cfg + executor.sh/bat ../etc/executor.sh. + +

    +

    + Locate and edit the FIX configuration file of Executor to be as follows. + This file is usually named executor.cfg +

    +
    +	[default]
    +	FileStorePath=examples/target/data/executor
    +	ConnectionType=acceptor
    +	StartTime=00:00:00
    +	EndTime=00:00:00
    +	HeartBtInt=30
    +	ValidOrderTypes=1,2,F
    +	SenderCompID=EXEC
    +	TargetCompID=SYNAPSE
    +	UseDataDictionary=Y
    +	DefaultMarketPrice=12.30
    +
    +	[session]
    +	BeginString=FIX.4.0
    +	SocketAcceptPort=19876
    +      
    +

    + Locate and edit the FIX configuration file of Banzai to be as follows. + This file is usually named banzai.cfg +

    +
    +	[default]
    +	FileStorePath=examples/target/data/banzai
    +	ConnectionType=initiator
    +	SenderCompID=BANZAI
    +	TargetCompID=SYNAPSE
    +	SocketConnectHost=localhost
    +	StartTime=00:00:00
    +	EndTime=00:00:00
    +	HeartBtInt=30
    +	ReconnectInterval=5
    +
    +	[session]
    +	BeginString=FIX.4.0
    +	SocketConnectPort=9876
    +      
    +

    + The FileStorePath property in the above two files should point + to two directories in your local file system. The launcher scripts for + the sample application can be found in the bin directory of Quickfix/J + distribution. +

    +

    + For more information regarding the FIX sample applications please + refer the Example Applications section in the Quickfix/J + documentation. For more information on configuring Quickfix/J applications + refer the Configuring Quickfix/J section of the Quickfix/J + documentation. +

    +

    + +

    + Configure WSO2 ESB for AMQP Transport +

    +

    +

    + The samples used in this guide assumes the existence of a local QPid + (1.0-M2 or higher) installation properly installed and started up. You also + need to copy the following client JAR files into the 'repository/components/lib' directory + to support AMQP. These files are found in the 'lib' directory of the + QPid installation. +

    +
      +
    • qpid-client-1.0-incubating-M2.jar
    • +
    • qpid-common-1.0-incubating-M2.jar
    • +
    • geronimo-jms_1.1_spec-1.0.jar
    • +
    • slf4j-api-1.4.0.jar **
    • +
    • slf4j-log4j12-1.4.0.jar **
    • +
    +

    + Note: To configure FIX (Quickfix/J 1.3) with AMQP (QPid-1.0-M2) copy the sl4j-* libraries comes with QPid and ignore the sl4j-* + libraries that come with Quickfix/J. +

    +

    + To enable the AMQP over JMS transport, you need to uncomment the JMS transport + listener configuration. To enable AMQP over JMS for ESB, the repository/conf/axis2.xml must be updated, + while to enable JMS support for the sample Axis2 server the + samples/axis2Server/repository/conf/axis2.xml file must be updated. +

    +
        <!--Uncomment this and configure as appropriate for JMS transport support, after setting up your JMS environment -->
    +        <transportReceiver name="jms" class="org.apache.synapse.transport.jms.JMSListener">
    +        </transportReceiver>
    +
    +        <transportSender name="jms" class="org.apache.synapse.transport.jms.JMSSender">
    +        </transportReceiver>
    + +

    +

    + Locate and edit the AMQP connection settings file for the message consumer, this fle is usually named direct.properties + and can be found in the repository/samples/resources/fix directory. +

    +
    +            java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory
    +            # register some connection factories
    +            # connectionfactory.[jndiname] = [ConnectionURL]
    +            connectionfactory.qpidConnectionfactory = amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5672'
    +            # Register an AMQP destination in JNDI
    +            # destination.[jniName] = [BindingURL]
    +            destination.directQueue = direct://amq.direct//QpidStockQuoteService?routingkey='QpidStockQuoteService'
    +            destination.replyQueue = direct://amq.direct//replyQueue?routingkey='replyQueue'
    +

    + Locate and edit the AMQP connection settings file for WSO2 ESB, this fle is usually named con.properties + and can be found in the repository/samples/resources/fix directory. +

    +
    +            #initial context factory
    +            #java.naming.factory.initial =org.apache.qpid.jndi.PropertiesFileInitialContextFactory
    +            # register some connection factories
    +            # connectionfactory.[jndiname] = [ConnectionURL]
    +            connectionfactory.qpidConnectionfactory=amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5672'
    +            # Register an AMQP destination in JNDI
    +            # destination.[jndiName] = [BindingURL]
    +            destination.directQueue=direct://amq.direct//QpidStockQuoteService
    +

    + + +

    + Configure WSO2 ESB for TCP Transport +

    +

    +

    + To enable the TCP transport for samples first you need to download the Axis2 TCP transport jar + and copy it to the lib directory of Synapse. This library can be downloaded from the + WS-Commons Transports website. Then open up the axis2.xml file and uncomment the TCP transport + receiver and sender configurations: +

    +
    +<transportReceiver name="tcp" class="org.apache.axis2.transport.tcp.TCPServer">
    +    <parameter name="port">6060</parameter>
    +</transportReceiver>
    +
    +<transportSender name="tcp" class="org.apache.axis2.transport.tcp.TCPTransportSender"/>
    +
    +

    + If you wish to use the sample Axis2 client to send TCP messages, you have to uncomment the + TCP transport sender configuration in the samples/axis2Client/client_repo/conf/axis2.xml file. +

    + + +

    + Configure WSO2 ESB for UDP Transport +

    +

    +

    + To enable the UDP transport for samples first you need to download the Axis2 UDP transport jar and + copy it to the lib directory of Synapse. This library can be downloaded from the + WS-Commons Transports website. Then open up + the axis2.xml file and uncomment the UDP transport receiver + and sender configurations: +

    +
    + <transportReceiver name="udp" class="org.apache.axis2.transport.udp.UDPListener"/>
    + <transportSender name="udp" class="org.apache.axis2.transport.udp.UDPSender"/>
    +

    + If you wish to use the sample Axis2 client to send UDP messages, you have to uncomment the UDP + transport sender configuration in the samples/axis2Client/client_repo/conf/axis2.xml file. +

    + + +

    + Configuring WSO2 ESB for supporting JSON +

    +

    +

    + JSON Then open up is a lightweight data-interchange format. It can be used as an alternative to XML or SOAP. + To enable the JSON support in Synapse, following two jar files should be deployed into the 'lib' directory of Synapse.

    + + + +

    + Having deployed the necessary libraries you should now register the JSON message builder and + formatter with Synapse. Open up 'repository/conf/axis2.xml' file of Synapse and add the following + two entries under the 'messageBuilders' and 'messageFormatters' sections respectively. +

    + +
    + <messageBuilder contentType="application/json"
    +                         class="org.apache.axis2.json.JSONOMBuilder"/>
    +
    +  <messageFormatter contentType="application/json"
    +                         class="org.apache.axis2.json.JSONMessageFormatter"/>
    +
    +

    + If you are planning to run sample 440, you should also add the above two entries to the + 'samples/axis2Client/client_repo/conf/axis2.xml' file. +

    + + +

    Configuring the ESB for Script Mediator Support

    + +

    The Script Mediator is a Synapse extension, and thus all pre-requisites +for all BSF supported scripting languages may not be bundled by default with +the ESB distribution. Before you use some script mediators, you may need to +manually add the required .jar files to the lib +directory('lib/extensions'), and optionally perform other installation +tasks as may be required by the individual scripting language. This is +detailed in the following sections.

    + +

    JavaScript Support

    + +

    The JavaScript/E4X support is enabled by default and comes ready-to-use +with the WSO2 ESB distribution.

    + +

    Ruby Support

    + +

    + You can download and install the JRuby engine manually. Download + the file named "jruby-complete-1.3.0.wso2v1.jar" from the WSO2 P2 repository and copy + it into repository/components/dropins directory. +

    +

    +

    + Setting up Derby database server +

    +

    + You can download Apache Derby distribution from http://db.apache.org/derby/ +

    +
      +
    1. + Set up and start the Derby network server +
    2. +
    3. + Create and open a connection to the database using the Derby client + driver
      +
       CONNECT 'jdbc:derby://localhost:1527/esbdb;user=esb;password=esb;create=true';
      +
    4. +
    5. + Create a table using the following statement +
       CREATE table company(name varchar(10), id varchar(10), price double);
      +
    6. +
    7. + Inserts some data using following statements +
       INSERT into company values ('IBM','c1',0.0);
      + INSERT into company values ('SUN','c2',0.0);
      + INSERT into company values ('MSFT','c3',0.0);
      +
    8. +
    + +

    When using Derby, you need to add derby.jar, derbyclient.jar and +derbynet.jar to the classpath. This can be done by putting the above three +jars into the ESB lib/extensions directory. For testing these samples Derby10.3.2.1 +binary distribution was used.

    + +

    You can use any other database product instead of Derby. Then you have to +change the database connection details accordingly. Also you have to copy the +required database driver jars to the ESB classpath.

    + +

    Setting up Synapse DataSources

    + +
    +

    Definition of the reusable database connection pool or datasources can be +done using datasources.properties file. It is possible to +configure any number of datasources. Currently this only supports two types of +datasources and those are based on Apache DBCP datasources. Those types are +BasicDataSource and PerUserPoolDataSource (based on Apache DBCP). Following +configuration includes both two definition. This configuration is related with +sample 363.

    + +

    Configuration is somewhat similar to the log4j appender configuration.

    + +

    It requires two databases, follow the above specified (Setting up Derby +Database server) steps to create the two databases +'jdbc:derby://localhost:1527/lookupdb', +'jdbc:derby://localhost:1527/reportdb' using the user name and +password as 'esb'. Fill in the data for those two databases as +per described in the above section

    + +
    +

    datasources.properties configuration
    +

    +
    ###############################################################################
    +# DataSources Configuration
    +###############################################################################
    +synapse.datasources=lookupds,reportds
    +synapse.datasources.icFactory=com.sun.jndi.rmi.registry.RegistryContextFactory
    +synapse.datasources.providerPort=2199
    +# If following property is present , then assumes that there is an external JNDI provider and will not start a RMI registry
    +#synapse.datasources.providerUrl=rmi://localhost:2199
    +
    +synapse.datasources.lookupds.registry=Memory
    +synapse.datasources.lookupds.type=BasicDataSource
    +synapse.datasources.lookupds.driverClassName=org.apache.derby.jdbc.ClientDriver
    +synapse.datasources.lookupds.url=jdbc:derby://localhost:1527/lookupdb;create=false
    +# Optionally you can specifiy a specific password provider implementation which overrides any globally configured provider
    +synapse.datasources.lookupds.secretProvider=org.apache.synapse.commons.security.secret.handler.SharedSecretCallbackHandler
    +synapse.datasources.lookupds.username=esb
    +# Depending on the password provider used, you may have to use an encrypted password here!
    +synapse.datasources.lookupds.password=esb
    +synapse.datasources.lookupds.dsName=lookupdb
    +synapse.datasources.lookupds.maxActive=100
    +synapse.datasources.lookupds.maxIdle=20
    +synapse.datasources.lookupds.maxWait=10000
    +
    +synapse.datasources.reportds.registry=JNDI
    +synapse.datasources.reportds.type=PerUserPoolDataSource
    +synapse.datasources.reportds.cpdsadapter.factory=org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS
    +synapse.datasources.reportds.cpdsadapter.className=org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS
    +synapse.datasources.reportds.cpdsadapter.name=cpds
    +synapse.datasources.reportds.dsName=reportdb
    +synapse.datasources.reportds.driverClassName=org.apache.derby.jdbc.ClientDriver
    +synapse.datasources.reportds.url=jdbc:derby://localhost:1527/reportdb;create=false
    +# Optionally you can specifiy a specific password provider implementation which overrides any globally configured provider
    +synapse.datasources.reportds.secretProvider=org.apache.synapse.commons.security.secret.handler.SharedSecretCallbackHandler
    +synapse.datasources.reportds.username=esb
    +# Depending on the password provider used, you may have to use an encrypted password here!
    +synapse.datasources.reportds.password=esb
    +synapse.datasources.reportds.maxActive=100
    +synapse.datasources.reportds.maxIdle=20
    +synapse.datasources.reportds.maxWait=10000
    + +

    + +

    To secure data sources password, it is need to use the mechanism for +securing secret Information. Please refer securing +secret Information guide. If that mechanism is used, then passwords +that have been specified are considered as aliases and those are used for +picking actual passwords. To get password securely, it is needed to set the +password provider for each data source. The password provider should be an +implementation of +org.apache.synapse.commons.security.secret.SecretCallbackHandler. +There are few options and for more information please refer securing +secret Information guide.

    + +

    For run this sample, you just need to uncomment +secret-conf.properties, cipher-text.properties and +datasources.properties. Those files are in conf directory.

    +
    +
    + + diff --git a/docs/xdoc/securing_secret_information.xml b/docs/xdoc/securing_secret_information.xml new file mode 100644 index 0000000000..ce804626ab --- /dev/null +++ b/docs/xdoc/securing_secret_information.xml @@ -0,0 +1,308 @@ + + + + + + + + + WSO2 ESB - Securing Confidential Information + + + + + + + [ Documentation Index ] +

    WSO2 Enterprise Service Bus (ESB), Securing Confidential Information

    + +

    + This guide describes how confidential information can be handled in a + secured manner in the ESB environment. From the context of the ESB + confidential information refers mainly to passwords. But confidential + information could be anything and hence instructions given in this guide + applies to all such confidential information elements. +

    + +

    Secret Providers

    + +

    The word 'secret' is used to refer to anything which needs to be kept as a +secret. Eventhough the current usage is limited to passwords, API supports any type of data. Secret +retrieving is done through 'SecretCallbackHandler' implementations. +Currently there are a few implementations and more implementations can be added as needed.

    +
      +
    • JBossEncryptionSecretCallbackHandler
    • +
    + +

    This is the default implementation used within the JBoss Application Server to secure +database passwords. It uses a hardcoded pass phrase (Need to use same pass phrase +that have been used for encryption). Admin can encrypt passwords using a pass phrase +and hard code that in the 'JBossEncryptionSecretCallbackHandler' +and make the source code closed.

    +
      +
    • JlineSecretCallbackHandler
    • +
    + +

    This is a command line based approach. Jline provides a way of reading passwords +without echoing text - similar to jdk 6 scanners.

    +
      +
    • JMXSecretCallbackHandler
    • +
    + +

    This is only supported in Synapse. With this we must use a JMX Console to provide +secrets. This may be useful for any users that manage servers in a production +environment using JMX.

    +
      +
    • HardCodedSecretCallbackHandler
    • +
    + +

    Admin needs to hard code password and make source code closed. This can be used +to just provide keystore passwords and other secrets can be retrieved using +'SecretManagerSecretCallbackHandler' (described next)

    +
      +
    • SecretManagerSecretCallbackHandler
    • +
    + +

    All secrets are managed using the Secret Manager. Secret Manager can keep +any number of secret repositories. Those are arranged in a cascading manner. All +secrets are stored in one place - secret repositories. Secrets can be accessed by +providing aliases for them (no need to put encrypted values inline in +application configurations). Key stores required by the Secret Manager and secret +repositories are configurable. It can be done through the +'secret-conf.properties'. Currently, there is only one secret +repository and it is called the FileBaseSecretRepository. It uses cipher-text.properties +to keep secrets. It keeps aliases vs. its actual secret in encrypted format +(encrypted by a key in keystore)

    + +

    Example

    + +

    secret-conf.properties

    +
    ############################################################################
    +# Secret Securing Configuration
    +############################################################################
    +# The following property specifies a global password provider implementation
    +# which will be used globally if not overriden in specific configurations
    +#carbon.secretProvider=<any implementation of org.apache.synapse.commons.security.secret.SecretCallbackHandler>
    +#Examples:
    +#carbon.secretProvider=org.apache.synapse.commons.security.secret.handler.SecretManagerSecretCallbackHandler
    +#carbon.secretProvider=org.apache.synapse.commons.security.secret.handler.JMXSecretCallbackHandler
    +#carbon.secretProvider=org.apache.synapse.commons.security.secret.handler.JlineSecretCallbackHandler
    +#carbon.secretProvider=org.apache.synapse.commons.security.secret.handler.JBossEncryptionSecretCallbackHandler
    +
    +#Secret Repositories configuration
    +
    +secretRepositories=file
    +secretRepositories.file.provider=org.apache.synapse.commons.security.secret.repository.filebased.FileBaseSecretRepositoryProvider
    +secretRepositories.file.location=cipher-text.properties
    +
    +#KeyStores configurations
    +
    +keystore.identity.location=resources/security/wso2carbon.jks
    +keystore.identity.type=JKS
    +keystore.identity.alias=wso2carbon
    +keystore.identity.store.password=wso2carbon
    +#keystore.identity.store.secretProvider=<any implementation of org.apache.synapse.commons.security.secret.SecretCallbackHandler>
    +keystore.identity.key.password=wso2carbon
    +#keystore.identity.key.secretProvider=<any implementation of org.apache.synapse.commons.security.secret.SecretCallbackHandler>
    +#keystore.identity.parameters=enableHostnameVerifier=false;keyStoreCertificateFilePath=/home/esb.cer
    +
    +keystore.trust.location=resources/security/client-truststore.jks
    +keystore.trust.type=JKS
    +keystore.trust.alias=wso2carbon
    +keystore.trust.store.password=wso2carbon
    +#keystore.trust.store.secretProvider=<any implementation of org.apache.synapse.commons.security.secret.SecretCallbackHandler>
    +
    + +

    cipher-text.properties

    + +
    aliases=esb
    +
    +# configuration  per each plaintext
    +esb.secret=M6U74dMVvRm4XFMczki2qZ6CsTvnUuRTjSditlACR5vTISSMI7F/mCTVJGOGdKJjij+VWVhBtmAOkElyvR9TwlUECnZ1o5DNsTK6l8je+9amc/ziTQLP3Q1tzm/Ex1pzHsG6jPGGrv3O0B9pZTfYFqRvlcNhM7Ve3WvA3ibs4Yk=
    +esb.secret.alias=wso2carbon
    +esb.secret.keystore=identity
    + +

    For security operations (encrypt / decrypt), Secret Manager uses a KeyStore +and securing the keystore passwords can be done by any of above mentioned ways. +In the current implementation, there is only a one Secret Repository - A file +based Secret Repository. It is possible to implements secret repositories based +on database, directory servers, registry etc.

    + +

    General API for Retrieving Secrets

    + +

    Consider that an application has a configuration for passwords as

    + +
      <datasource>
    +      <password>pass</password>
    +      <secretProvider>any implementation of SecretCallbackHandler- class name</secretProvider>
    +  </datasource> 
    + +

    For JBossEncryptionSecretCallbackHandler, 'password' should +contain an encrypted value. In any other case, it is just an alias- can keep +any human readable text. For example in Secret Manger, actual password is in +secret repositories. For file based repository, it is something like bellow.

    +
      
    +  aliases=pass
    +  pass.secret=EsY65tztE9R5b9pErVxLp8Br5d3ol6vRdWAkYHdc7XkZteGf37VJ+iNlCenqxYSEto0vcjpcmmzwf7K2wd9u3KQtVGKEoNLSe2LYZtrm3tKmGd6PX9YpdN72ml3JISNXPJ69yybFi6DVUIJfE5MFOd7gswWfCnkmZ3eJ6M1nuiI=
    + +

    To retrieve secret, it is needed to use following API and follow steps.

    + +

    Retrieving API

    + +

    Read the configuration parameter value of 'secret Provider' - +say 'secretProvider'

    +
    // Create SecretCallbackHandler
    + SecretCallbackHandler secretCallbackHanlder SecretCallbackHandlerFactory.createSecretCallbackHandler(secretProvider);
    +
    +// Setup SecretLoadingModule with 
    +CallbackHandlersSecretLoadingModule secretLoadingModule = new SecretLoadingModule();
    +secretLoadingModule.init(new SecretCallbackHandler[]{secretCallbackHanlder});
    +
    +// Create SecretCallbacks
    +SingleSecretCallback secretCallback = new SingleSecretCallback(aliases); // for above example 'aliases' is 'pass'
    +
    +secretLoadingModule.load(new SecretCallback[]{secretCallback});
    +
    +String actualPassword= secretCallback.getSecret();
    + +

    If you want to load multiple secrets at once you can use +'MultiSecretCallback'; or array of SingleSecretCallback s.

    + +

    There is a simple way to avoid code duplication.

    + +
    SecretInformation secretInformation = SecretInformationFactory.createSecretInformation(secretProvider, aliasPassword, passwordPrompt);
    +
    +String actualPassword = secretInformation.getResolvedSecret();
    + +

    Adapting in OSGI Environment

    + +

    All 'SecretCallbackHandlers' other than the +'SecretManagerSecretCallbackHandler' are stateless enabling to be used +without any additional code. With 'SecretManagerSecretCallbackHandler', +it is best if there is only one 'SecretManager' instance. More +precisely, a single 'SecretManagerSecretCallbackHandler' instance. +For this, there is a carbon module called 'secretvault'. It just reads +'secret-conf.properties' and initiates a new +'SecretCallbackHandler' instance. This can be a +'SecretManagerSecretCallbackHandler' or any other +'SecretCallbackHandlers' instance that needs to be shared +globally. To acccess this instance one must follow the instuctions +given below.

    + +

    Step 1 - Adding Dependencies

    + +
    <dependency>
    +    <groupId>org.apache.synapse</groupId>
    +    <artifactId>synapse-commons</artifactId>
    +    <version>1.3.0-SNAPSHOT</version>
    +</dependency> 
    +
    +<dependency>
    +     <groupId>org.wso2.carbon</groupId>
    +     <artifactId>org.wso2.carbon.securevault</artifactId>
    +     <version>${carbon.version}</version>
    +</dependency>
    + +

    Setp 2 - Listening to SecretCallbackHandlerService

    + +
    +/** @scr.reference name="secret.callback.handler.service"
    +* interface="org.wso2.carbon.securevault.SecretCallbackHandlerService"
    +* cardinality="1..1" policy="dynamic"
    +* bind="setSecretCallbackHandlerService" unbind="unsetSecretCallbackHandlerService
    +*/
    +
    +protected void setSecretCallbackHandlerService( SecretCallbackHandlerService secretCallbackHandlerService) {
    +            Logic on Set
    +}
    +
    +protected void unsetSecretCallbackHandlerService(SecretCallbackHandlerService secretCallbackHandlerService) {
    +           Logic on Unset
    +}
    + +

    +The annotations at the top are required and the Maven SCR plugin must be used to build the code. Please refer +Maven 2 documentation on how to use the Maven SCR plugin. SCR plugin generates OSGi declarative service +descriptors by parsing the scr annotations stated in the source files. +

    + +

    Logic on Set

    + +

    If the secret that needs to be resolved can be accessed directlym, for example +passing as an argument, you can use the following logic.

    + +
      SecretCallbackHandler secretProvider = secretCallbackHandlerService.getSecretCallbackHandler());
    +  SecretInformation secretInformation = SecretInformationFactory.createSecretInformation(secretProvider, aliasPassword, passwordPrompt);
    +  String actualPassword = secretInformation.getResolvedSecret();
    + +

    Now you can pass either an actual password or a SecretProvider or +SecretInformation to the code location that uses the password. But if the code that +performs secret resolution can not be accessed, for example, when using a configuration +such as follows - you cannot pass resolved password directly.

    + +
      <datasource>
    +      <password>pass</password>
    +      <secretProvider>any implementation of SecretCallbackHandler- class name</secretProvider>
    +  </datasource>
    + +

    You have to do following if the scenario is similar to the above.

    + +
      if (secretCallbackHandlerService != null) {
    +      SecretCallbackHandler secretCallbackHandler = secretCallbackHandlerService.getSecretCallbackHandler();
    +      SharedSecretCallbackHandlerCache.getInstance().setSecretCallbackHandler(secretCallbackHandler);
    +  }
    +

    Then you have to specify secretProvider in the configuration +as +org.apache.synapse.commons.security.secret.handler.SharedSecretCallbackHandler. +This is another SecretCallbackHandler that uses the handler +set in the SharedSecretCallbackHandlerCache. You need to +use Retrieving API. What we do here is using OSGI services in order +to share across any component and use the Singleton pattern to share across classes in a +single component and enable using the Retrieving API as it is.

    + +

    Ciphertool

    + +

    This is a simple tool to encrypt and decrypt simple texts.There are scripts +named ciphertool.sh & ciphertool.bat available in the bin directory to launch the tool. The arguments +accepted by this tool with their meanings are shown bellow.

    +
      +
    • keystore - If keys are in a store , its location
    • +
    • storepass - Password to access keyStore
    • +
    • keypass - To get private key
    • +
    • alias - Alias to identify key owner
    • +
    • storetype - Type of keyStore, Default is JKS
    • +
    • keyfile - If key is in a file
    • +
    • opmode - encrypt or decrypt , Default is encrypt
    • +
    • algorithm - encrypt or decrypt algorithm , Default is RSA
    • +
    • source - Either cipher or plain text as an in-lined form
    • +
    • outencode - Currently base64 and used for encoding the result
    • +
    • inencode - Currently base64 and used to decode input
    • +
    • trusted - Is KeyStore a trusted store? If this argument is provided, consider as a + trusted store
    • +
    • passphrase - if a simple symmetric encryption using a pass phrase shall + be used
    • +
    + +

    An example

    + +
    ciphertool.bat -source testpass -keystore resources/security/client-truststore.jks -storepass wso2carbon -alias wo2carbon -outencode base64 -trusted
    + + diff --git a/docs/xdoc/sequence_editor.xml b/docs/xdoc/sequence_editor.xml new file mode 100644 index 0000000000..22950b07b3 --- /dev/null +++ b/docs/xdoc/sequence_editor.xml @@ -0,0 +1,153 @@ + + + + + + + WSO2 ESB - Sequence Editor + + + + + +

    Sequence Editor

    + +

    A sequence is the basis of message mediation. A sequence is a collection of +mediators. Sequence editor allows creation of sequences from the UI. Sequences +can be created as named sequences and refer later from other parts of ESB +configuration. Some configurations expects sequences to be defined in the place +they are used. We call this type of sequences inline sequences. Sequence editor +is used in both these cases for creating a sequence.

    + +

    Sequence List

    + +

    Use the Mediation +Sequences page to add new sequences or edit existing sequences. As shown +in Figure,1 the sequence management section displays a list of existing +sequences.

    + +

    + +

    + +

    Figure 1: Mediation sequence management

    + +

    + +

    In the navigator, under Manage/Mediation, click Sequences. The Mediation Sequences +page appears.

    +
      +
    • Enable Statistics +
        +
      • Click Enable Statistics to + gather information relating to a particular sequence.
      • +
      +
    • +
    • Enable Tracing +
        +
      • Click Enable Tracing to turn + on all trace messages for the corresponding sequence
      • +
      +
    • +
    + +

    The above options are turned off by default because they cause a severe +performance degradation. Use these options only in a situation where you have +to debug a particular problem.

    +
      +
    • Edit +
        +
      • Click Edit to open the + sequence in the design view for editing purposes.
      • +
      +
    • +
    • Delete +
        +
      • Click Delete to remove a + particular sequence from the system.
      • +
      +
    • +
    + +

    + +

    Adding a Sequence

    +
      +
    1. On the Mediation Sequences + page, click Add Sequence. The Design Sequence page + appears.
    2. +
    3. Enter a sequence name.
    4. +
    5. Click Add Child , and select the required nodes for your + sequence.
    6. +
    + +

    + +

    Figure 2: Add sequence design view

    + +

    Editing a sequence

    +
      +
    1. On the Mediation + Sequences page, click Edit. + The Design + Sequence page appears, displaying the selected sequence.
    2. +
    3. Click on the node you want edit. The + properties for that node will be displayed below.
    4. +
    + +

    + +

    Figure 3: Editing a sequence

    + +

    + +

    Figure 4: Editing node specific properties

    +
      +
    • You can edit the node specific attributes displayed in the Design view. +
    • +
    • You can add a sibling node, in the Design view..
    • +
    • You can add only siblings to some nodes, while you can also add a child + node to others.
    • +
    • You can move the selected node up or down using the arrow icons.
    • +
    • You can also delete the node.
    • +
    + +

    Click switch to source view to view +the XML of the particular sequence. If you're familiar with the Synapse +configuration language you can edit the XML directly. After editing you can +save the sequences by clicking the save button. If you click on swith +to design view source will be saved before going to the graphical +view.

    + +

    + +

    Sequence source view

    + +

    Figure 5: Source view of the sequence editor

    + + diff --git a/docs/xdoc/setting_java_home.xml b/docs/xdoc/setting_java_home.xml new file mode 100644 index 0000000000..c2834945e9 --- /dev/null +++ b/docs/xdoc/setting_java_home.xml @@ -0,0 +1,51 @@ + + + + + + + + How to setup JAVA_HOME environment variable in Windows + + +

    How to setup JAVA_HOME environment variable in Windows

    + +

    Please follow the instructions to set up JAVA_HOME environment variable in your computer. + First find out the installation folder of Java development kit (JDK) in your machine. + Let's + assume it is installed in the folder "C:/j2sdk1.4.2" +

    + +
      +
    1. Right click on the My Computer icon on your desktop and select properties
    2. +
    3. Click the Advanced Tab
    4. +
    5. Click the Environment Variables button
    6. +
    7. Under System Variable, click New
    8. +
    9. Enter the variable name as JAVA_HOME
    10. +
    11. Enter the variable value as the install path for the Development Kit
    12. +
    13. Click OK
    14. +
    15. Click Apply Changes
    16. + +
    + + + + \ No newline at end of file diff --git a/docs/xdoc/source-repository.xml b/docs/xdoc/source-repository.xml new file mode 100644 index 0000000000..a7e0eebf4d --- /dev/null +++ b/docs/xdoc/source-repository.xml @@ -0,0 +1,133 @@ + + + + + + + + + WSO2 ESB - Source Repository + + + + [ Documentation Index ] +

    WSO2 Enterprise Service Bus (ESB) Source Repository

    + WSO2 ESB is developed on top of the revolutionary WSO2 Carbon platform. You might need the + source of the Carbon platform as well apart from the ESB source code. Please note that both + ESB and the Carbon platform is open source and the code is available under the Apache + Software License v2.0. + +

    Overview

    +

    This project uses Subversion + to manage its source code. Instructions on Subversion use can be found at + http://svnbook.red-bean.com/.

    + +

    Source code of the ESB 4.0.0 release

    +

    The following is a link to the online source tag of the WSO2 ESB 4.0.0 release.

    + +

    The complete source including the carbon platform can be checked out anonymously from + SVN with this command:

    +
    +
    $ svn checkout http://svn.wso2.org/repos/wso2/tags/esb/java/4.0.0 wso2esb
    +
    + +

    This code base contains the ESB product source code inside the directory "product" and + it also contains the source for the platform under the directory "carbon-pltform". Further + there will be a "build.sh" script to build the ESB with the platform.

    + +

    This script accepts any of the maven related system properties, but the property to skip + the tests has been shortned to "-ts", for example to build the ESB with the platform on + skipping tests the command is;

    + +
    +
    $ ./build.sh -ts
    +
    + +

    To build off-line with this build script you can pass in the "-o" option. If you just + need to build either the product or a specific part of the platform (for example Synapse) + you just need to traverse to that directory and use maven to build any of the projects.

    + +

    Source code of the WSO2 ESB trunk

    +

    Everyone can access the Subversion repository via HTTPS, but Committers must checkout + the Subversion repository via HTTPS. +

    +
    +
    $ svn checkout https://svn.wso2.org/repos/wso2/trunk/esb/java wso2esb
    +
    + +

    The Carbon framework related source code can be checked out from the + following commands.

    + +
    +
    $ svn checkout https://svn.wso2.org/repos/wso2/trunk/carbon carbon
    +
    + +
    +
    $ svn checkout https://svn.wso2.org/repos/wso2/trunk/carbon-components carbon-components
    +
    + +

    The Carbon project is the root project of the OSGi platform on whcih all the Java + product stack is built on top of, and the carbon-components contains all the components + not just ESB specific components. So you obviously need to build just the set of + components required by the ESB, which can be achieved through; +

    + +
    +
    $ mvn clean install -Dproduct=esb
    +
    + +

    To commit changes to the repository, execute the following command (svn will prompt + you for your password) +

    +
    +
    $ svn commit --username your-username -m "A message"
    +
    + +

    Access from behind a firewall

    +

    For those users who are stuck behind a corporate firewall which is blocking http access + to the Subversion repository, you can try to access it via the developer connection: +

    +
    +
    $ svn checkout https://svn.wso2.org/repos/wso2/trunk/esb/java wso2esb
    +
    +

    Access through a proxy

    +

    The Subversion client can go through a proxy, if you configure it to do so. + First, edit your "servers" configuration file to indicate which proxy to use. The + files location depends on your operating system. On Linux or Unix it is + located in the directory "~/.subversion". On Windows it is in "%APPDATA%\Subversion". + (Try "echo %APPDATA%", note this is a hidden directory.) +

    +

    There are comments in the file explaining what to do. If you don't have that file, get + the latest Subversion client and run any command; this will cause the configuration + directory and template files to be created. +

    +

    Example : Edit the 'servers' file and add something like :

    +
    +
    [global]
    +http-proxy-host = your.proxy.name
    +http-proxy-port = 3128
    +            
    +
    + + + diff --git a/docs/xdoc/templates.xml b/docs/xdoc/templates.xml new file mode 100644 index 0000000000..e66cfa3bbd --- /dev/null +++ b/docs/xdoc/templates.xml @@ -0,0 +1,409 @@ + + + + + + + + + WSO2 Enterprise Service Bus (ESB) Templates + + + + + + [ Documentation Index ] +

    WSO2 Enterprise Service Bus (ESB) Templates

    +

    Contents

    + +

    Introduction

    + +

    ESB configuration language is a very powerful and robust way of driving enterprise +data/messages through ESB mediation engine. However your requirements can become +such that very large amount of configuration files in the form of sequences, +endpoints ,proxies and transformations would be required to satisfy all the +mediation requirements of your system. In such cases number of configuration files +will be scattered all over and would be extremely hard to manage. What would be +frustrating to note is that , most of the configurations of particular types are +redundant in nature.

    +

    ESB Templates try to minimize this redundancy by creating prototypes that users +can re-use and utilize as and when needed. This is very much analogous to classes +and instances of classes where-as, a template is a class that can be used to wield +instance objects such as templates and endpoints. Thus ESB Templates is an ideal +way to improve re-usability and readability of ESB configurations/xml s. Addition +to that users can utilize predefined Templates that reflect commonly used EIP +patterns for rapid development of ESB message/mediation flows. +

    + +

    Templates

    +

    ESB templates comes in two different forms. +

    + +
      +
    • Sequence Templates +

      This defines a templated form of a ESB sequence. Sequence + Template has the ability to parameterize xpath expressions used + within a sequence defined inside a template. We invoke a Sequence + Template with a mediator named call-template by passing parameter + values + ie:- + +

      +
      <call-template target=”template” >
      +                    <parameter name=”name” value=”value”/>
      +                    .....
      +</call-template>
      + +
    • +
    • Endpoint Templates +

      Defines a templated form of an endpoint. Endpoint Template has + the ability to parameterize a endpoint defined within it. + Invoking a template of this kind is achieved using a template + Endpoint + ie:- +

      +
      <endpoint template=”name” ...>
      +                    <parameter name=”name” value=”value”/>
      +                    .....
      +</endpoint>
      + + +
    • +
    + + +

    Sequence Template Configuration

    + +

    +Template is a parametrized sequence defined in ESB. Parameters of a template are defined in the form +of xpath statement/s. +Callers can invoke such a template by populating parameters with static values /xpath expressions . We call such an artifact, Call-Template mediator. +

    + +

    In other words template sequence is an abstract/generic form of a ESB sequence. Only a call template mediator can make +a sequence template in to a concrete sequence. Let's illustrate this with a simple example. Suppose we have a sequence which +logs hello world in four different languages. You would do that in ESB in following way,

    + +
    <sequence>
    +   <switch source="//m0:greeting/m0:lang" xmlns:m0="http://services.samples">
    +        <case regex="EN">
    +            <log level="custom">
    +
    +      		  <property name=”GREETING_MESSAGE” value=”HELLO WORLD!!!!!!” />
    +
    +   	    </log>
    +        </case>
    +        <case regex="FR">
    +	    <log level="custom">
    +
    +      		  <property name=”GREETING_MESSAGE” value=”Bonjour tout le monde!!!!!!” />
    +
    +   	    </log>
    +        </case>
    +	<case regex="IT">
    +	    <log level="custom">
    +
    +      		  <property name=”GREETING_MESSAGE” value=”Ciao a tutti!!!!!!!” />
    +
    +   	    </log>
    +        </case>
    +	<case regex="JPN">
    +	    <log level="custom">
    +
    +      		  <property name=”GREETING_MESSAGE” value=”ハローワールド!!!!!!!” />
    +
    +   	    </log>
    +        </case>
    +    </switch>
    +
    +</sequence>
    + +

    Instead of printing our hello world message for each and every language inside the sequence, we can create a generalized template of this +actions which will accept any greeting message(from a particular language) and log it on screen. For example we can create the following template, which +you may name "HelloWorld_Logger".

    + +
    <template name="HelloWorld_Logger">
    +   <parameter name="message"/>
    +   <sequence>
    +        <log level="custom">
    +      		  <property name=”GREETING_MESSAGE” expression=”$func:message” />
    +   	</log>
    +   </sequence>
    +</template>
    + +

    With our "HelloWorld_Logger" in place, call-template mediator can populate this template with actual hello world messages and execute + the sequence of actions defined within the template like with any other sequence. This is illustrated below

    + +
    <sequence>
    +   <switch source="//m0:greeting/m0:lang" xmlns:m0="http://services.samples">
    +        <case regex="EN">
    +            <call-template target="HelloWorld_Logger">
    +		<with-param name="message" value="HELLO WORLD!!!!!!" />
    +	    </call-template>
    +        </case>
    +        <case regex="FR">
    +	    <call-template target="HelloWorld_Logger">
    +		<with-param name="message" value="Bonjour tout le monde!!!!!!" />
    +	    </call-template>
    +        </case>
    +	<case regex="IT">
    +	    <call-template target="HelloWorld_Logger">
    +		<with-param name="message" value="Ciao a tutti!!!!!!!" />
    +	    </call-template>
    +        </case>
    +	<case regex="JPN">
    +	    <call-template target="HelloWorld_Logger">
    +		<with-param name="message" value="ハローワールド!!!!!!!" />
    +	    </call-template>
    +        </case>
    +    </switch>
    +
    +</sequence>
    + +

    Note how call template mediator/s point to the same template "HelloWorld_Logger" and pass different arguments to it. This way sequence templates make it easy to +stereotype different workflows inside ESB.

    + + +

    Syntax

    +
    <template name="string">
    +   <!-- parameters this sequence template will be supporting -->
    +   (
    +   <parameter name="string"/>
    +   ) *
    +   <!--this is the in-line sequence of the template     -->
    +   <sequence>
    +        mediator+
    +   </sequence>
    + </template>
    +

    +sequence template is a top level element defined with the name attribute in ESB +configuration. Both endpoint and sequence template starts with a template element. +Parameters (ie:-<parameter>) are the inputs supported by this sequence template . +These sequence template parameters can be referred by a xpath expression defined +inside the in-line sequence. For example parameter named 'foo' can be referred +by a property mediator (defined inside the in-line sequence of the template) in +following ways +

    +

    <property name=”fooValue” expression=”$func:foo” />

    +

    OR

    +

    <property name=”fooValue” expression=”get-property('foo','func')” />

    +

    +Note the scope variable used in the xpath expression. We use function scope or +?func? to refer to template parameters. Only through this parameter name, we can +refer to a particular parameter value passed externally by a invoker such as call- +template mediator. WSO2 Management console UI provide easy way of adding these parameters. An example is +shown below.

    +

    + Defining/Accessing Seqeunce Template Parameters +

    +

    Figure 1: Defining/Accessing Seqeunce Template Parameters

    + +

    Call Template Mediator

    +

    Syntax

    +
    <call-template target="string">
    +   <!-- parameter values will be passed on to a sequence template -->
    +   (
    +    <!--passing plain static values -->
    +   <with-param name="string" value="string" /> |
    +    <!--passing xpath expressions -->
    +   <with-param name="string" value="{string}" /> |
    +    <!--passing dynamic xpath expressions where values will be compiled
    +dynamically-->
    +   <with-param name="string" value="{{string}}" /> |
    +   ) *
    +   <!--this is the in-line sequence of the template    -->
    + </call-template>
    + +

    call-template mediator should define a target template it should be invoking , +with 'target' attribute.

    +

    <with-param> element is used to parse parameter values to a target sequence +template. Note that parameter names has to be exact match to the names specified +in target template. Parameter element can contain three types of parameterized +values. xpath values are passed in within curly braces (ie:- {}) for value +attribute. Special type of xpath expressions can be declared in double curly +braces. These xpath expressions will be evaluated dynamically (others are +evaluated before invoking a template or outside the template ) .

    + +

    Please note that this is currently +only supported for special type of mediators such as iterator and aggregate mediator, where actual +xpath operations are made on a different soap message than the message coming in +to the mediator. Following shows how users can declare parameters inside call-template mediator UI

    + +

    + Passing Values with Call Template Mediator +

    +

    Figure 2: Passing Values with Call Template Mediator

    +

    Endpoint Template Configuration

    +

    Endpoint Template is a generalized form of endpoint configuration used in ESB. Unlike sequence +templates , endpoint templates are always parameterized using '$' prefixed values (ie:- NOT xpath expressions).

    +

    Template Endpoint is the artifact that makes a template of endpoint type into a concrete endpoint. In other words an +endpoint template would be useless without a Template Endpoint referring to it. +This is semantically similar to the relationship between a Sequence template and a Call-template mediator. +For example lets say we have two default endpoints with following hypothetical configurations,

    + +
    <endpoint  name="ep1">
    +            <default>
    +               <suspendOnFailure>
    +                     <errorCodes>10001,10002</errorCodes>
    +                     <progressionFactor>1.0</progressionFactor>
    +                </suspendOnFailure>
    +                <markForSuspension>
    +                     <retriesBeforeSuspension>5</retriesBeforeSuspension>
    +                     <retryDelay>0</retryDelay>
    +                </markForSuspension>
    +            </default>
    +</endpoint>
    +<endpoint  name="ep2">
    +            <default>
    +               <suspendOnFailure>
    +                     <errorCodes>10001,10003</errorCodes>
    +                     <progressionFactor>2.0</progressionFactor>
    +                </suspendOnFailure>
    +                <markForSuspension>
    +                     <retriesBeforeSuspension>3</retriesBeforeSuspension>
    +                     <retryDelay>0</retryDelay>
    +                </markForSuspension>
    +            </default>
    +</endpoint>
    + +

    We can see that these two endpoints have different set of error codes and different progression factors for suspension. Futhermore number of retries are different between them. By defining a endpoint template we can converge these + two endpoints to a generalized form. This is illustrated in the follwoing (Note how '$' is used to paramaeterize configuration and $name is a implicit/default parameter) ,

    + +
    <template name="ep_template">
    +     <parameter name="codes"/>
    +     <parameter name="factor"/>
    +     <parameter name="retries"/>
    +     <endpoint name="$name">
    +            <default>
    +               <suspendOnFailure>
    +                     <errorCodes>$codes</errorCodes>
    +                     <progressionFactor>$factor</progressionFactor>
    +                </suspendOnFailure>
    +                <markForSuspension>
    +                     <retriesBeforeSuspension>$retries</retriesBeforeSuspension>
    +                     <retryDelay>0</retryDelay>
    +                </markForSuspension>
    +            </default>
    +     </endpoint>
    +</template>
    + +

    Since we have a template defined we can use template endpoints to create two concrete endpoint instances with different parameter values for this scenario. + This is shown below.

    + +
    <endpoint name="ep1" template="ep_template">
    +           <parameter name="codes" value="10001,10002" />
    +	   <parameter name="factor" value="1.0" />
    +	   <parameter name="retries" value="5" />
    +</endpoint>
    +<endpoint name="ep2" template="ep_template">
    +           <parameter name="codes" value="10001,10003" />
    +	   <parameter name="factor" value="2.0" />
    +	   <parameter name="retries" value="3" />
    +</endpoint>
    + +

    As with call-template mediator , above template endpoint will stereotype endpoints with customized configuration parameters. + This makes it very easy to understand and maintain certain ESB configurations and improves reusability in a certain way.

    + +

    Syntax

    +
    <template name="string">
    +   <!-- parameters this endpoint template will be supporting -->
    +   (
    +   <parameter name="string"/>
    +   ) *
    +   <!--this is the in-line endpoint of the template    -->
    +   <endpoint [name="string"] >
    +           address-endpoint | default-endpoint | wsdl-endpoint | load-balanced-
    +endpoint | fail-over-endpoint
    +     </endpoint>
    +</template>
    + +

    Similar to sequence templates ,endpoint templates are defined as top level element +(with the name specified by the name attribute )of ESB configuration +Parameters (ie:-<parameter>) are the inputs supported by this endpoint template . +These endpoint template parameters can be referred by $ prefixed parameter name. +For example parameter named 'foo' can be referred by $foo. Most of the parameters +of the endpoint definition can be parametrized with $ prefixed values. This is +shown in the following extract,

    +
    <template name="sample_ep_template">
    +            <parameter name="foo"/>
    +            <parameter name="bar"/>
    +            <default>
    +               <suspendOnFailure>
    +                     <errorCodes>$foo</errorCodes>
    +                     <progressionFactor>$bar</progressionFactor>
    +                </suspendOnFailure>
    +                <markForSuspension>
    +                     <retriesBeforeSuspension>0</retriesBeforeSuspension>
    +                     <retryDelay>0</retryDelay>
    +                </markForSuspension>
    +            </default>
    +     </endpoint>
    +</template>
    +

    Note $name and $uri are default parameters that a template can use anywhere within +the endpoint template (usually used as parameters for endpoint name and address +attributes). Following figure shows, how a endpoint template design page is rendered in WSO2 Management console + UI. +

    +

    + Designing an Endpoint Template +

    +

    Figure 3: Designing an Endpoint Template

    + +

    Template Endpoint

    +

    Syntax

    +
    <endpoint [name="string"] [key="string"] template="string">
    +      <!-- parameter values will be passed on to a endpoint template -->
    +   (
    +           <parameter name="string" value="string" />
    +   ) *
    +</endpoint>
    +

    Template endpoint defines parameter values that can parameterize endpoint . The 'template' attribute +points to a target endpoint template.

    +

    As in the endpoint template , Note that parameter names has to be exact match to +the names specified in target endpoint template. UI for a template endpoint is depicted below +

    +

    + Template Endpoint UI +

    +

    Figure 4: Template Endpoint UI

    + + diff --git a/docs/xdoc/transactions.xml b/docs/xdoc/transactions.xml new file mode 100644 index 0000000000..96847f04d8 --- /dev/null +++ b/docs/xdoc/transactions.xml @@ -0,0 +1,170 @@ + + + + + + + + + WSO2 ESB - Transactions + + + + + + [ Documentation Index ] +

    WSO2 Enterprise Service Bus (ESB) Transaction support

    +

    Contents

    + +

    Introduction

    +

    + Transaction plays a major role in today's business world. It adds a very important functionality to your + system, which you will only see in a system crash. Having a good transactional support will + ensure correct functionality in a system crash. This guide describes the transaction support avilable + in WSO2 ESB. +

    +
    +

    + Transaction mediator +

    +

    A new synpase mediator (transaction mediator) has been added to support the distributed transactions + using Java transaction API(JTA). JTA allows applications to perform a distributed transaction that + is, transactions that access and update data on two or more networked computer resources (an example would + be to have two databases or a database and a message queue such as JMS). This mediator can be used to + perform a distributed transaction. The synapse configuration has been extended to add explicit transaction + markers. What this means is you can use the synpase configuration language to define the start, end etc.., + of your transaction. It's the responsibility of the user to define when to start, commit or rollback the + transaction. For example we can mark the start of a transaction at the start of a database commit and end + of the transaction at the end of the database commit and we can mark rollback transaction if a failure occurs. +

    +

    + Transaction mediator configuration +

    +

    + Transaction mediator has the following configuration +

    +
    +	    <transaction action="new|use-existing-or-new|fault-if-no-tx|commit|rollback|suspend|resume"/>
    +        
    +

    The action attribute has the following meanings.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    newCreate a new jta transaction. Generate a fault if a transaction already exist.
    use-existing-or-newCreate a new jta transaction. Do nothing if a transaction exist.
    fault-if-no-txGenerate a fault if no transaction exist. Do nothing if a transaction exist.
    commitCommit transaction. Generate a fault if no transaction exist.
    rollbackRollback transaction. Generate a fault if no transaction exist.
    suspendSuspend transaction. Generate a fault if no transaction exist.
    resumeResume transaction. Generate a fault if no transaction exist.
    +

    To use the transaction mediator you need to have a JTA provider in your environment. What this mean is you + need to deploy WSO2 ESB in an application sever which provide the JTA service. JBoss is an example of such + application server. Refer the Reference section to see how you can deploy ESB on JBoss.

    +

    An example is avilable in the article(see Reference section) which demostrate the + distributed transaction support. +

    +
    +

    Java Message Service(JMS) transactions

    +

    In addition to the distributed transactions, WSO2 ESB also has the support for JMS transactions. The JMS + transport which ships with WSO2 ESB has the support for both local and distrbuted transactions. +

    + +

    JMS local transaction

    +

    + A local transaction represents a unit of work on a single connection to a data source managed by a resource + manager. In JMS, we can use the JMS API to get a transacted session and call methods for commit or rollback + for the relevant transaction objects. This is managed internal to a resource manager. There is no external + transaction manager involved in the coordination of such transactions +

    +

    JMS local transaction configuration

    +

    To start a local JMS transaction you defined following property in JMS transport Listner/Sender in axis2.xml

    +
    +	    <parameter name="transport.jms.SessionTransacted">true|false</parameter>
    +        
    +

    By default the sesstion is not transacted and if you want to use JMS local transaction set the above parameter + to true. And you need to set the following property in synpase fault handler to rollback the transaction in + case of a failure. +

    +
    +        <property name="SET_ROLLBACK_ONLY" value="true" scope="axis2"/>
    +        
    +

    There is an example of JMS local transaction in the transaction article(see Reference + section).

    + +

    JMS distribued transaction

    +

    WSO2 ESB also has the support for distributed JMS transaction. You can use JMS transport with more than one + distributed resources( for example a JMS queue and a remote database server).

    +

    Transaction mediator can be used to mark a distributed transaction which involves a distrbution transaction + which span through mulitple JMS resources.

    +

    The article contains a sample on JMS distributed transaction(see Reference + section).

    + +

    References

    + + + + diff --git a/docs/xdoc/user_guide.xml b/docs/xdoc/user_guide.xml new file mode 100644 index 0000000000..bc71486041 --- /dev/null +++ b/docs/xdoc/user_guide.xml @@ -0,0 +1,720 @@ + + + + + + + + WSO2 ESB - User Guide + + + + + + [ Documentation Index ] +

    + WSO2 Enterprise Service Bus (ESB) User Guide +

    +

    + The User Guide describes how to configure WSO2 ESB using the + Web based management console. The WSO2 Management Console has been tested + on the Mozilla Firefox 2.0, 3.0 and Internet Explorer 6.0, 7.0 Web Browsers at a + resolution of 1024x768. +

    +

    Contents

    + +

    + Installing and Running the WSO2 ESB +

    +

    + Please refer the Installation Guide + for details on how to install and run the WSO2 ESB. +

    +

    + +

    +

    + Accessing the ESB Web based Management Console +

    +

    + Once WSO2 ESB has been successfully installed and started, launch a Web + browser instance and point it to the URL https://localhost:9443/carbon. + This will take you to the Sign In page of the WSO2 ESB + Management Console. +

    +

    + Signing In +

    +

    + Enter your user name and password to log on to the ESB Management Console. +

    +

    + The default username / password is : admin / admin +

    +

    + You can change your password using the instructions + given below. +

    +

    + If you get any errors when trying + to sign in, click Sign-in Help. A list of + possible errors, their descriptions and solutions will be displayed. +

    +

    + Changing Your User Name and Password +

    +

    + You can change the default password using user management. Click on User Management menu + from left. +

    +

    + Please refer the documentation on managing + users for details. +

    +

    + Icons and Descriptions +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + Icon + + Description +
    + Add + + Add - Click this icon to add an item. Most + often clicking on this icon gives a submenu from which you can + select an element. +
    + Edit + + Edit - Click this icon to modify an + existing item. +
    + Delete + + Delete - Click this icon to permanently + delete an item. A message will appear prompting you to confirm the + deletion. +
    + Registry Picker + + Registry Browser - Click this icon to view + the registry browser. You can select elements from the local + registry as well as the integrated registry, as both registries are + displayed in the browser. Also user has the option of choosing from + the Governance registry as well as from the Configuration registry. +
    + Namespace + + Namespace Editor - Click this icon to open + the Namespace Editor dialog box. +
    + Stats Enabled + + Disable Statistics - This icon indicates + that statistics generation is in progress. Click this icon to stop + statistics generation for the respective element. +
    + Stats Disabled + + Enable Statistics - This icon indicates + that statics are not been generated at present. Click this icon to + start statistics generation for the respective element. +
    + Trace Enabled + + Disable Tracing - This icon indicates that + message tracing is in progress. Click this icon to stop tracing for + the respective element. +
    + Trace Disabled + + Enable Tracing - This icon indicates that + messages are not been traced at present. Click this icon to start + tracing messages for the respective element. +
    + Proxy Service + + Proxy Service - This icon will be used to denote + Proxy Services on the services listing page. +
    + Context-sensitive Help + + Context-sensitive Help - To learn about a + feature, click this icon. A context-sensitive help window will pop up. +
    +

    +

    + Common Screens and Dialog Boxes +

    +

    +

    + Registry Browser - This dialog box is invoked + from the Pick from Registry option. The Registry + Browser contains elements from the integrated registry and the local + registry. +

    +

    +

    + Registry Browser +

    +

    +

    + Add Namespace - This dialog box is invoked by + clicking Namespaces link from the configuration section + of mediators. XML namespaces provide a simple method for qualifying + an element and attribute names used in Extensible Markup Language + documents by associating them with namespaces identified by URI + references. Enter a prefix and the URI which it identifies. +

    +

    + Add namespace +

    +

    +

    + Managing the underlying Synapse Configuration +

    +

    + The Synapse configuration + language consists of endpoints, sequences, registry entries, + tasks, proxy services and more. Messages coming into ESB are processed by the + underlying Synapse engine through mediation sequences and delivered to the + specified endpoints. In addition, scheduled tasks may inject new messages + into the ESB periodically or execute other tasks. +

    +

    + Proxy Services +

    +

    + Proxy services define virtual services hosted on the ESB that can accept + requests, mediate them, and deliver them to an actual service. Proxy + services could perform transport or interface switching and expose + different semantics than the actual service, i.e., WSDL, policies, and QoS + aspects like WS-RM, WS-Security, etc. +

    +

    +

    + Adding a Proxy Service +

    +

    + This function allows you to add a proxy service. Please refer + Adding a Proxy Service for details. +

    +

    + Proxy Service Actions +

    +

    + You can edit, delete, enable statistics, start and stop the proxy service, + and enable tracing for the proxy service as described below. All existing + proxy services will be displayed in the services listing page with a special + icon been used to denote Proxy Services. Clicking on the name of a Proxy Service + there will take you to configurations specific to that service. The proxy + service actions are initiated by clicking on the respective links that could be + found in the in the table. +

    +

    +

    + Proxy Services +

    +

    +

    + Please refer the documentation of + the service listing page for general configurations that could be done on a proxy service. +

    +

    + Proxy Service specific configurations +

    +
    +

    + Edit Proxy Service +

    +

    + Use this function to modify existing proxy services. +

    +
      +
    1. + In the Specific Configuration section of the Proxy Service + click the Edit link. The proxy service page will be displayed. +
    2. +
    +

    + Redeploy Proxy Service +

    +

    + Use this function to redeploy the proxy service. +

    +
      +
    1. + In the Specific Configuration section of the Proxy Service + click the Redeploy link. This will redeploy the proxy service. +
    2. +
    +

    + Enable Statistics +

    +

    + Use this function to generate statistics for the proxy services. +

    +
      +
    • + In the Specific Configuration section of the Proxy Service + click the Enable Statistics link. +
    • +
    +
    +
    +

    + Enable Tracing +

    +

    + Use this function to enable tracing for the proxy services. +

    +
      +
    • + In the Specific Configuration section of the Proxy Service + click the Enable Tracing link. +
    • +
    +
    +

    +

    + Scheduled Tasks +

    +

    + The built-in Quartz scheduler lets administrators schedule tasks to run at + specified intervals. Tasks may be used to initiate long-running tasks, + automate recurring processes and facilitate reporting etc. The tasks are + simple Java classes that must implement org.apache.synapse.startup.Task + interface that just defines a single 'public void execute();' method. A + Task may thus use the ESB/Apache Synapse APIs to poll external services, + inject messages into the ESB or perform any task that could be implemented + in Java. +

    +

    + Please refer the + documentation on scheduled tasks for details. +

    +

    + Endpoints +

    +

    + An endpoint is a specific destination for a message. It may be specified + as an Address endpoint, WSDL endpoint, a fail over group, or a load balance + group. +

    +

    + Endpoints can be added, edited, and deleted. You can also enable + statistics for Address and WSDL endpoints. +

    +

    + Please refer the documentation on + endpoints for details. +

    +

    + Sequences +

    +

    + A sequence element is used to define a sequence of mediators that can be + invoked later as a sequence. If the configuration defines a sequence named + Main, then it is considered as the main mediation sequence of the ESB. If + such a sequence is not defined locally, and a registry has been specified, + the registry is looked up for a key named "main" to find the main mediator + sequence. If User doesn't define a main or fault sequence ESB will create default sequences. +

    +

    + Please refer the documentation on managing + sequences for details. +

    + +

    + Message Stores +

    +

    + A Message Store element is used to define a Message store that can be used to store ESB + Messages. Store mediator can be used to store the messages in a message store.Message processor + associated with Message store can be used to implement different messaging patterns. +

    +

    + Associated Message processors can be used to consume messages from message stores and do processing. +

    +

    + Users can create there own message store implementations and use it. WSO2 ESB ships with in memory + message store and a jms message store. +

    +

    + Please refer the + documentation + on managing + Message stores for details. +

    +

    + Message Processor +

    +

    + A sequence element is used to define a Message Processor which can be used to process messages + in an associated message store. +

    +

    + Please refer the + documentation + on managing + sequences for details. +

    +

    + Local Registry Entries +

    +

    + The local registry entries are used to locally define resources such as + scripts, schemas, WSDLs, policies and other resources in a configuration. + They are not uploaded or fetched from the Integrated Registry. They are + static. An entry that exists in the local registry has higher precedence + over an entry with the same name that exists in the integrated registry. +

    +

    + Adding a Local Registry Entry +

    +
      +
    1. + Click Local Entries on the navigator. +
    2. +
    3. + In the Manage Local Registry Entries pane, you can choose the type of + local entry you want and click Add of each entry to add a + one. +

      +

      + Registry Entry +

      +

      +

    4. +
    +
    +

    + In-Lined Text +

    +
    +
    +
      +
    1. + Enter a name for the entry. +
    2. +
    3. + In the Value field, specify the property + values +
    4. +
    5. + Click Save.
      +
    6. +
    +

    + In-Lined XML +

    +
    +
    +
      +
    1. + Enter a name for the XML entry. +
    2. +
    3. + In the Value field, enter the XML code. +
    4. +
    5. + Click Save. +
    6. +
    +

    + Source URL +

    +
      +
    1. + Enter a name of the source file. +
    2. +
    3. + In the Value field, specify the location of + the source file as a URL. +
    4. +
    5. + Click Save. +
    6. +
    +
    +

    + Local Registry Actions +

    +

    + You can edit and delete previously entered local registry entries. All + existing local registry entries will be displayed in the Registry Entries + table. The registry actions are initiated by clicking on the respective + icons in the table. +

    +

    +

    + Local entry actions +

    +

    +

    +

    + Edit Local Registry Entry +

    +

    + Use this option to modify registry entries. +

    +
      +
    1. + In the Actions column of the Registry table, + click the corresponding Edit icon of the entry you want to edit. The + registry entry page will be displayed. +
    2. +
    3. + Make the necessary changes and click Save. +
    4. +
    +

    + Delete Local Registry Entry +

    +

    + Use this function to delete registry entries that have been entered + previously. +

    +
      +
    • + In the Actions column of the Registry table, + click the corresponding Delete icon of the entry you want to delete. +
    • +
    +
    +

    + ESB Configuration (Source View) +

    +

    + This function commits the configuration changes you have made to the local + storage of the host running the ESB. The XML code for your configuration + is displayed in the Current Configuration text area. You can also make any + changes directly in the XML code. +

    +

    + To apply your changes and save the configuration to the local storage click + the Update button. This will first validate the provided + configuration and warn you about any faults or inconsistencies detected. User has + the option of proceeding with the update operation or cancelling it at this + point. If no faults are detected, the configuration will be applied and saved to + the storage. +

    +

    + The Reset operation could be used to revert any changes you + have made to the source view and revert back to last saved configuration. +

    +

    + Please refer the documentation on managing + synapse configuration for details. +

    +

    +

    +

    +

    + Managing the Integrated Registry +

    +

    + The registry provides a mechanism of creating and storing configuration + elements outside the ESB. These registry contents can be dynamically + loaded or modified, which will allow runtime modification of the ESB + behaviors. The folder structure gives a clear view of the available files + and easy access to modifying the files. Once these files are loaded, their + content are cached in the ESB for the specified duration, and is updated + at the end of the caching period. +

    +

    + You can use these files at the time of defining target sequences and + target endpoints for the proxy services. +

    +

    +

    + Manage Registry Entry +

    +

    Please refer the documentation on managing + the embedded registry for details.

    +

    +

    + Monitoring the System +

    +

    + This feature provides runtime information about the ESB on the Administrator + Console. It displays system statistics, + mediation statistics, + transport statistics, + system logs, + SOAP tracer, + mediation tracer and + Message flows. +

    +

    + A detailed guide on monitoring WSO2 ESB can be found + here. +

    +

    +

    +

    + References +

    +

    + WSO2 ESB Installation Guide +

    +

    + ESB Configuration Language +

    +

    + + diff --git a/docs/xdoc/webapp_deployment_guide.xml b/docs/xdoc/webapp_deployment_guide.xml new file mode 100644 index 0000000000..0a13d98fed --- /dev/null +++ b/docs/xdoc/webapp_deployment_guide.xml @@ -0,0 +1,185 @@ + + + + + + + + + WSO2 ESB - Webapp Deployment Guide + + + + + + [ Deployment Guide ] +

    + WSO2 Enterprise Service Bus (ESB) Webapp Deployment Guide +

    + +

    + WSO2 ESB can be deployed on different application servers such as IBM WebSphere, + BEA WebLogic Server, JBoss and Apache Tomcat. This guide describes how to deploy the ESB + on Apache Tomcat in a step-by-step manner. The methodology should be the same for + other application server deployments as well, but it will require some knowledge on the + application server for you to get it working on that particular application server. +

    +

    Step 1 - Downloading and installing Apache Tomcat

    + +

    + You can download the latest version of Apache Tomcat from + here (We will be using Apache + Tomcat 5.5.20 to demonstrate this particular deployment). Extract the downloaded distribution + to a specific location and define the environment variables properly. (Assume you extracted + the downloaded Tomcat into the folder \opt\software\apache-tomcat-5.5.20) +

    + +
    E.g.: -
    +    CATALINA_HOME=\opt\software\apache-tomcat-5.5.20
    +    
    + +

    Step 2 - Downloading and installing WSO2 ESB

    + +

    + Download the WSO2 ESB distribution and extract to a specific location in the file system. + (E.g.:- /opt/software/wso2esb-4.0.0). +

    + +

    + Copy the repository in the extracted distribution to a different location + (this is the directory we are planning to treat as ESB_HOME, E.g.:- /opt/software/esb-home) +

    + +

    Step 3 - Enable HTTPS on the Apache Tomcat

    + +

    + Next you will need to enable HTTPS on Apache Tomcat since WSO2 ESB administration console + runs over HTTPS. To do this, open up the server.xml file located at $CATALINA_HOME/conf + using a text editor and uncomment the following: +

    + +
    +  <Connector port="8443" maxHttpHeaderSize="8192"
    +        maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    +        enableLookups="false" disableUploadTimeout="true"
    +        acceptCount="100" scheme="https" secure="true"
    +        clientAuth="false" sslProtocol="TLS"/>
    + +

    + Then you will need to provide the keystore file location along with it's password as below. +

    + +
    +  <Connector port="8443" maxHttpHeaderSize="8192"
    +        maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    +        enableLookups="false" disableUploadTimeout="true"
    +        acceptCount="100" scheme="https" secure="true"
    +        clientAuth="false" sslProtocol="TLS"
    +        keystoreFile = "/opt/software/wso2esb-3.0.1/resources/security/wso2carbon.jks"
    +        keystorePass="wso2carbon"/>
    + +

    Step 4 - Setting environment variables

    + +

    + You will have to set an environment variable with the name CARBON_HOME pointing it to + the directory into which you have copied the repository directory. +

    + +
    E.g.:-
    +    CARBON_HOME=/opt/software/esb-home
    +    
    + +

    Step 5 - Copying required files to Apache Tomcat

    + +

    Now create a new directory inside the webapps folder of Tomcat.

    +
    E.g.:-
    +    /opt/software/apache-tomcat-5.5.20/webapps/esb
    +    
    + +

    + Next, you need to copy the WEB-INF folder of the extracted distribution of the ESB to + the created webapp directory. +

    +
    E.g.:-
    +  cp -r /opt/software/wso2esb-4.0.0/lib/core/WEB-INF /opt/software/apache-tomcat-5.5.20/webapps/esb/
    +    
    +

    + You should also copy all the jar files in lib/api directory of ESB distribution into the + WEB-INF/lib directory of the ESB webapp in Tomcat. +

    +
    E.g.:-
    +  cp /opt/software/wso2esb-4.0.0/lib/api/*.jar /opt/software/apache-tomcat-5.5.20/webapps/esb/WEB-INF/lib
    +    
    + +

    Step 6 - Configuring the WSO2 ESB

    + +
      +
    1. Open the carbon.xml file which is in the CARBON_HOME/conf folder and specify the + following URL as the ServerURL https://localhost:8443/esb/services/ +
    2. +
    3. Then you need to specify the absolute paths of the WSO2CARBON_DB of the two files + registry.xml and user-mgt.xml +
      jdbc:derby:database/WSO2CARBON_DB;create=true
      has to be replaced with +
      jdbc:derby:/opt/software/esb-home/WSO2CARBON_DB;create=true
      +
    4. +
    5. In order for the logging to work properly you need to copy the log4j.properties file + found at the lib directory of the extracted distribution to the webapp classpath
    6. +
    7. You need to specify the absolute paths for the two .jks files wso2carbon.jks and + client-truststore.jks specified in the HTTPS transport configuration section of the + axis2.xml and also the wso2carbon.jks file specified in the carbon.xml file. +
    8. +
    9. Further, you need to uncomment the wsdlEPRPrefix parameter of the HTTP and HTTPS + transport receiver configurations and put the value as +
      http://${host}:${port}/services
      +
    10. +
    11. Finally you will have to specify the absolute path of the Synapse configuration files in the + axis2.xml file located at CARBON_HOME/repository/conf. Simply change, +
      repository/deployment/server/synapse-config/default
      +to +
      /opt/software/esb-home/repository/deployment/server/synapse-config/default
      +
    12. +
    +

    Step 7 - Starting the Apache Tomcat Server

    + +

    + Now you can start the Apache Tomcat server by giving the command from the tomcat + installation bin directory

    +
      ./catalina.sh run
    + +

    Step 7 - Login to the WSO2 ESB Administration Console

    + +

    Now you should be able to login to the WSO2 ESB Administration Console as,

    +
      https://localhost:8443/esb/carbon
    + +

    Specific Instructions when Deploying WSO2 ESB in Other Application Servers

    +

    JBoss

    +
      +
    1. In [Step-5], You should skip copying jboss-transaction-api-1.0.1.GA.jar when copying jars from + /opt/software/wso2esb-4.0.0/lib/api/ to + /opt/software/apache-tomcat-5.5.20/webapps/esb/WEB-INF/lib +
    2. +
    3. + Delete /opt/software/esb-home/repository//components/plugins/geronimo-jta_1.1_spec-1.1.0.wso2v1.jar +
    4. +
    +

    Without following these two steps, Transaction Mediator will not work when WSO2 ESB deployed in JBoss

    + + diff --git a/docs/xdoc/xpath.xml b/docs/xdoc/xpath.xml new file mode 100644 index 0000000000..f1863b8ac1 --- /dev/null +++ b/docs/xdoc/xpath.xml @@ -0,0 +1,219 @@ + + + + + + + + + WSO2 ESB - XPath Functions & Variables + + + + + + [ Documentation Index ] +

    WSO2 Enterprise Service Bus (ESB) XPath Extensions Catalog

    +

    Contents

    +
    +
      +
    1. + Introduction +
    2. +
    3. + Functions + + +
    4. +
    5. + Variables + + + + +
    6. +
    +
    +

    Introduction

    +

    + WSO2 ESB supports standard XPath functions and variables through its underlying XPath + engine. All these standard XPath features are available for configuring the ESB. + XPath allows to build custom functions to extend its functionality. There are several + custom XPath functions and variables defined by the WSO2 ESB for accessing various + message properties. +

    +

    Functions

    +

    + There are two custom functions supported by the ESB.

    +
      +
    1. get-property
    2. +
    3. base64Encode
    4. +
    +

    get-property function

    +

    Syntax:

    +
      +
    1. + get-property(String propertyName)
    2. +
    3. + get-property(String scope, String propertyName)
    4. +
    +

    + Get property function retrieves a message property at the given scope. If only the property + name is specified without the scope it assumes the default syanpse scope.

    +

    + Supported Scopes

    +
      +
    1. synpase
    2. +
    3. axis2
    4. +
    5. transport
    6. +
    +

    Special Properties suported by get-property function

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameReturn Value
    ToIncoming URL as a String or empty string («») if a To address is + not defined. +
    FromFrom address as a String or empty string («») if a From address + is not defined +
    ActionSOAP Addressing Action header value as a String or empty string («») + if a Action is not defined +
    FaultToSOAP FautTo header value as a String or empty string («») if a + FaultTo address is not defined +
    ReplyToReplyTo header value as a String or empty string («») if a + ReplyTo address is not defined +
    MessageIDA unique identifier (UUID) for the message as a String or empty string («») + if MessageID is not defined. This id is guaranteed to be unique. +
    FAULTTRUE if the message has a fault or empty string if message doesn't have a + fault +
    MESSAGE_FORMATReturns pox, get, soap11, soap12 depending on the message. If a message type + is unknown this returns soap12 +
    OperationNameOperation name corresponding to the message. A proxy service with a WSDL can + have different operations. If the WSDL is not defined ESB defines fixed + operations +
    +

    base64Encode function

    +

    Syntax:

    + +

    base64Encode(string)

    + +

    Returns the base64 encoded value of the argument.

    + +

    Variables

    +

    There are several variables supported by the ESB. These are used for accessing various + properties and refer to fixed parts in the ESB.

    +
      +
    1. $axis2
    2. +
    3. $trp
    4. +
    5. $ctx
    6. +
    7. $url
    8. +
    + +

    These XPath variables gets the properties at various scopes.

    + +

    $axis2

    + +

    Gets the property at the axis2 scope.

    + +

    i.e. To get the property named 'messageType' use the following XPath expression

    + +
    $axis2:messageType
    + +

    $trp

    + +

    Gets a transport header.

    + +

    i.e. To get the transport header named Content-Type use the following XPath expression

    + +
    $trp:Content-Type
    + +

    HTTP transport headers are considered to be case insensitive. So in HTTP case

    + +

    $trp:Content-Type and $trp:CONENT-TYPE are equal.

    + +

    $ctx

    + +

    Gets a property at the default scope.

    + +

    i.e To get the property named 'foo' at the default scope use the following XPath expresion

    + +
    $ctx:foo
    + +

    $url

    + +

    Gets a URL parameter.

    + +

    i.e. To get the URL parameter named 'bar' use the following XPth expression

    + +
    $url:foo
    + + diff --git a/modules/distribution/pom.xml b/modules/distribution/pom.xml new file mode 100644 index 0000000000..2987efe578 --- /dev/null +++ b/modules/distribution/pom.xml @@ -0,0 +1,70 @@ + + + + + + + org.wso2.am + am-parent + 1.7.0-SNAPSHOT + ../../pom.xml + + + 4.0.0 + am-distribution-parent + pom + WSO2 API Manager - Distribution Parent + http://wso2.com/products/api-manager + WSO2 API Manager Distribution Parent + + + + Apache License Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + + + + + product + + + + + + + + + + maven-clean-plugin + + + auto-clean + initialize + + clean + + + + + + + + diff --git a/modules/distribution/product/pom.xml b/modules/distribution/product/pom.xml new file mode 100644 index 0000000000..4cda9b26fe --- /dev/null +++ b/modules/distribution/product/pom.xml @@ -0,0 +1,301 @@ + + + + + + + org.wso2.am + am-distribution-parent + 1.7.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + wso2am + pom + WSO2 API Manager - Distribution + http://www.wso2.org/projects/am/java + WSO2 API Manager Distribution + + + + com.h2database.wso2 + h2-database-engine + ${orbit.version.h2.engine} + + + org.eclipse.osgi + org.eclipse.osgi + + + commons-logging + commons-logging + + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + 2.0-alpha-4 + false + + + unpack-wso2carbon + package + + unpack + + + + + org.wso2.carbon + wso2carbon-core + ${carbon.platform.version} + zip + true + target + + + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + 1.1 + + + extract-docs-from-components + package + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + clean_target + install + + + + + + + + + + + + + run + + + + create-API-manager-database + package + + run + + + + + + + + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-site-plugin + 3.0 + + + package + + site + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + pre_dist + test + + attached + + + + ${basedir}/src/main/assembly/filter.properties + + + src/main/assembly/dist.xml + + + + + dist + package + + attached + + + + ${basedir}/src/main/assembly/filter.properties + + + src/main/assembly/bin.xml + + src/main/assembly/docs.xml + + + + + + + + + com.google.code.maven-replacer-plugin + replacer + 1.5.2 + + + prepare-package + + replace + + + + + ${basedir}/../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/repository/conf/security/application-authentication.xml + + + /ApplicationAuthentication/JDBCPersistenceManager/DataSource/Name + (jdbc/WSO2CarbonDB) + jdbc/WSO2AM_DB + + + + + + + + + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.4 + + + + index + + + + + + + + diff --git a/modules/distribution/product/src/main/assembly/bin.xml b/modules/distribution/product/src/main/assembly/bin.xml new file mode 100644 index 0000000000..6a88b12235 --- /dev/null +++ b/modules/distribution/product/src/main/assembly/bin.xml @@ -0,0 +1,824 @@ + + + + + zip + + false + + + target/wso2carbon-core-${carbon.platform.version} + wso2am-${pom.version} + + **/*.sh + **/conf/axis2/axis2.xml + **/conf/axis2/axis2.xml_NHTTP + **/conf/axis2/axis2.xml_PT + **/conf/axis2/tenant-axis2.xml + **/conf/synapse.xml + **/log4j.properties + **/services/sample01.aar + **/repository/services/version/** + **/version.txt + **/wso2server.bat + **/README.txt + **/LICENSE.txt + **/INSTALL.txt + **/release-notes.html + **/carbon.xml + **/registry.xml + **/identity.xml + **/master-datasources.xml + **/dbscripts/mysql.sql + **/dbscripts/db2.sql + **/dbscripts/mysql_cluster.sql + **/bin/ciphertool.bat + **/cipher-text.properties + **/cipher-tool.properties + **/authenticators.xml + **/lib/org.wso2.ciphertool-1.0.0-wso2v2.jar + **/client-truststore.jks + + + + target/wso2carbon-core-${carbon.platform.version} + wso2am-${pom.version} + + **/*.sh + + + **/wso2server.sh + + 755 + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/repository/conf/security + wso2am-${pom.version}/repository/conf/security + + authenticators.xml + + + + + src/main/conf/synapse-configs + wso2am-${pom.version}/repository/deployment/server/synapse-configs + + + src/main/conf/synapse-configs/default/sequences + wso2am-${pom.version}/repository/resources/apim-synapse-config/ + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/repository/conf/advanced/ + wso2am-${pom.version}/repository/conf/advanced + + **/qpid-config.xml + **/qpid-jmxremote.access + **/qpid-virtualhosts.xml + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/repository/conf/identity/ + wso2am-${pom.version}/repository/conf/identity + + + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/dbscripts/identity/application-mgt/ + + wso2am-${pom.version}/dbscripts/identity/application-mgt + + **/**.sql + + + + + ../resources/sql/ + + wso2am-${pom.version}/dbscripts/apimgt + + **/**.sql + + + + ../../p2-profile-gen/target/WSO2-CARBON-PATCH-${carbon.version}-0001/dbscripts + wso2am-${pom.version}/dbscripts + + + + ../resources/migration-1.0.0_to_1.2.0/ + + wso2am-${pom.version}/dbscripts/migration-1.0.0_to_1.2.0 + + + + ../resources/migration-1.2.0_to_1.3.0/ + + wso2am-${pom.version}/dbscripts/migration-1.2.0_to_1.3.0 + + + + ../resources/migration-1.3.0_to_1.4.0/ + + wso2am-${pom.version}/dbscripts/migration-1.3.0_to_1.4.0 + + + + + ../resources/migration-1.4.0_to_1.5.0/ + + wso2am-${pom.version}/dbscripts/migration-1.4.0_to_1.5.0 + + + + + ../resources/migration-1.5.0_to_1.6.0/ + + wso2am-${pom.version}/dbscripts/migration-1.5.0_to_1.6.0 + + + + + ../resources/migration-1.6.0_to_1.7.0/ + + wso2am-${pom.version}/dbscripts/migration-1.6.0_to_1.7.0 + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/repository/deployment/server/jaggeryapps/publisher/ + wso2am-${pom.version}/repository/deployment/server/jaggeryapps/publisher + + publisherLogo/** + publisherTheme/** + publisherSite/** + footer/** + localstyles.css + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/repository/deployment/server/jaggeryapps/store/ + wso2am-${pom.version}/repository/deployment/server/jaggeryapps/store + + storeLogo/** + storeSite/** + base-page/** + login/** + styles-layout.css + + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/repository/deployment/server/jaggeryapps/workflow-admin/ + wso2am-${pom.version}/repository/deployment/server/jaggeryapps/workflow-admin + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/repository/deployment/server/jaggeryapps/admin-dashboard/ + wso2am-${pom.version}/repository/deployment/server/jaggeryapps/admin-dashboard + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/repository/modules + ${pom.artifactId}-${pom.version}/modules/ + + */** + + + + ../../jaggery + wso2am-${pom.version}/modules + + **/**.xml + + + + + ../../../modules/styles/service/src/main/resources/web/styles/images + wso2am-${pom.version}/resources/allthemes/Default/images + + + ../../../modules/styles/service/src/main/resources/web/styles/css + wso2am-${pom.version}/resources/allthemes/Default/admin + + + ../../../config/rxts + wso2am-${pom.version}/repository/resources/rxts + + **/**.rxt + + + + + ../../integration/tests/src/test/resources/artifacts/AM/scripts + wso2am-${pom.version}/repository/resources/scripts + + **/**.jmx + + + + + ../resources/scripts/tenant_Creation + wso2am-${pom.version}/repository/resources/scripts/tenantCreation + + **/**.jmx + + + + + ../resources/api_templates + wso2am-${pom.version}/repository/resources/api_templates + + **/**.xml + + + + src/main/conf/governance + wso2am-${pom.version}/repository/resources + + **/** + + + + ../../samples + wso2am-${pom.version}/samples + + **/*.* + + + **/PizzaShack/** + **/TwitterSearch/** + **/YahooPlaceFinder/** + + + + ../../samples + wso2am-${pom.version}/samples + + **/PizzaShack/**/pom.xml + + + + src/main/business-processes + wso2am-${pom.version}/business-processes + + **/*.* + + + + + src/main/statistics/target + wso2am-${pom.version}/statistics + + **/*.* + + + + + + +../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/repository/deployment/server/webapps + + ${pom.artifactId}-${pom.version}/repository/deployment/server/webapps + + oauth2.war + + + + +../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/repository/resources/rxts/forum + + ${pom.artifactId}-${pom.version}/repository/resources/rxts/forum + + *.rxt + + + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/repository/deployment/server/webapps + + ${pom.artifactId}-${pom.version}/repository/deployment/server/webapps + + + authenticationendpoint.war + + + + + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/multitenancy/ + + ${pom.artifactId}-${pom.version}/repository/conf/multitenancy + + **/stratos.xml + **/multitenancy-packages.xml + **/usage-throttling-agent-config.xml + **/cloud-services-desc.xml + + + + + + + src/main/resources/STRATOS_ROOT + ${pom.artifactId}-${pom.version}/repository/deployment/server/webapps/STRATOS_ROOT + 755 + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/lib/runtimes + ${pom.artifactId}-${pom.version}/lib/runtimes/ + + */** + + + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/modules + ${pom.artifactId}-${pom.version}/modules/ + + **/carbon/** + **/process/** + + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.kernel.version}/dbscripts/service-provider/ + ${pom.artifactId}-${pom.version}/dbscripts/service-provider + + **/**.sql + + + + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0001 + wso2am-${pom.version}/repository/components/patches/ + + **/patch0001/*.* + + + + + ../../p2-profile-gen/target/WSO2-CARBON-PATCH-4.2.0-0001/lib + ${pom.artifactId}-${pom.version}/lib + + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0002 + wso2am-${pom.version}/repository/components/patches/ + + **/patch0002/*.* + + + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0003 + wso2am-${pom.version}/repository/components/patches/ + + **/patch0003/*.* + + + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0004 + wso2am-${pom.version}/repository/components/patches/ + + **/patch0004/*.* + + + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0005 + wso2am-${pom.version}/repository/components/patches/ + + **/patch0005/*.* + + + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0006 + wso2am-${pom.version}/repository/components/patches/ + + **/patch0006/*.* + + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0007 + wso2am-${pom.version}/repository/components/patches/ + + **/patch0007/*.* + + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0008 + wso2am-${pom.version}/repository/components/patches/ + + **/patch0008/*.* + + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0001/dbscripts + wso2am-${pom.version}/dbscripts + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0002/dbscripts + wso2am-${pom.version}/dbscripts + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0002/lib + wso2am-${pom.version}/lib + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0003/dbscripts + wso2am-${pom.version}/dbscripts + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0003/lib + wso2am-${pom.version}/lib + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0004/dbscripts + wso2am-${pom.version}/dbscripts + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0004/bin + wso2am-${pom.version}/bin + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0005/dbscripts + wso2am-${pom.version}/dbscripts + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0005/lib + wso2am-${pom.version}/lib + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0006/dbscripts + wso2am-${pom.version}/dbscripts + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0004/repository/resources/security + wso2am-${pom.version}/repository/resources/security/ + + **/cipher-tool.properties + + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0005/repository/resources/security + wso2am-${pom.version}/repository/resources/security/ + + **/client-truststore.jks + + + + ../../p2-profile/product/target/WSO2-CARBON-PATCH-4.2.0-0006/lib + wso2am-${pom.version}/lib/ + + **/org.wso2.ciphertool-1.0.0-wso2v2.jar + + + + + + + + + wso2am-${pom.version}/lib/core/WEB-INF/lib + + org.wso2.carbon:org.wso2.carbon.mediator.bridge:jar + + + + + wso2am-${pom.version}/lib/core/WEB-INF/lib/ + org.apache.qpid.wso2:qpid-client:jar + + + + wso2am-${pom.version}/samples/axis2Client/client_repo/modules + + org.apache.axis2:addressing:mar + org.apache.rampart:rampart:mar + org.apache.sandesha2:sandesha2:mar + + ${artifact.artifactId}.${artifact.extension} + + + wso2am-${pom.version}/samples/axis2Server/repository/modules + + org.apache.axis2:addressing:mar + org.apache.rampart:rampart:mar + org.apache.sandesha2:sandesha2:mar + + ${artifact.artifactId}.${artifact.extension} + + + wso2am-${pom.version}/repository/axis2/client/lib + + bouncycastle:bcprov-jdk15:jar + + ${artifact.artifactId}.${artifact.extension} + + + wso2am-${pom.version}/repository/deployment/client/modules + + org.apache.rampart:rampart:mar + + + + + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/repository/conf/claim-config.xml + wso2am-${pom.version}/repository/conf + + + + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/repository/conf/event-broker.xml + wso2am-${pom.version}/repository/conf + + + src/main/conf/axis2.xml + wso2am-${pom.version}/repository/conf/axis2 + axis2.xml + + + src/main/conf/axis2_blocking_client.xml + wso2am-${pom.version}/repository/conf/axis2 + axis2_blocking_client.xml + + + src/main/conf/axis2.xml_NHTTP + wso2am-${pom.version}/repository/conf/axis2 + axis2.xml_NHTTP + + + src/main/conf/axis2.xml_PT + wso2am-${pom.version}/repository/conf/axis2 + axis2.xml_PT + + + src/main/conf/tenant-axis2.xml + wso2am-${pom.version}/repository/conf/axis2 + tenant-axis2.xml + + + src/main/conf/master-datasources.xml + wso2am-${pom.version}/repository/conf/datasources + master-datasources.xml + + + src/main/conf/registry.xml + wso2am-${pom.version}/repository/conf + registry.xml + true + 644 + + + src/main/conf/identity.xml + wso2am-${pom.version}/repository/conf + identity.xml + + + src/main/conf/log4j.properties + wso2am-${pom.version}/repository/conf + log4j.properties + true + + + src/main/conf/synapse.properties + wso2am-${pom.version}/repository/conf + synapse.properties + true + + + src/main/conf/datasources.properties + wso2am-${pom.version}/repository/conf + datasources.properties + true + + + src/main/conf/nhttp.properties + wso2am-${pom.version}/repository/conf + nhttp.properties + true + + + src/main/conf/passthru-http.properties + wso2am-${pom.version}/repository/conf + passthru-http.properties + true + + + src/main/conf/jndi.properties + wso2am-${pom.version}/repository/conf + jndi.properties + true + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/repository/conf/etc/logging-config.xml + wso2am-${pom.version}/repository/conf/etc + + + + ../../distribution/product/target/repository/database/WSO2AM_DB.h2.db + wso2am-${pom.version}/repository/database + true + 666 + + + ../../../docs/xdoc/release-notes.xml + wso2am-${pom.version} + release-notes.html + 644 + + + target/wso2carbon-core-${carbon.platform.version}/bin/README.txt + wso2am-${pom.version}/bin/ + true + 644 + + + target/wso2carbon-core-${carbon.platform.version}/bin/version.txt + wso2am-${pom.version}/bin/ + true + 644 + + + ../../../config/api-manager.xml + wso2am-${pom.version}/repository/conf + true + 755 + + + ../../../config/wso2server.sh + wso2am-${pom.version}/bin + true + 755 + + + ../../../config/wso2server.bat + wso2am-${pom.version}/bin + true + + + + src/main/conf/carbon.xml + wso2am-${pom.version}/repository/conf/ + true + + + src/main/conf/cloud-services-desc.xml + wso2am-${pom.version}/repository/conf/multitenancy + true + + + src/main/resources/httpmime-4.2.5.jar + wso2am-${pom.version}/repository/components/lib + true + + + src/main/resources/encoder-1.1.jar + wso2am-${pom.version}/repository/components/lib + true + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/tomcat/webapp-classloading.xml + wso2am-${pom.version}/repository/conf/tomcat + true + 644 + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/tomcat/webapp-classloading-environments.xml + wso2am-${pom.version}/repository/conf/tomcat + true + 644 + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/thrift-authentication.xml + wso2am-${pom.version}/repository/conf + 644 + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/security/application-authentication.xml + wso2am-${pom.version}/repository/conf/security + 644 + + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/data-bridge/thrift-agent-config.xml + wso2am-${pom.version}/repository/conf/data-bridge/ + 644 + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/tomcat/context.xml + wso2am-${pom.version}/repository/conf/tomcat + true + 644 + + + + + + + diff --git a/modules/distribution/product/src/main/assembly/dist.xml b/modules/distribution/product/src/main/assembly/dist.xml new file mode 100644 index 0000000000..3f9a045940 --- /dev/null +++ b/modules/distribution/product/src/main/assembly/dist.xml @@ -0,0 +1,36 @@ + + + + zip + + false + + + + ../../p2-profile/product/target/wso2carbon-core-${carbon.platform.version}/repository/components + wso2am-${pom.version}/repository/components + + **/eclipse.ini + **/*.lock + **/.data + **/.settings + + + + diff --git a/modules/distribution/product/src/main/assembly/docs.xml b/modules/distribution/product/src/main/assembly/docs.xml new file mode 100644 index 0000000000..837f695b18 --- /dev/null +++ b/modules/distribution/product/src/main/assembly/docs.xml @@ -0,0 +1,32 @@ + + + + docs + + zip + + false + + + target/site + wso2am-${pom.version}-docs + 755 + + + diff --git a/modules/distribution/product/src/main/assembly/filter.properties b/modules/distribution/product/src/main/assembly/filter.properties new file mode 100644 index 0000000000..52842383d8 --- /dev/null +++ b/modules/distribution/product/src/main/assembly/filter.properties @@ -0,0 +1,8 @@ +product.name=WSO2 API Manager +product.key=AM +product.version=1.7.0 + +carbon.version=4.2.0 +am.version=1.7.0 +default.server.role=APIManager +bundle.creators=org.wso2.carbon.mediator.bridge.MediatorBundleCreator diff --git a/modules/distribution/product/src/main/assembly/src.xml b/modules/distribution/product/src/main/assembly/src.xml new file mode 100644 index 0000000000..e55b1d4e3d --- /dev/null +++ b/modules/distribution/product/src/main/assembly/src.xml @@ -0,0 +1,73 @@ + + + src + false + + zip + + + + + target/sources + wso2am-${pom.version}-src + + **/* + + + + ../../.. + wso2am-${pom.version}-src + + modules/**/* + **/pom.xml + docs/**/* + + + **/target + **/target/**/* + **/build + **/build/**/* + **/.settings + **/.classpath + **/.project + **/.wtpmodules + **/*.iml + **/.settings + **/.settings/**/* + + + + + + ../../../LICENSE.txt + wso2am-${pom.version}-src + true + + + ../../../README.txt + wso2am-${pom.version}-src + true + + + ../../../INSTALL.txt + wso2am-${pom.version}-src + true + + + diff --git a/modules/distribution/product/src/main/business-processes/application-creation/BPEL/ApplicationApprovalWorkFlowProcess_1.0.0.zip b/modules/distribution/product/src/main/business-processes/application-creation/BPEL/ApplicationApprovalWorkFlowProcess_1.0.0.zip new file mode 100644 index 0000000000..62747471ab Binary files /dev/null and b/modules/distribution/product/src/main/business-processes/application-creation/BPEL/ApplicationApprovalWorkFlowProcess_1.0.0.zip differ diff --git a/modules/distribution/product/src/main/business-processes/application-creation/HumanTask/ApplicationsApprovalTask-1.0.0.zip b/modules/distribution/product/src/main/business-processes/application-creation/HumanTask/ApplicationsApprovalTask-1.0.0.zip new file mode 100644 index 0000000000..801e3b9226 Binary files /dev/null and b/modules/distribution/product/src/main/business-processes/application-creation/HumanTask/ApplicationsApprovalTask-1.0.0.zip differ diff --git a/modules/distribution/product/src/main/business-processes/application-registration/BPEL/ApplicationRegistrationWorkflowProcess_1.0.0.zip b/modules/distribution/product/src/main/business-processes/application-registration/BPEL/ApplicationRegistrationWorkflowProcess_1.0.0.zip new file mode 100644 index 0000000000..283369181c Binary files /dev/null and b/modules/distribution/product/src/main/business-processes/application-registration/BPEL/ApplicationRegistrationWorkflowProcess_1.0.0.zip differ diff --git a/modules/distribution/product/src/main/business-processes/application-registration/HumanTask/ApplicationRegistrationTask-1.0.0.zip b/modules/distribution/product/src/main/business-processes/application-registration/HumanTask/ApplicationRegistrationTask-1.0.0.zip new file mode 100644 index 0000000000..03651c1f62 Binary files /dev/null and b/modules/distribution/product/src/main/business-processes/application-registration/HumanTask/ApplicationRegistrationTask-1.0.0.zip differ diff --git a/modules/distribution/product/src/main/business-processes/epr/ApplicationCallbackService.epr b/modules/distribution/product/src/main/business-processes/epr/ApplicationCallbackService.epr new file mode 100644 index 0000000000..c8f9926a4a --- /dev/null +++ b/modules/distribution/product/src/main/business-processes/epr/ApplicationCallbackService.epr @@ -0,0 +1,17 @@ + + https://localhost:8243/services/WorkflowCallbackService + + SInvokeEPR + + + + + admin + admin + + + diff --git a/modules/distribution/product/src/main/business-processes/epr/ApplicationService.epr b/modules/distribution/product/src/main/business-processes/epr/ApplicationService.epr new file mode 100644 index 0000000000..407a608824 --- /dev/null +++ b/modules/distribution/product/src/main/business-processes/epr/ApplicationService.epr @@ -0,0 +1,17 @@ + + http://localhost:9765/services/ApplicationService + + SInvokeEPR + + + + + admin + admin + + + diff --git a/modules/distribution/product/src/main/business-processes/epr/RegistrationCallbackService.epr b/modules/distribution/product/src/main/business-processes/epr/RegistrationCallbackService.epr new file mode 100644 index 0000000000..c8f9926a4a --- /dev/null +++ b/modules/distribution/product/src/main/business-processes/epr/RegistrationCallbackService.epr @@ -0,0 +1,17 @@ + + https://localhost:8243/services/WorkflowCallbackService + + SInvokeEPR + + + + + admin + admin + + + diff --git a/modules/distribution/product/src/main/business-processes/epr/RegistrationService.epr b/modules/distribution/product/src/main/business-processes/epr/RegistrationService.epr new file mode 100644 index 0000000000..b38ac46051 --- /dev/null +++ b/modules/distribution/product/src/main/business-processes/epr/RegistrationService.epr @@ -0,0 +1,17 @@ + + http://localhost:9765/services/ApplicationRegistration + + SInvokeEPR + + + + + admin + admin + + + diff --git a/modules/distribution/product/src/main/business-processes/epr/SubscriptionCallbackService.epr b/modules/distribution/product/src/main/business-processes/epr/SubscriptionCallbackService.epr new file mode 100644 index 0000000000..f66981bd90 --- /dev/null +++ b/modules/distribution/product/src/main/business-processes/epr/SubscriptionCallbackService.epr @@ -0,0 +1,17 @@ + + https://localhost:8243/services/WorkflowCallbackService + + SInvokeEPR + + + + + admin + admin + + + diff --git a/modules/distribution/product/src/main/business-processes/epr/SubscriptionService.epr b/modules/distribution/product/src/main/business-processes/epr/SubscriptionService.epr new file mode 100644 index 0000000000..093d35a804 --- /dev/null +++ b/modules/distribution/product/src/main/business-processes/epr/SubscriptionService.epr @@ -0,0 +1,17 @@ + + http://localhost:9765/services/SubscriptionService/ + + SInvokeEPR + + + + + admin + admin + + + diff --git a/modules/distribution/product/src/main/business-processes/epr/UserSignupProcess.epr b/modules/distribution/product/src/main/business-processes/epr/UserSignupProcess.epr new file mode 100644 index 0000000000..951d325b68 --- /dev/null +++ b/modules/distribution/product/src/main/business-processes/epr/UserSignupProcess.epr @@ -0,0 +1,18 @@ + + https://localhost:8243/services/WorkflowCallbackService + + SInvokeEPR + + + + + admin + admin + + + + diff --git a/modules/distribution/product/src/main/business-processes/epr/UserSignupService.epr b/modules/distribution/product/src/main/business-processes/epr/UserSignupService.epr new file mode 100644 index 0000000000..8785a7ce84 --- /dev/null +++ b/modules/distribution/product/src/main/business-processes/epr/UserSignupService.epr @@ -0,0 +1,18 @@ + + http://localhost:9765/services/UserApprovalService + + SInvokeEPR + + + + + admin + admin + + + + diff --git a/modules/distribution/product/src/main/business-processes/subscription-creation/BPEL/SubscriptionApprovalWorkFlowProcess_1.0.0.zip b/modules/distribution/product/src/main/business-processes/subscription-creation/BPEL/SubscriptionApprovalWorkFlowProcess_1.0.0.zip new file mode 100644 index 0000000000..3452d45f82 Binary files /dev/null and b/modules/distribution/product/src/main/business-processes/subscription-creation/BPEL/SubscriptionApprovalWorkFlowProcess_1.0.0.zip differ diff --git a/modules/distribution/product/src/main/business-processes/subscription-creation/HumanTask/SubscriptionsApprovalTask-1.0.0.zip b/modules/distribution/product/src/main/business-processes/subscription-creation/HumanTask/SubscriptionsApprovalTask-1.0.0.zip new file mode 100644 index 0000000000..542d9b7eb9 Binary files /dev/null and b/modules/distribution/product/src/main/business-processes/subscription-creation/HumanTask/SubscriptionsApprovalTask-1.0.0.zip differ diff --git a/modules/distribution/product/src/main/business-processes/user-signup/BPEL/UserSignupApprovalProcess_1.0.0.zip b/modules/distribution/product/src/main/business-processes/user-signup/BPEL/UserSignupApprovalProcess_1.0.0.zip new file mode 100644 index 0000000000..f4011cbce3 Binary files /dev/null and b/modules/distribution/product/src/main/business-processes/user-signup/BPEL/UserSignupApprovalProcess_1.0.0.zip differ diff --git a/modules/distribution/product/src/main/business-processes/user-signup/HumanTask/UserApprovalTask-1.0.0.zip b/modules/distribution/product/src/main/business-processes/user-signup/HumanTask/UserApprovalTask-1.0.0.zip new file mode 100644 index 0000000000..782be65413 Binary files /dev/null and b/modules/distribution/product/src/main/business-processes/user-signup/HumanTask/UserApprovalTask-1.0.0.zip differ diff --git a/modules/distribution/product/src/main/conf/axis2.xml b/modules/distribution/product/src/main/conf/axis2.xml new file mode 100644 index 0000000000..cdb19b33e4 --- /dev/null +++ b/modules/distribution/product/src/main/conf/axis2.xml @@ -0,0 +1,931 @@ + + + + + + + + + + + true + + true + + + false + + false + + + false + + work/mtom + + 4000 + + + false + + + inmemory + + + + + services + + + axis2services + + + axis2modules + + + WSO2 AM 1.7.0 + WSO2 AM 1.7.0 + + + + false + + + + + + + false + + + true + + + 30000 + + + repository/deployment/server/synapse-configs + + . + + . + + localhost + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 8280 + true + + + org.wso2.carbon.transport.nhttp.api.PassThroughNHttpGetProcessor + + + + + + + + + + + + 8243 + true + + + org.wso2.carbon.transport.nhttp.api.PassThroughNHttpGetProcessor + + + repository/resources/security/wso2carbon.jks + JKS + wso2carbon + wso2carbon + + + + + repository/resources/security/client-truststore.jks + JKS + wso2carbon + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/axis2.xml_NHTTP b/modules/distribution/product/src/main/conf/axis2.xml_NHTTP new file mode 100644 index 0000000000..5be21e6fa1 --- /dev/null +++ b/modules/distribution/product/src/main/conf/axis2.xml_NHTTP @@ -0,0 +1,920 @@ + + + + + + + + + + + true + + true + + + false + + false + + + false + + work/mtom + + 4000 + + + false + + + inmemory + + + + + services + + + axis2services + + + axis2modules + + + WSO2 AM 1.4.1 + WSO2 AM 1.4.1 + + + + false + + + + + + + false + + + true + + + 30000 + + + repository/deployment/server/synapse-configs + + . + + . + + localhost + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 8280 + true + true + + + org.wso2.carbon.transport.nhttp.api.NHttpGetProcessor + + + + + + + + + + + + + 8243 + true + + + + org.wso2.carbon.transport.nhttp.api.NHttpGetProcessor + true + + + repository/resources/security/wso2carbon.jks + JKS + wso2carbon + wso2carbon + + + + + repository/resources/security/client-truststore.jks + JKS + wso2carbon + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/axis2.xml_PT b/modules/distribution/product/src/main/conf/axis2.xml_PT new file mode 100644 index 0000000000..277521f65d --- /dev/null +++ b/modules/distribution/product/src/main/conf/axis2.xml_PT @@ -0,0 +1,918 @@ + + + + + + + + + + + true + + true + + + false + + false + + + false + + work/mtom + + 4000 + + + false + + + inmemory + + + + + services + + + axis2services + + + axis2modules + + + WSO2 AM 1.4.1 + WSO2 AM 1.4.1 + + + + false + + + + + + + false + + + true + + + 30000 + + + repository/deployment/server/synapse-configs + + . + + . + + localhost + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 8280 + true + + + org.wso2.carbon.transport.nhttp.api.PassThroughNHttpGetProcessor + + + + + + + + + + + + 8243 + true--> + + + org.wso2.carbon.transport.nhttp.api.PassThroughNHttpGetProcessor + + + repository/resources/security/wso2carbon.jks + JKS + wso2carbon + wso2carbon + + + + + repository/resources/security/client-truststore.jks + JKS + wso2carbon + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/axis2_blocking_client.xml b/modules/distribution/product/src/main/conf/axis2_blocking_client.xml new file mode 100644 index 0000000000..bc5af5ff8b --- /dev/null +++ b/modules/distribution/product/src/main/conf/axis2_blocking_client.xml @@ -0,0 +1,438 @@ + + + + + + + true + false + false + false + + + + + + 30000 + + + + false + + + + + + false + + admin + axis2 + + + + + + + + + + + + + + + + + + + + + + services + rest + + + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 8200 + + + + + + + + + + + + + + + + + + + > + + + + + + + + + + + + HTTP/1.1 + chunked + true + 200 + + + + + + HTTP/1.1 + chunked + true + 200 + + + + + + smtp.gmail.com + 587 + true + true + synapse.demo.0 + mailpassword + synapse.demo.0@gmail.com + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/carbon.xml b/modules/distribution/product/src/main/conf/carbon.xml new file mode 100644 index 0000000000..f21b2b6894 --- /dev/null +++ b/modules/distribution/product/src/main/conf/carbon.xml @@ -0,0 +1,640 @@ + + + + + + + + + WSO2 API Manager + + + 1.7.0 + + AM + + + + + + + + + local:/${carbon.context}/services/ + + + + + + + APIManager + + + + + + + + org.wso2.carbon + + + / + + + + + + 15 + + + + + + + + + 0 + + + + + 9999 + + 11111 + + + + + + 10389 + + 8000 + + + + + + 5672 + + 8672 + + + + + + 10500 + + + + + + + org.wso2.carbon.tomcat.jndi.CarbonJavaURLContextFactory + + + + + + + + + + + + java + + + + + + + + + + false + + + false + + + 600 + + + false + + + false + + + + + ${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/wso2carbon.jks + + JKS + + wso2carbon + + wso2carbon + + wso2carbon + + + + + + ${carbon.home}/repository/resources/security/client-truststore.jks + + JKS + + wso2carbon + + + + + + + + + + + + + + + + + + + UserManager + + + false + + + org.apache.rahas.impl.FSBasedRetiredTokenPersister + ${carbon.home}/repository/resources/security/tokenstore + 500 + + + + + + ${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 + + + + + + + + + + + + + + + + + + + ${require.carbon.servlet} + + + + + true + + + + + + + default repository + ${p2.repo.url} + + + + + + + + false + + + + + + true + + diff --git a/modules/distribution/product/src/main/conf/cipher-text.properties b/modules/distribution/product/src/main/conf/cipher-text.properties new file mode 100644 index 0000000000..5c72b08e91 --- /dev/null +++ b/modules/distribution/product/src/main/conf/cipher-text.properties @@ -0,0 +1,23 @@ +# +# 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. +# + +#aliases=esb +# +## configuration per each plaintext +#esb.secret=M6U74dMVvRm4XFMczki2qZ6CsTvnUuRTjSditlACR5vTISSMI7F/mCTVJGOGdKJjij+VWVhBtmAOkElyvR9TwlUECnZ1o5DNsTK6l8je+9amc/ziTQLP3Q1tzm/Ex1pzHsG6jPGGrv3O0B9pZTfYFqRvlcNhM7Ve3WvA3ibs4Yk= +#esb.secret.alias=wso2carbon +#esb.secret.keystore=identity +# diff --git a/modules/distribution/product/src/main/conf/claim-config.xml b/modules/distribution/product/src/main/conf/claim-config.xml new file mode 100644 index 0000000000..37d12ae0f3 --- /dev/null +++ b/modules/distribution/product/src/main/conf/claim-config.xml @@ -0,0 +1,901 @@ + + + + + + http://wso2.org/claims/givenname + First Name + givenName + First Name + + 1 + + + + http://wso2.org/claims/lastname + Last Name + sn + Last Name + + 2 + + + + http://wso2.org/claims/organization + Organization + organizationName + Organization + 3 + + + + http://wso2.org/claims/streetaddress + Address + streetAddress + Address + 4 + + + + http://wso2.org/claims/country + Country + country + Country + 5 + + + + http://wso2.org/claims/emailaddress + Email + mail + Email Address + + 6 + + ^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$ + + + http://wso2.org/claims/telephone + Telephone + telephoneNumber + Telephone + 7 + + + + http://wso2.org/claims/mobile + Mobile + mobile + Mobile + 8 + + + + http://wso2.org/claims/im + IM + im + IM + 9 + + + + http://wso2.org/claims/url + URL + url + URL + 10 + + + + http://wso2.org/claims/gender + Gender + gender + Gender + + + http://wso2.org/claims/title + Title + title + Title + + + http://wso2.org/claims/role + Role + role + Role + + + + + http://wso2.org/claims/postalcode + Postal Code + postalcode + Postal Code + + + http://wso2.org/claims/locality + Locality + localityName + Locality + + + http://wso2.org/claims/region + Region + http://wso2.org/claims/region + Region + + + http://wso2.org/claims/dob + Birth Date + dateOfBirth + Birth Date + + + http://wso2.org/claims/nickname + Nick Name + nickName + Nick Name + + + http://wso2.org/claims/stateorprovince + State + stateOrProvinceName + State + + + http://wso2.org/claims/otherphone + Other Phone + otherPhone + Other Phone + + + http://wso2.org/claims/fullname + Full Name + cn + Full Name + + + + + http://wso2.org/claims/primaryChallengeQuestion + Primary Challenge Question + + title + Primary Challenge Question + + + http://wso2.org/claims/challengeQuestionUris + Challenge Question + + stateOrProvinceName + Challenge Question + + + + http://wso2.org/claims/oneTimePassword + One Time Password + + postalcode + One Time Password + + + http://wso2.org/claims/passwordTimestamp + Password Time Stamp + + nickName + Password Time Stamp + + + http://wso2.org/claims/accountStatus + Account Locked + + otherPhone + Account Locked + + + + http://wso2.org/claims/challengeQuestion1 + Challenge Question1 + + gender + Challenge Question1 + + + + http://wso2.org/claims/challengeQuestion2 + Challenge Question2 + + localityName + Challenge Question2 + + + + + + + http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname + First Name + givenName + First Name + + + + + http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nickname + Nick Name + nickName + Nick Name + + + http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname + Last Name + sn + Last Name + + + + + http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress + Email + mail + Email Address + + + ^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$ + + + http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth + DOB + dateOfBirth + Date of Birth + + + http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender + Gender + gender + Gender + + + http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country + Country + country + Country + + + + http://schemas.xmlsoap.org/ws/2005/05/identity/claims/streetaddress + Street Address + streetAddress + Street Address + + + http://schemas.xmlsoap.org/ws/2005/05/identity/claims/homephone + Home Phone + homePhone + Home Phone + + + + http://schemas.xmlsoap.org/ws/2005/05/identity/claims/otherphone + Other Phone + otherPhone + Other Phone + + + http://schemas.xmlsoap.org/ws/2005/05/identity/claims/mobile + Mobile + mobile + Mobile + + + http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality + Locality + localityName + Locality + + + http://schemas.xmlsoap.org/ws/2005/05/identity/claims/stateorprovince + State + stateOrProvinceName + State + + + http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode + Postalcode + postalCode + Postalcode + + + + http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier + privatePersonalIdentifier + PPID + + + + + + + + nickname + First Name + nickName + First Name + + 1 + + + + fullname + Full Name + cn + Full Name + 2 + + + + + email + Email + mail + Email Address + 3 + + + ^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$ + + + country + Country + country + Country + 5 + + + + timezone + Time Zone + timeZone + Time Zone + 9 + + + + dob + DOB + dateOfBirth + Date of Birth + 6 + + + + postcode + Postalcode + postalCode + Postalcode + 4 + + + + gender + Gender + gender + Gender + 8 + + + + language + Language + prefferedLanguage + Language + 7 + + + + + + + http://axschema.org/namePerson/first + First Name + cn + First Name + + + + + http://axschema.org/namePerson/last + Last Name + sn + Last Name + + + + + http://axschema.org/contact/email + Email + mail + Email Address + + + ^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$ + + + http://axschema.org/contact/country/home + Country + country + Country + + + + http://axschema.org/pref/timezone + Time Zone + timeZone + Time Zone + + + http://axschema.org/birthDate + DOB + dateOfBirth + Date of Birth + + + + http://axschema.org/contact/postalCode/home + Postalcode + postalCode + Postalcode + + + + http://axschema.org/person/gender + Gender + gender + Gender + + + + http://axschema.org/pref/language + Language + prefferedLanguage + Language + + + + + + urn:scim:schemas:core:1.0:id + Id + scimId + Id + + 1 + + + + urn:scim:schemas:core:1.0:externalId + External Id + externalId + External Id + + 1 + + + + urn:scim:schemas:core:1.0:meta.created + Meta - Created + createdDate + Meta - Created + + 1 + + + + urn:scim:schemas:core:1.0:meta.lastModified + Meta - Last Modified + lastModifiedDate + Meta - Last Modified + + 1 + + + + urn:scim:schemas:core:1.0:meta.location + Meta - Location + location + Meta - Location + + 1 + + + + urn:scim:schemas:core:1.0:userName + User Name + uid + User Name + 2 + + + + + urn:scim:schemas:core:1.0:name.givenName + Name - Given Name + givenName + Given Name + + 1 + + + + urn:scim:schemas:core:1.0:name.familyName + Name - Family Name + sn + Family Name + 2 + + + + + urn:scim:schemas:core:1.0:name.formatted + Name - Formatted Name + formattedName + Formatted Name + 2 + + + + + urn:scim:schemas:core:1.0:name.middleName + Name - Middle Name + middleName + Middle Name + 2 + + + + + urn:scim:schemas:core:1.0:name.honorificPrefix + Name - Honoric Prefix + honoricPrefix + Honoric Prefix + 2 + + + + + urn:scim:schemas:core:1.0:name.honorificSuffix + Name - Honoric Suffix + honoricSuffix + Honoric Suffix + 2 + + + + + urn:scim:schemas:core:1.0:displayName + Display Name + displayName + Display Name + 2 + + + + + urn:scim:schemas:core:1.0:nickName + Nick Name + nickName + Nick Name + 2 + + + + + urn:scim:schemas:core:1.0:profileUrl + Profile URL + url + Profile URL + 2 + + + + + urn:scim:schemas:core:1.0:title + Title + title + Title + 2 + + + + + urn:scim:schemas:core:1.0:userType + User Type + userType + User Type + 2 + + + + + urn:scim:schemas:core:1.0:preferredLanguage + Preferred Language + preferredLanguage + Preferred Language + 2 + + + + + urn:scim:schemas:core:1.0:local + Local + local + Local + 2 + + + + + urn:scim:schemas:core:1.0:timeZone + Time Zone + timeZone + Time Zone + 2 + + + + + urn:scim:schemas:core:1.0:active + Active + active + Active + 2 + + + + + urn:scim:schemas:core:1.0:emails + Emails + mail + Email Addresses + 3 + + + ^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$ + + + urn:scim:schemas:core:1.0:emails.work + Emails - Work Email + workEmail + Work Email + 5 + + + + urn:scim:schemas:core:1.0:emails.home + Emails - Home Email + homeEmail + Home Email + 5 + + + + urn:scim:schemas:core:1.0:emails.other + Emails - Other Email + otherEmail + Other Email + 5 + + + + urn:scim:schemas:core:1.0:phoneNumbers + Phone Numbers + phoneNumbers + Phone Numbers + 3 + + + ^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$ + + + urn:scim:schemas:core:1.0:phoneNumbers.mobile + Phone Numbers - Mobile Number + mobile + Mobile Number + 5 + + + + urn:scim:schemas:core:1.0:phoneNumbers.home + Phone Numbers - Home Phone Number + homePhone + Home Phone + 5 + + + + urn:scim:schemas:core:1.0:phoneNumbers.work + Phone Numbers - Work Phone Number + workPhone + Work Phone + 5 + + + + urn:scim:schemas:core:1.0:phoneNumbers.fax + Phone Numbers - Fax Number + fax + Fax Number + 5 + + + + urn:scim:schemas:core:1.0:phoneNumbers.pager + Phone Numbers - Pager Number + pager + Pager Number + 5 + + + + urn:scim:schemas:core:1.0:phoneNumbers.other + Phone Numbers - Other + otherPhoneNumber + Other Phone Number + 5 + + + + urn:scim:schemas:core:1.0:ims + IMS + im + IM + 5 + + + + urn:scim:schemas:core:1.0:ims.gtalk + IM - Gtalk + imGtalk + IM - Gtalk + 5 + + + + urn:scim:schemas:core:1.0:ims.skype + IM - Skype + imSkype + IM - Skype + 5 + + + + urn:scim:schemas:core:1.0:photos + Photo + photos + Photo + 5 + + + + urn:scim:schemas:core:1.0:photos.photo + Photo + photoUrl + Photo + 5 + + + + urn:scim:schemas:core:1.0:photos.thumbnail + Photo - Thumbnail + thumbnail + Photo - Thumbnail + 5 + + + + urn:scim:schemas:core:1.0:addresses + Address + addresses + Address + 5 + + + + urn:scim:schemas:core:1.0:addresses.formatted + Address - Formatted + formattedAddress + Address - Formatted + 5 + + + + urn:scim:schemas:core:1.0:addresses.streetAddress + Address - Street + streetAddress + Address - Street + 5 + + + + urn:scim:schemas:core:1.0:addresses.locality + Address - Locality + localityAddress + Address - Locality + 5 + + + + urn:scim:schemas:core:1.0:addresses.region + Address - Region + region + Address - Region + 5 + + + + urn:scim:schemas:core:1.0:addresses.postalCode + Address - Postal Code + postalCode + Address - Postal Code + 5 + + + + urn:scim:schemas:core:1.0:addresses.country + Address - Country + country + Address - Country + 5 + + + + urn:scim:schemas:core:1.0:groups + Groups + groups + Groups + 5 + + + + urn:scim:schemas:core:1.0:entitlements + Entitlements + entitlements + Entitlements + 5 + + + + urn:scim:schemas:core:1.0:roles + Roles + roles + Roles + 5 + + + + urn:scim:schemas:core:1.0:x509Certificates + X509Certificates + x509Certificates + X509Certificates + 5 + + + + + diff --git a/modules/distribution/product/src/main/conf/cloud-services-desc.xml b/modules/distribution/product/src/main/conf/cloud-services-desc.xml new file mode 100644 index 0000000000..f66b05cf3e --- /dev/null +++ b/modules/distribution/product/src/main/conf/cloud-services-desc.xml @@ -0,0 +1,16 @@ + + + + + + AM + + https://am.cloud.wso2.com + API Manager in the cloud. + + + diff --git a/modules/distribution/product/src/main/conf/datasources.properties b/modules/distribution/product/src/main/conf/datasources.properties new file mode 100644 index 0000000000..144586f51b --- /dev/null +++ b/modules/distribution/product/src/main/conf/datasources.properties @@ -0,0 +1,55 @@ +# +# 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. +# + +################################################################################ +## DataSources Configuration +################################################################################ +#synapse.datasources=lookupds,reportds +#synapse.datasources.icFactory=com.sun.jndi.rmi.registry.RegistryContextFactory +#synapse.datasources.providerPort=2199 +## If following property is present , then assumes that there is an external JNDI provider and will not start a RMI registry +##synapse.datasources.providerUrl=rmi://localhost:2199 +# +#synapse.datasources.lookupds.registry=Memory +#synapse.datasources.lookupds.type=BasicDataSource +#synapse.datasources.lookupds.driverClassName=org.apache.derby.jdbc.ClientDriver +#synapse.datasources.lookupds.url=jdbc:derby://localhost:1527/lookupdb;create=false +## Optionally you can specifiy a specific password provider implementation which overrides any globally configured provider +#synapse.datasources.lookupds.secretProvider=org.apache.synapse.commons.security.secret.handler.SharedSecretCallbackHandler +#synapse.datasources.lookupds.username=esb +## Depending on the password provider used, you may have to use an encrypted password here! +#synapse.datasources.lookupds.password=esb +#synapse.datasources.lookupds.dsName=lookupdb +#synapse.datasources.lookupds.maxActive=100 +#synapse.datasources.lookupds.maxIdle=20 +#synapse.datasources.lookupds.maxWait=10000 +# +#synapse.datasources.reportds.registry=JNDI +#synapse.datasources.reportds.type=PerUserPoolDataSource +#synapse.datasources.reportds.cpdsadapter.factory=org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS +#synapse.datasources.reportds.cpdsadapter.className=org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS +#synapse.datasources.reportds.cpdsadapter.name=cpds +#synapse.datasources.reportds.dsName=reportdb +#synapse.datasources.reportds.driverClassName=org.apache.derby.jdbc.ClientDriver +#synapse.datasources.reportds.url=jdbc:derby://localhost:1527/reportdb;create=false +## Optionally you can specifiy a specific password provider implementation which overrides any globally configured provider +#synapse.datasources.reportds.secretProvider=org.apache.synapse.commons.security.secret.handler.SharedSecretCallbackHandler +#synapse.datasources.reportds.username=esb +## Depending on the password provider used, you may have to use an encrypted password here! +#synapse.datasources.reportds.password=esb +#synapse.datasources.reportds.maxActive=100 +#synapse.datasources.reportds.maxIdle=20 +#synapse.datasources.reportds.maxWait=10000 \ No newline at end of file diff --git a/modules/distribution/product/src/main/conf/governance/lifecycle-config.xsd b/modules/distribution/product/src/main/conf/governance/lifecycle-config.xsd new file mode 100644 index 0000000000..051296b896 --- /dev/null +++ b/modules/distribution/product/src/main/conf/governance/lifecycle-config.xsd @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/governance/lifecycle-local.xsd b/modules/distribution/product/src/main/conf/governance/lifecycle-local.xsd new file mode 100644 index 0000000000..654228c247 --- /dev/null +++ b/modules/distribution/product/src/main/conf/governance/lifecycle-local.xsd @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/governance/lifecycles/configurations.xml b/modules/distribution/product/src/main/conf/governance/lifecycles/configurations.xml new file mode 100644 index 0000000000..e7db0abff1 --- /dev/null +++ b/modules/distribution/product/src/main/conf/governance/lifecycles/configurations.xml @@ -0,0 +1,128 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/governance/rxt.xsd b/modules/distribution/product/src/main/conf/governance/rxt.xsd new file mode 100644 index 0000000000..ff448c859a --- /dev/null +++ b/modules/distribution/product/src/main/conf/governance/rxt.xsd @@ -0,0 +1,169 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/governance/service-ui-config.xsd b/modules/distribution/product/src/main/conf/governance/service-ui-config.xsd new file mode 100644 index 0000000000..01ed865134 --- /dev/null +++ b/modules/distribution/product/src/main/conf/governance/service-ui-config.xsd @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/governance/services-config.xml b/modules/distribution/product/src/main/conf/governance/services-config.xml new file mode 100644 index 0000000000..1feff85602 --- /dev/null +++ b/modules/distribution/product/src/main/conf/governance/services-config.xml @@ -0,0 +1,156 @@ + + + + + + + Name + + + Namespace + + + Version + + + Scopes + + + Types + + + Description + +
    + + + + Contact TypeContact Name/Organization Name + + + Contact + + NoneTechnical OwnerBusiness Owner + + +
    + + + + WSDL URL + + + Transport Protocols + + NoneHTTPSHTTPSMTPTCPXMPPJMS + + + + Message Formats + + NoneSOAP 1.1SOAP 1.2XMLJSONHTTP-RESTCSVBINARY + + + + Message Exchange Patterns + + NoneRequest ResponseOne Way + + +
    + + + + Authentication Platform + + NoneTAM_WEBSEALXTS-WS TRUSTBuiltInWSO2 Identity Server + + + + Authentication Mechanism + + NoneOpenIDInfoCardClient CertifcatesHTTPS Basic AuthenticationIP Address FilteringWS-Security/WS-Trust TokenOthers + + + + Authorization Platform + + NoneTAM_WEBSEALXTS-WS TRUSTBuiltInWSO2 Identity Server + + + + Message Integrity + + NoneSSLWS-SecurityXML Digital SignaturesOther + + + + Message Encryption + + NoneSSLWS-SecurityXML Digital SignaturesOther + + + + Comments + +
    + + + + EnvironmentsURL + + + Endpoint + + NoneUnknownDevTestStagProd + + +
    + + + + Document TypeURLComment + + + Document Type + + + URL + + + Document Comment + + + Document Type1 + + + URL1 + + + Document Comment1 + + + Document Type2 + + + URL2 + + + Document Comment2 + +
    +
    diff --git a/modules/distribution/product/src/main/conf/governance/services-config.xsd b/modules/distribution/product/src/main/conf/governance/services-config.xsd new file mode 100644 index 0000000000..9561b82c86 --- /dev/null +++ b/modules/distribution/product/src/main/conf/governance/services-config.xsd @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/identity.xml b/modules/distribution/product/src/main/conf/identity.xml new file mode 100644 index 0000000000..220077b1a6 --- /dev/null +++ b/modules/distribution/product/src/main/conf/identity.xml @@ -0,0 +1,239 @@ + + + + + + https://localhost:9443/openidserver + + https://localhost:9443/openid/ + + false + + 7200 + + + + + jdbc/WSO2AM_DB + + + true + + + + + + ${carbon.home}/repository/resources/security/userRP.jks + + JKS + + wso2carbon + + wso2carbon + + + + ${carbon.home}/conf/keystores + + + + SelfAndManaged + CertValidate + + + + + + + + + + https://localhost:9443/oauth/request-token + https://localhost:9443/oauth/access-token + https://localhost:9443/oauth/authorize-url + + 300 + + 3600 + + 3600 + + 3600 + + 300 + + true + + + org.wso2.carbon.identity.oauth.tokenprocessor.PlainTextPersistenceProcessor + + + org.wso2.carbon.identity.oauth2.token.handlers.clientauth.BasicAuthClientAuthHandler + + + + + + token + org.wso2.carbon.identity.oauth2.authz.handlers.TokenResponseTypeHandler + + + code + org.wso2.carbon.identity.oauth2.authz.handlers.CodeResponseTypeHandler + + + + + + authorization_code + org.wso2.carbon.apimgt.keymgt.handlers.ExtendedAuthorizationCodeGrantHandler + + + password + org.wso2.carbon.apimgt.keymgt.handlers.ExtendedPasswordGrantHandler + + + refresh_token + org.wso2.carbon.identity.oauth2.token.handlers.grant.RefreshGrantHandler + + + client_credentials + org.wso2.carbon.apimgt.keymgt.handlers.ExtendedClientCredentialsGrantHandler + + + urn:ietf:params:oauth:grant-type:saml2-bearer + org.wso2.carbon.identity.oauth2.token.handlers.grant.saml.SAML2BearerGrantHandler + + + urn:ietf:params:oauth:grant-type:saml2-bearer + org.wso2.carbon.identity.oauth2.token.handlers.grant.saml.SAML2BearerGrantHandler + + + iwa:ntlm + org.wso2.carbon.identity.oauth2.token.handlers.grant.iwa.ntlm.NTLMAuthenticationGrantHandler + + + + + + + + + + + + + + + + false + + + + false + + + + + + false + org.wso2.carbon.identity.oauth2.authcontext.JWTTokenGenerator + org.wso2.carbon.identity.oauth2.authcontext.DefaultClaimsRetriever + http://wso2.org/claims + SHA256withRSA + 15 + + + + + + + + + + + + + + gtalk + talk.google.com + 5222 + gmail.com + multifactor1@gmail.com + wso2carbon + + + + + + https://localhost:9443/samlsso + + + + + + + true + 36000 + + + true + + + true + ${Ports.ThriftEntitlementReceivePort} + 10000 + + ${carbon.home}/repository/resources/security/wso2carbon.jks + wso2carbon + + + + + + false + diff --git a/modules/distribution/product/src/main/conf/jndi.properties b/modules/distribution/product/src/main/conf/jndi.properties new file mode 100644 index 0000000000..404f464ea7 --- /dev/null +++ b/modules/distribution/product/src/main/conf/jndi.properties @@ -0,0 +1,27 @@ +# +# Copyright (c) 2011, 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. +# + +# register some connection factories +# connectionfactory.[jndiname] = [ConnectionURL] +connectionfactory.QueueConnectionFactory = amqp://admin:admin@clientID/test?brokerlist='tcp://localhost:5672' + +# register some queues in JNDI using the form +# queue.[jndiName] = [physicalName] +queue.MyQueue = example.MyQueue + +# register some topics in JNDI using the form +# topic.[jndiName] = [physicalName] +topic.MyTopic = example.MyTopic diff --git a/modules/distribution/product/src/main/conf/log4j.properties b/modules/distribution/product/src/main/conf/log4j.properties new file mode 100644 index 0000000000..1ed0ab8bd4 --- /dev/null +++ b/modules/distribution/product/src/main/conf/log4j.properties @@ -0,0 +1,177 @@ +# +# 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.category.org.apache.synapse=INFO +log4j.category.org.apache.synapse.transport=INFO +log4j.category.org.apache.axis2=INFO +log4j.category.org.apache.axis2.transport=INFO +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 + +# 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 + +# The console appender is used to display general information at console +log4j.appender.CARBON_CONSOLE=org.wso2.carbon.logging.appenders.CarbonConsoleAppender +log4j.appender.CARBON_CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CARBON_CONSOLE.layout.ConversionPattern=[%d{ISO8601}] %5p - %c{1} %m%n + +# 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-apigw-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-apigw-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.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.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-apigw-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.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 + +# LOGEVENT is set to be a LogEventAppender using a PatternLayout to send logs to LOGEVENT +log4j.appender.LOGEVENT=org.wso2.carbon.logging.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 + + +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 + +# LOGEVENT is set to be a LogEventAppender using a PatternLayout to send logs to LOGEVENT +log4j.appender.LOGEVENT=org.wso2.carbon.logging.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,%H,%I,%Stacktrace +log4j.appender.LOGEVENT.userName=admin +log4j.appender.LOGEVENT.password=admin + +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 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 + diff --git a/modules/distribution/product/src/main/conf/master-datasources.xml b/modules/distribution/product/src/main/conf/master-datasources.xml new file mode 100644 index 0000000000..ecd9379f20 --- /dev/null +++ b/modules/distribution/product/src/main/conf/master-datasources.xml @@ -0,0 +1,111 @@ + + + + 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 + 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 + false + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + + + WSO2AM_STATS_DB + The datasource used for getting statistics to API Manager + + jdbc/WSO2AM_STATS_DB + + + + jdbc:h2:;AUTO_SERVER=TRUE + wso2carbon + wso2carbon + false + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/nhttp.properties b/modules/distribution/product/src/main/conf/nhttp.properties new file mode 100644 index 0000000000..c64037036d --- /dev/null +++ b/modules/distribution/product/src/main/conf/nhttp.properties @@ -0,0 +1,43 @@ +# +# 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/) diff --git a/modules/distribution/product/src/main/conf/passthru-http.properties b/modules/distribution/product/src/main/conf/passthru-http.properties new file mode 100644 index 0000000000..8f2dd8d1a8 --- /dev/null +++ b/modules/distribution/product/src/main/conf/passthru-http.properties @@ -0,0 +1,49 @@ +# +# 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/) + diff --git a/modules/distribution/product/src/main/conf/registry.xml b/modules/distribution/product/src/main/conf/registry.xml new file mode 100644 index 0000000000..fb3e7a32cf --- /dev/null +++ b/modules/distribution/product/src/main/conf/registry.xml @@ -0,0 +1,328 @@ + + + + + + wso2registry + false + true + / + + + + + jdbc/WSO2CarbonDB + + + + + + + .* + + + + + + + + .* + + + + + + + + true + + /trunk/schemas/ + + + /trunk/wsdls/ + + + /trunk/policies/ + + + + application/wsdl+xml + + + + + + + application/wsdl+xml + application/xsd+xml + 50 + true + + 3 + + /trunk/schemas/ + + + /trunk/wsdls/ + + + application/vnd.wso2.governance-archive + + + + + + + + 1.0.0-SNAPSHOT + true + + dev + qa + live + + + application/vnd.wso2-service+xml + + + + + + + + application/vnd.wso2-service+xml + + + + + + + + + /_system/governance/event/topics/registry/notifications/.* + + + + + + + + + Created + Tested + Deployed + + + application/vnd.wso2-smart-link + + + + + + + + /trunk/policies/ + + + application/policy+xml + + + + + + + + true + + /trunk/schemas/ + + + application/x-xsd+xml + + + + + + + + application/vnd.wso2-hyperlink + + + + + + + application/vnd.wso2.endpoint + + /trunk/endpoints/ + + + + + + + + application/vnd.wso2-uri+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/product/src/main/conf/rule-component.conf b/modules/distribution/product/src/main/conf/rule-component.conf new file mode 100644 index 0000000000..432cb8b955 --- /dev/null +++ b/modules/distribution/product/src/main/conf/rule-component.conf @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/modules/distribution/product/src/main/conf/synapse-configs/default/api/_AuthorizeAPI_.xml b/modules/distribution/product/src/main/conf/synapse-configs/default/api/_AuthorizeAPI_.xml new file mode 100644 index 0000000000..0b132aa264 --- /dev/null +++ b/modules/distribution/product/src/main/conf/synapse-configs/default/api/_AuthorizeAPI_.xml @@ -0,0 +1,14 @@ + + + + + +
    + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/synapse-configs/default/api/_RevokeAPI_.xml b/modules/distribution/product/src/main/conf/synapse-configs/default/api/_RevokeAPI_.xml new file mode 100644 index 0000000000..bbed5c05e0 --- /dev/null +++ b/modules/distribution/product/src/main/conf/synapse-configs/default/api/_RevokeAPI_.xml @@ -0,0 +1,17 @@ + + + + + +
    + + + + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/synapse-configs/default/api/_TokenAPI_.xml b/modules/distribution/product/src/main/conf/synapse-configs/default/api/_TokenAPI_.xml new file mode 100644 index 0000000000..c49f3dd958 --- /dev/null +++ b/modules/distribution/product/src/main/conf/synapse-configs/default/api/_TokenAPI_.xml @@ -0,0 +1,17 @@ + + + + + +
    + + + + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/synapse-configs/default/proxy-services/WorkflowCallbackService.xml b/modules/distribution/product/src/main/conf/synapse-configs/default/proxy-services/WorkflowCallbackService.xml new file mode 100644 index 0000000000..722d81b059 --- /dev/null +++ b/modules/distribution/product/src/main/conf/synapse-configs/default/proxy-services/WorkflowCallbackService.xml @@ -0,0 +1,145 @@ + + + + + + + + +
    + + + + + + + + + + + WorkflowCallbackService + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/synapse-configs/default/registry.xml b/modules/distribution/product/src/main/conf/synapse-configs/default/registry.xml new file mode 100644 index 0000000000..b19a4c8939 --- /dev/null +++ b/modules/distribution/product/src/main/conf/synapse-configs/default/registry.xml @@ -0,0 +1,25 @@ + + + + + + + 15000 + diff --git a/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_auth_failure_handler_.xml b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_auth_failure_handler_.xml new file mode 100644 index 0000000000..44d5d0edf0 --- /dev/null +++ b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_auth_failure_handler_.xml @@ -0,0 +1,4 @@ + + + + diff --git a/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_build_.xml b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_build_.xml new file mode 100644 index 0000000000..64e8fe390d --- /dev/null +++ b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_build_.xml @@ -0,0 +1,26 @@ + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_production_key_error_.xml b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_production_key_error_.xml new file mode 100644 index 0000000000..771994193f --- /dev/null +++ b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_production_key_error_.xml @@ -0,0 +1,24 @@ + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_resource_mismatch_handler_.xml b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_resource_mismatch_handler_.xml new file mode 100644 index 0000000000..f88ce6b6d3 --- /dev/null +++ b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_resource_mismatch_handler_.xml @@ -0,0 +1,24 @@ + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_sandbox_key_error_.xml b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_sandbox_key_error_.xml new file mode 100644 index 0000000000..12906f2e01 --- /dev/null +++ b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_sandbox_key_error_.xml @@ -0,0 +1,24 @@ + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_throttle_out_handler_.xml b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_throttle_out_handler_.xml new file mode 100644 index 0000000000..e2a601c38a --- /dev/null +++ b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_throttle_out_handler_.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_token_fault_.xml b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_token_fault_.xml new file mode 100644 index 0000000000..4b06ba43d7 --- /dev/null +++ b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/_token_fault_.xml @@ -0,0 +1,39 @@ + + + + + + + + + + $1 + Status report + Runtime Error + $2 + + + + + + + + + + + + + + + + +
    + + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/fault.xml b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/fault.xml new file mode 100644 index 0000000000..df0ac95b9b --- /dev/null +++ b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/fault.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + $1 + Status report + Runtime Error + $2 + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/main.xml b/modules/distribution/product/src/main/conf/synapse-configs/default/sequences/main.xml new file mode 100644 index 0000000000..a1fd716787 --- /dev/null +++ b/modules/distribution/product/src/main/conf/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. + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/distribution/product/src/main/conf/synapse-configs/default/synapse.xml b/modules/distribution/product/src/main/conf/synapse-configs/default/synapse.xml new file mode 100644 index 0000000000..d7f60ec4bf --- /dev/null +++ b/modules/distribution/product/src/main/conf/synapse-configs/default/synapse.xml @@ -0,0 +1,25 @@ + + + + + + + + diff --git a/modules/distribution/product/src/main/conf/synapse.properties b/modules/distribution/product/src/main/conf/synapse.properties new file mode 100644 index 0000000000..617f2b36d6 --- /dev/null +++ b/modules/distribution/product/src/main/conf/synapse.properties @@ -0,0 +1,41 @@ +# +# 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. +# + +#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 + +synapse.sal.endpoints.sesssion.timeout.default=600000 +synapse.global_timeout_interval=120000 +#In memory statistics cleaning state +statistics.clean.enable=false + +# Dependency tracking Synapse observer +# Comment out to disable dependency management +synapse.observers=org.wso2.carbon.mediation.dependency.mgt.DependencyTracker + +# 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 +#provides custom xpath function for securevault +synapse.xpath.func.extensions=org.wso2.carbon.mediation.security.vault.xpath.SecureVaultLookupXPathFunctionProvider \ No newline at end of file diff --git a/modules/distribution/product/src/main/conf/tenant-axis2.xml b/modules/distribution/product/src/main/conf/tenant-axis2.xml new file mode 100644 index 0000000000..5806e8abd3 --- /dev/null +++ b/modules/distribution/product/src/main/conf/tenant-axis2.xml @@ -0,0 +1,354 @@ + + + + + + + + + true + true + optional + + + false + + + false + + + + true + + + + + + false + + + false + + + axis2services + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/product/src/main/statistics/API_Manager_Analytics/analytics/am_stats_analyzer b/modules/distribution/product/src/main/statistics/API_Manager_Analytics/analytics/am_stats_analyzer new file mode 100644 index 0000000000..e1af884f1d --- /dev/null +++ b/modules/distribution/product/src/main/statistics/API_Manager_Analytics/analytics/am_stats_analyzer @@ -0,0 +1,97 @@ +CREATE EXTERNAL TABLE IF NOT EXISTS APIRequestData (key STRING,api STRING, + api_version STRING,consumerKey STRING,userId STRING, + context STRING,version STRING, request INT, requestTime BIGINT, resourcePath STRING, method STRING, hostName STRING, apiPublisher STRING) STORED BY + 'org.apache.hadoop.hive.cassandra.CassandraStorageHandler' WITH SERDEPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2BAM_CASSANDRA_DATASOURCE', + "cassandra.cf.name" = "org_wso2_apimgt_statistics_request", + "cassandra.columns.mapping" = ":key,payload_api, payload_api_version,payload_consumerKey,payload_userId,payload_context,payload_version, payload_request, payload_requestTime, payload_resourcePath, payload_method,payload_hostName,payload_apiPublisher" ); + + +CREATE EXTERNAL TABLE IF NOT EXISTS APIRequestSummaryData (api STRING, api_version STRING, version STRING, apiPublisher STRING, + consumerKey STRING,userId STRING,context STRING, max_request_time BIGINT, + total_request_count INT, hostName STRING,year SMALLINT,month SMALLINT,day SMALLINT, time STRING) STORED BY + 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.primary.key.fields'='api,api_version,version,apiPublisher,consumerKey,userId,context,hostName,time', + 'hive.jdbc.table.create.query' = 'CREATE TABLE API_REQUEST_SUMMARY ( api VARCHAR(100), api_version VARCHAR(100), version VARCHAR(100), + apiPublisher VARCHAR(100),consumerKey VARCHAR(100),userId VARCHAR(100), context VARCHAR(100),max_request_time BIGINT, total_request_count INT, hostName VARCHAR(100), year SMALLINT, month SMALLINT, day SMALLINT, time VARCHAR(30),PRIMARY KEY(api,api_version,apiPublisher,consumerKey,userId,context,hostName,time))' ); + +insert overwrite table APIRequestSummaryData select api, api_version,version, apiPublisher, COALESCE(consumerKey,''),userId,context,max(requestTime) as max_request_time,sum(request) as total_request_count,hostName, year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as year, month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as month,day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as day,concat(substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16),':00') as time from APIRequestData group by api,api_version,version,apiPublisher,consumerKey,userId,context,hostName,year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )), month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),hour(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),minute(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16); + + +CREATE EXTERNAL TABLE IF NOT EXISTS APIVersionUsageSummaryData ( api STRING, version STRING, apiPublisher STRING,context STRING,total_request_count INT, hostName STRING,year SMALLINT,month SMALLINT,day SMALLINT, time STRING) STORED BY 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.primary.key.fields'='api,version,apiPublisher,context,hostName,time', + 'hive.jdbc.table.create.query' = 'CREATE TABLE API_VERSION_USAGE_SUMMARY ( api VARCHAR(100), version VARCHAR(100),apiPublisher VARCHAR(100),context VARCHAR(100), + total_request_count INT,hostName VARCHAR(100), year SMALLINT, month SMALLINT, day SMALLINT, time VARCHAR(30), PRIMARY KEY(api,version,apiPublisher,context,hostName,time))' ); + + +insert overwrite table APIVersionUsageSummaryData select api,version,apiPublisher,context,sum(request) as total_request_count,hostName, year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as year, month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as month,day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as day,concat(substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16),':00') as time from APIRequestData group by api,version,apiPublisher,context,hostName,year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )), month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),hour(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),minute(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16); + + +CREATE EXTERNAL TABLE IF NOT EXISTS APIResourcePathUsageSummaryData ( api STRING, version STRING,apiPublisher STRING,consumerKey STRING,resourcePath STRING,context STRING, method STRING, total_request_count INT ,hostName STRING,year SMALLINT,month SMALLINT,day SMALLINT, time STRING) STORED BY 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES + ( 'wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.primary.key.fields'='api,version,apiPublisher,context,method,hostName,time', + 'hive.jdbc.table.create.query' = 'CREATE TABLE API_Resource_USAGE_SUMMARY ( api VARCHAR(100), version VARCHAR(100),apiPublisher VARCHAR(100) , consumerKey VARCHAR(100),resourcePath VARCHAR(100) ,context VARCHAR(100), + method VARCHAR(100), total_request_count INT, hostName VARCHAR(100), year SMALLINT, month SMALLINT, day SMALLINT, time VARCHAR(30), PRIMARY KEY(api,version,apiPublisher,consumerKey,context,method,time))' ); + + + insert overwrite table APIResourcePathUsageSummaryData select api,version,apiPublisher,consumerKey,resourcePath,context,method,sum(request),hostName as total_request_count, year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as year, month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as month,day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as day,concat(substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16),':00') as time from APIRequestData group by api,version,apiPublisher,consumerKey,resourcePath,context,method,hostName,year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )), month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),hour(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),minute(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16); + + + +CREATE EXTERNAL TABLE IF NOT EXISTS APIResponseData (key STRING, + api_version STRING,apiPublisher STRING,context STRING,serviceTime BIGINT, + response INT,hostName STRING,responseTime BIGINT) STORED BY + 'org.apache.hadoop.hive.cassandra.CassandraStorageHandler' WITH SERDEPROPERTIES ('wso2.carbon.datasource.name'='WSO2BAM_CASSANDRA_DATASOURCE', + "cassandra.cf.name" = "org_wso2_apimgt_statistics_response", + "cassandra.columns.mapping" = ":key,payload_api_version,payload_apiPublisher,payload_context,payload_serviceTime,payload_response,payload_hostName,payload_responseTime" ); + + +CREATE EXTERNAL TABLE IF NOT EXISTS APIResponseSummaryData (api_version STRING,apiPublisher STRING,context STRING,serviceTime INT,total_response_count INT,hostName STRING,year SMALLINT,month SMALLINT,day SMALLINT, time STRING) STORED BY + 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.primary.key.fields'='api_version,apiPublisher,context,hostName,time', + 'hive.jdbc.table.create.query' = 'CREATE TABLE API_RESPONSE_SUMMARY ( api_version VARCHAR(100),apiPublisher VARCHAR(100), + context VARCHAR(100),serviceTime INT,total_response_count INT,hostName VARCHAR(100), year SMALLINT, month SMALLINT, day SMALLINT, time VARCHAR(30), PRIMARY KEY(api_version,apiPublisher,context,hostName,time))' ); + + +insert overwrite table APIResponseSummaryData select api_version,apiPublisher,context, avg(serviceTime) as avg_service_time,sum(response) as total_response_count, hostName, year(from_unixtime(cast(responseTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as year, month(from_unixtime(cast(responseTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as month,day(from_unixtime(cast(responseTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as day,concat(substring(from_unixtime(cast(responseTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16),':00') as time from APIResponseData group by api_version,apiPublisher,context,hostName,year(from_unixtime(cast(responseTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )), month(from_unixtime(cast(responseTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),day(from_unixtime(cast(responseTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),hour(from_unixtime(cast(responseTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),minute(from_unixtime(cast(responseTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),substring(from_unixtime(cast(responseTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16); + + +CREATE EXTERNAL TABLE IF NOT EXISTS APIFaultData (key STRING, + api STRING,version STRING,consumerKey STRING, apiPublisher STRING,context STRING, errorCode STRING, + errorMessage STRING, requestTime STRING, hostName STRING) STORED BY + 'org.apache.hadoop.hive.cassandra.CassandraStorageHandler' WITH SERDEPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2BAM_CASSANDRA_DATASOURCE', + "cassandra.cf.name" = "org_wso2_apimgt_statistics_fault", + "cassandra.columns.mapping" = ":key,payload_api, payload_version,payload_consumerKey ,payload_apiPublisher,payload_context,payload_errorCode,payload_errorMessage,payload_requestTime,payload_hostName" ); + + + +CREATE EXTERNAL TABLE IF NOT EXISTS APIFaultSummaryData (api STRING, version STRING,apiPublisher STRING,consumerKey STRING,context STRING, total_fault_count INT, hostName STRING, year SMALLINT,month SMALLINT,day SMALLINT, time STRING) STORED BY + 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.primary.key.fields'='api,version,apiPublisher,context,hostName,time', + 'hive.jdbc.table.create.query' = 'CREATE TABLE API_FAULT_SUMMARY ( api VARCHAR(100), version VARCHAR(100),apiPublisher VARCHAR(100),consumerKey VARCHAR(100),context VARCHAR(100), + total_fault_count INT, hostName VARCHAR(100), year SMALLINT, month SMALLINT, day SMALLINT, time VARCHAR(30), PRIMARY KEY(api,version,apiPublisher,context,hostName,time)) ' ); + +insert overwrite table APIFaultSummaryData select api,version,apiPublisher,consumerKey,context,count(errorMessage) as total_fault_count,hostName, year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as year, month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as month,day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as day,concat(substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16),':00') as time from APIFaultData group by api,version,apiPublisher,consumerKey ,context,hostName,year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )), month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),hour(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),minute(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16); + + +CREATE EXTERNAL TABLE IF NOT EXISTS APIDestinationData (key STRING, + api STRING,version STRING,request INT,apiPublisher STRING,context STRING, destination STRING, + requestTime STRING, hostName STRING) STORED BY + 'org.apache.hadoop.hive.cassandra.CassandraStorageHandler' WITH SERDEPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2BAM_CASSANDRA_DATASOURCE', + "cassandra.cf.name" = "org_wso2_apimgt_statistics_destination", + "cassandra.columns.mapping" = ":key,payload_api, payload_version, payload_request, payload_apiPublisher,payload_context,payload_destination,payload_requestTime,payload_hostName" ); + +CREATE EXTERNAL TABLE IF NOT EXISTS APIDestinationDataSummaryData (api STRING, version STRING,apiPublisher STRING,context STRING, destination STRING, total_request_count INT, hostName STRING, year SMALLINT,month SMALLINT,day SMALLINT, time STRING) STORED BY + 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.primary.key.fields'='api,version,apiPublisher,context,destination,hostName,time', + 'hive.jdbc.table.create.query' = 'CREATE TABLE API_DESTINATION_SUMMARY ( api VARCHAR(100), version VARCHAR(100),apiPublisher VARCHAR(100),context VARCHAR(100),destination VARCHAR(100), + total_request_count INT, hostName VARCHAR(100), year SMALLINT, month SMALLINT, day SMALLINT, time VARCHAR(30), PRIMARY KEY(api,version,apiPublisher,context,destination,hostName,time))' ); + +insert overwrite table APIDestinationDataSummaryData select api,version,apiPublisher, context,destination, sum(request) as total_request_count,hostName, year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as year, month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as month,day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as day,concat(substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16),':00') as time from APIDestinationData group by api,version,apiPublisher,context,destination,hostName,year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )), month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),hour(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),minute(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16); + + diff --git a/modules/distribution/product/src/main/statistics/API_Manager_Analytics/analytics/analyzers.properties b/modules/distribution/product/src/main/statistics/API_Manager_Analytics/analytics/analyzers.properties new file mode 100644 index 0000000000..c1a4ef344d --- /dev/null +++ b/modules/distribution/product/src/main/statistics/API_Manager_Analytics/analytics/analyzers.properties @@ -0,0 +1,4 @@ +analyzers.scripts=am +analyzers.scripts.am.filename=am_stats_analyzer +analyzers.scripts.am.description=API Manager statistics analyzer +analyzers.scripts.am.cron=0 0/2 * * * ? diff --git a/modules/distribution/product/src/main/statistics/API_Manager_Analytics/streamDefn/faultStreamDefn b/modules/distribution/product/src/main/statistics/API_Manager_Analytics/streamDefn/faultStreamDefn new file mode 100644 index 0000000000..53b29c311a --- /dev/null +++ b/modules/distribution/product/src/main/statistics/API_Manager_Analytics/streamDefn/faultStreamDefn @@ -0,0 +1,28 @@ +{ + 'name':'org.wso2.apimgt.statistics.fault', + 'version':'1.0.0', + 'nickName': 'API Manager Fault Data', + 'description': 'Fault Data', + 'metaData':[ + {'name':'clientType','type':'STRING'} + ], + 'payloadData':[ + {'name':'consumerKey','type':'STRING'}, + {'name':'context','type':'STRING'}, + {'name':'api_version','type':'STRING'}, + {'name':'api','type':'STRING'}, + {'name':'resourcePath','type':'STRING'}, + {'name':'method','type':'STRING'}, + {'name':'version','type':'STRING'}, + {'name':'errorCode','type':'STRING'}, + {'name':'errorMessage','type':'STRING'}, + {'name':'requestTime','type':'STRING'}, + {'name':'userId','type':'STRING'}, + {'name':'tenantDomain','type':'STRING'}, + {'name':'hostName','type':'STRING'}, + {'name':'apiPublisher','type':'STRING'}, + {'name':'applicationName','type':'STRING'}, + {'name':'applicationId','type':'STRING'} + ] + + } diff --git a/modules/distribution/product/src/main/statistics/API_Manager_Analytics/streamDefn/requestStreamDefn b/modules/distribution/product/src/main/statistics/API_Manager_Analytics/streamDefn/requestStreamDefn new file mode 100644 index 0000000000..73cca0dd67 --- /dev/null +++ b/modules/distribution/product/src/main/statistics/API_Manager_Analytics/streamDefn/requestStreamDefn @@ -0,0 +1,26 @@ +{ + 'name':'org.wso2.apimgt.statistics.request', + 'version':'1.0.0', + 'nickName': 'API Manager Request Data', + 'description': 'Request Data', + 'metaData':[ + {'name':'clientType','type':'STRING'} + ], + 'payloadData':[ + {'name':'consumerKey','type':'STRING'}, + {'name':'context','type':'STRING'}, + {'name':'api_version','type':'STRING'}, + {'name':'api','type':'STRING'}, + {'name':'resourcePath','type':'STRING'}, + {'name':'method','type':'STRING'}, + {'name':'version','type':'STRING'}, + {'name':'request','type':'INT'}, + {'name':'requestTime','type':'LONG'}, + {'name':'userId','type':'STRING'}, + {'name':'tenantDomain','type':'STRING'}, + {'name':'hostName','type':'STRING'}, + {'name':'apiPublisher','type':'STRING'}, + {'name':'applicationName','type':'STRING'}, + {'name':'applicationId','type':'STRING'} + ] + } diff --git a/modules/distribution/product/src/main/statistics/API_Manager_Analytics/streamDefn/responseStreamDefn b/modules/distribution/product/src/main/statistics/API_Manager_Analytics/streamDefn/responseStreamDefn new file mode 100644 index 0000000000..d0947f5be0 --- /dev/null +++ b/modules/distribution/product/src/main/statistics/API_Manager_Analytics/streamDefn/responseStreamDefn @@ -0,0 +1,28 @@ +{ + 'name':'org.wso2.apimgt.statistics.response', + 'version':'1.0.0', + 'nickName': 'API Manager Reponse Data', + 'description': 'Response Data', + 'metaData':[ + {'name':'clientType','type':'STRING'} + ], + 'payloadData':[ + {'name':'consumerKey','type':'STRING'}, + {'name':'context','type':'STRING'}, + {'name':'api_version','type':'STRING'}, + {'name':'api','type':'STRING'}, + {'name':'resourcePath','type':'STRING'}, + {'name':'method','type':'STRING'}, + {'name':'version','type':'STRING'}, + {'name':'response','type':'INT'}, + {'name':'responseTime','type':'LONG'}, + {'name':'serviceTime','type':'LONG'}, + {'name':'userId','type':'STRING'}, + {'name':'tenantDomain','type':'STRING'}, + {'name':'hostName','type':'STRING'}, + {'name':'apiPublisher','type':'STRING'}, + {'name':'applicationName','type':'STRING'}, + {'name':'applicationId','type':'STRING'} + ] + + } diff --git a/modules/distribution/product/src/main/statistics/API_Manager_Analytics/streamDefn/streams.properties b/modules/distribution/product/src/main/statistics/API_Manager_Analytics/streamDefn/streams.properties new file mode 100644 index 0000000000..2a85067599 --- /dev/null +++ b/modules/distribution/product/src/main/statistics/API_Manager_Analytics/streamDefn/streams.properties @@ -0,0 +1,13 @@ +streams.definitions=defn1,defn2,defn3 +streams.definitions.defn1.filename=responseStreamDefn +streams.definitions.defn1.username=admin +streams.definitions.defn1.password=admin +streams.definitions.defn1.description=This is the datastream published from APIManager Stats Client +streams.definitions.defn2.filename=requestStreamDefn +streams.definitions.defn2.username=admin +streams.definitions.defn2.password=admin +streams.definitions.defn2.description=This is the datastream published from APIManager Stats Client +streams.definitions.defn3.filename=faultStreamDefn +streams.definitions.defn3.username=admin +streams.definitions.defn3.password=admin +streams.definitions.defn3.description=This is the datastream published from APIManager Stats Client for Faults diff --git a/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/analytics/am_stats_analyzer b/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/analytics/am_stats_analyzer new file mode 100644 index 0000000000..cf269a5320 --- /dev/null +++ b/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/analytics/am_stats_analyzer @@ -0,0 +1,97 @@ +CREATE EXTERNAL TABLE IF NOT EXISTS APIRequestData (key STRING,api STRING, + api_version STRING,consumerKey STRING,userId STRING, + context STRING,version STRING, request INT, requestTime BIGINT, resourcePath STRING, method STRING, hostName STRING, apiPublisher STRING) STORED BY + 'org.apache.hadoop.hive.cassandra.CassandraStorageHandler' WITH SERDEPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2BAM_CASSANDRA_DATASOURCE', + "cassandra.cf.name" = "org_wso2_apimgt_statistics_request", + "cassandra.columns.mapping" = ":key,payload_api, payload_api_version,payload_consumerKey,payload_userId,payload_context,payload_version, payload_request, payload_requestTime, payload_resourcePath, payload_method,payload_hostName,payload_apiPublisher" ); + + +CREATE EXTERNAL TABLE IF NOT EXISTS APIRequestSummaryData (api STRING, api_version STRING, version STRING, apiPublisher STRING, + consumerKey STRING,userId STRING,context STRING, max_request_time BIGINT, + total_request_count INT, hostName STRING,year SMALLINT,month SMALLINT,day SMALLINT, time STRING) STORED BY + 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.primary.key.fields'='api,api_version,version,apiPublisher,consumerKey,userId,context,hostName,time', + 'hive.jdbc.table.create.query' = 'CREATE TABLE API_REQUEST_SUMMARY ( api VARCHAR2(100), api_version VARCHAR2(100), version VARCHAR2(100), + apiPublisher VARCHAR2(100),consumerKey VARCHAR2(100),userId VARCHAR2(100), context VARCHAR2(100),max_request_time NUMBER, total_request_count INT, hostName VARCHAR2(100), year SMALLINT, month SMALLINT, day SMALLINT, time VARCHAR2(30),PRIMARY KEY(api,api_version,apiPublisher,consumerKey,userId,context,hostName,time))' ); + +insert overwrite table APIRequestSummaryData select api, api_version,version, apiPublisher, COALESCE(consumerKey,''),userId,context,max(requestTime) as max_request_time,sum(request) as total_request_count,hostName, year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as year, month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as month,day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as day,concat(substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16),':00') as time from APIRequestData group by api,api_version,version,apiPublisher,consumerKey,userId,context,hostName,year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )), month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),hour(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),minute(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16); + + +CREATE EXTERNAL TABLE IF NOT EXISTS APIVersionUsageSummaryData ( api STRING, version STRING, apiPublisher STRING,context STRING,total_request_count INT, hostName STRING,year SMALLINT,month SMALLINT,day SMALLINT, time STRING) STORED BY 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.primary.key.fields'='api,version,apiPublisher,context,hostName,time', + 'hive.jdbc.table.create.query' = 'CREATE TABLE API_VERSION_USAGE_SUMMARY ( api VARCHAR2(100), version VARCHAR2(100),apiPublisher VARCHAR2(100),context VARCHAR2(100), + total_request_count INT,hostName VARCHAR2(100), year SMALLINT, month SMALLINT, day SMALLINT, time VARCHAR2(30), PRIMARY KEY(api,version,apiPublisher,context,hostName,time))' ); + + +insert overwrite table APIVersionUsageSummaryData select api,version,apiPublisher,context,sum(request) as total_request_count,hostName, year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as year, month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as month,day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as day,concat(substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16),':00') as time from APIRequestData group by api,version,apiPublisher,context,hostName,year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )), month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),hour(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),minute(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16); + + +CREATE EXTERNAL TABLE IF NOT EXISTS APIResourcePathUsageSummaryData ( api STRING, version STRING,apiPublisher STRING,consumerKey STRING,resourcePath STRING,context STRING, method STRING, total_request_count INT ,hostName STRING,year SMALLINT,month SMALLINT,day SMALLINT, time STRING) STORED BY 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES + ( 'wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.primary.key.fields'='api,version,apiPublisher,context,method,hostName,time', + 'hive.jdbc.table.create.query' = 'CREATE TABLE API_Resource_USAGE_SUMMARY ( api VARCHAR(100), version VARCHAR(100),apiPublisher VARCHAR(100) , consumerKey VARCHAR(100),resourcePath VARCHAR(100) ,context VARCHAR(100), + method VARCHAR(100), total_request_count INT, hostName VARCHAR(100), year SMALLINT, month SMALLINT, day SMALLINT, time VARCHAR(30), PRIMARY KEY(api,version,apiPublisher,consumerKey,context,method,time))' ); + + + insert overwrite table APIResourcePathUsageSummaryData select api,version,apiPublisher,consumerKey,resourcePath,context,method,sum(request),hostName as total_request_count, year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as year, month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as month,day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as day,concat(substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16),':00') as time from APIRequestData group by api,version,apiPublisher,consumerKey,resourcePath,context,method,hostName,year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )), month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),hour(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),minute(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16); + + + +CREATE EXTERNAL TABLE IF NOT EXISTS APIResponseData (key STRING, + api_version STRING,apiPublisher STRING,context STRING,serviceTime BIGINT, + response INT,hostName STRING,responseTime BIGINT) STORED BY + 'org.apache.hadoop.hive.cassandra.CassandraStorageHandler' WITH SERDEPROPERTIES ('wso2.carbon.datasource.name'='WSO2BAM_CASSANDRA_DATASOURCE', + "cassandra.cf.name" = "org_wso2_apimgt_statistics_response", + "cassandra.columns.mapping" = ":key,payload_api_version,payload_apiPublisher,payload_context,payload_serviceTime,payload_response,payload_hostName,payload_responseTime" ); + + +CREATE EXTERNAL TABLE IF NOT EXISTS APIResponseSummaryData (api_version STRING,apiPublisher STRING,context STRING,serviceTime INT,total_response_count INT,hostName STRING,year SMALLINT,month SMALLINT,day SMALLINT, time STRING) STORED BY + 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.primary.key.fields'='api_version,apiPublisher,context,hostName,time', + 'hive.jdbc.table.create.query' = 'CREATE TABLE API_RESPONSE_SUMMARY ( api_version VARCHAR2(100),apiPublisher VARCHAR2(100), + context VARCHAR2(100),serviceTime INT,total_response_count INT,hostName VARCHAR2(100), year SMALLINT, month SMALLINT, day SMALLINT, time VARCHAR2(30), PRIMARY KEY(api_version,apiPublisher,context,hostName,time))' ); + + +insert overwrite table APIResponseSummaryData select api_version,apiPublisher,context, avg(serviceTime) as avg_service_time,sum(response) as total_response_count, hostName, year(from_unixtime(cast(responseTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as year, month(from_unixtime(cast(responseTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as month,day(from_unixtime(cast(responseTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as day,concat(substring(from_unixtime(cast(responseTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16),':00') as time from APIResponseData group by api_version,apiPublisher,context,hostName,year(from_unixtime(cast(responseTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )), month(from_unixtime(cast(responseTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),day(from_unixtime(cast(responseTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),hour(from_unixtime(cast(responseTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),minute(from_unixtime(cast(responseTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),substring(from_unixtime(cast(responseTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16); + + +CREATE EXTERNAL TABLE IF NOT EXISTS APIFaultData (key STRING, + api STRING,version STRING,consumerKey STRING, apiPublisher STRING,context STRING, errorCode STRING, + errorMessage STRING, requestTime STRING, hostName STRING) STORED BY + 'org.apache.hadoop.hive.cassandra.CassandraStorageHandler' WITH SERDEPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2BAM_CASSANDRA_DATASOURCE', + "cassandra.cf.name" = "org_wso2_apimgt_statistics_fault", + "cassandra.columns.mapping" = ":key,payload_api, payload_version,payload_consumerKey ,payload_apiPublisher,payload_context,payload_errorCode,payload_errorMessage,payload_requestTime,payload_hostName" ); + + + +CREATE EXTERNAL TABLE IF NOT EXISTS APIFaultSummaryData (api STRING, version STRING,apiPublisher STRING,consumerKey STRING,context STRING, total_fault_count INT, hostName STRING, year SMALLINT,month SMALLINT,day SMALLINT, time STRING) STORED BY + 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.primary.key.fields'='api,version,apiPublisher,context,hostName,time', + 'hive.jdbc.table.create.query' = 'CREATE TABLE API_FAULT_SUMMARY ( api VARCHAR(100), version VARCHAR(100),apiPublisher VARCHAR(100),consumerKey VARCHAR(100),context VARCHAR(100), + total_fault_count INT, hostName VARCHAR(100), year SMALLINT, month SMALLINT, day SMALLINT, time VARCHAR(30), PRIMARY KEY(api,version,apiPublisher,context,hostName,time)) ' ); + +insert overwrite table APIFaultSummaryData select api,version,apiPublisher,consumerKey,context,count(errorMessage) as total_fault_count,hostName, year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as year, month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as month,day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as day,concat(substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16),':00') as time from APIFaultData group by api,version,apiPublisher,consumerKey ,context,hostName,year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )), month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),hour(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),minute(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16); + + +CREATE EXTERNAL TABLE IF NOT EXISTS APIDestinationData (key STRING, + api STRING,version STRING,request INT,apiPublisher STRING,context STRING, destination STRING, + requestTime STRING, hostName STRING) STORED BY + 'org.apache.hadoop.hive.cassandra.CassandraStorageHandler' WITH SERDEPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2BAM_CASSANDRA_DATASOURCE', + "cassandra.cf.name" = "org_wso2_apimgt_statistics_destination", + "cassandra.columns.mapping" = ":key,payload_api, payload_version, payload_request, payload_apiPublisher,payload_context,payload_destination,payload_requestTime,payload_hostName" ); + +CREATE EXTERNAL TABLE IF NOT EXISTS APIDestinationDataSummaryData (api STRING, version STRING,apiPublisher STRING,context STRING, destination STRING, total_request_count INT, hostName STRING, year SMALLINT,month SMALLINT,day SMALLINT, time STRING) STORED BY + 'org.wso2.carbon.hadoop.hive.jdbc.storage.JDBCStorageHandler' TBLPROPERTIES ( 'wso2.carbon.datasource.name'='WSO2AM_STATS_DB', + 'hive.jdbc.update.on.duplicate' = 'true', + 'hive.jdbc.primary.key.fields'='api,version,apiPublisher,context,destination,hostName,time', + 'hive.jdbc.table.create.query' = 'CREATE TABLE API_DESTINATION_SUMMARY ( api VARCHAR2(100), version VARCHAR2(100),apiPublisher VARCHAR2(100),context VARCHAR2(100),destination VARCHAR2(100), + total_request_count INT, hostName VARCHAR2(100), year SMALLINT, month SMALLINT, day SMALLINT, time VARCHAR2(30), PRIMARY KEY(api,version,apiPublisher,context,destination,hostName,time))' ); + +insert overwrite table APIDestinationDataSummaryData select api,version,apiPublisher, context,destination, sum(request) as total_request_count,hostName, year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as year, month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as month,day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )) as day,concat(substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16),':00') as time from APIDestinationData group by api,version,apiPublisher,context,destination,hostName,year(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )), month(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),day(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),hour(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),minute(from_unixtime(cast(requestTime/1000 as BIGINT),'yyyy-MM-dd HH:mm:ss.SSS' )),substring(from_unixtime(cast(requestTime/1000 as BIGINT), 'yyyy-MM-dd HH:mm:ss'),0,16); + + diff --git a/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/analytics/analyzers.properties b/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/analytics/analyzers.properties new file mode 100644 index 0000000000..c1a4ef344d --- /dev/null +++ b/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/analytics/analyzers.properties @@ -0,0 +1,4 @@ +analyzers.scripts=am +analyzers.scripts.am.filename=am_stats_analyzer +analyzers.scripts.am.description=API Manager statistics analyzer +analyzers.scripts.am.cron=0 0/2 * * * ? diff --git a/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/streamDefn/faultStreamDefn b/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/streamDefn/faultStreamDefn new file mode 100644 index 0000000000..53b29c311a --- /dev/null +++ b/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/streamDefn/faultStreamDefn @@ -0,0 +1,28 @@ +{ + 'name':'org.wso2.apimgt.statistics.fault', + 'version':'1.0.0', + 'nickName': 'API Manager Fault Data', + 'description': 'Fault Data', + 'metaData':[ + {'name':'clientType','type':'STRING'} + ], + 'payloadData':[ + {'name':'consumerKey','type':'STRING'}, + {'name':'context','type':'STRING'}, + {'name':'api_version','type':'STRING'}, + {'name':'api','type':'STRING'}, + {'name':'resourcePath','type':'STRING'}, + {'name':'method','type':'STRING'}, + {'name':'version','type':'STRING'}, + {'name':'errorCode','type':'STRING'}, + {'name':'errorMessage','type':'STRING'}, + {'name':'requestTime','type':'STRING'}, + {'name':'userId','type':'STRING'}, + {'name':'tenantDomain','type':'STRING'}, + {'name':'hostName','type':'STRING'}, + {'name':'apiPublisher','type':'STRING'}, + {'name':'applicationName','type':'STRING'}, + {'name':'applicationId','type':'STRING'} + ] + + } diff --git a/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/streamDefn/requestStreamDefn b/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/streamDefn/requestStreamDefn new file mode 100644 index 0000000000..73cca0dd67 --- /dev/null +++ b/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/streamDefn/requestStreamDefn @@ -0,0 +1,26 @@ +{ + 'name':'org.wso2.apimgt.statistics.request', + 'version':'1.0.0', + 'nickName': 'API Manager Request Data', + 'description': 'Request Data', + 'metaData':[ + {'name':'clientType','type':'STRING'} + ], + 'payloadData':[ + {'name':'consumerKey','type':'STRING'}, + {'name':'context','type':'STRING'}, + {'name':'api_version','type':'STRING'}, + {'name':'api','type':'STRING'}, + {'name':'resourcePath','type':'STRING'}, + {'name':'method','type':'STRING'}, + {'name':'version','type':'STRING'}, + {'name':'request','type':'INT'}, + {'name':'requestTime','type':'LONG'}, + {'name':'userId','type':'STRING'}, + {'name':'tenantDomain','type':'STRING'}, + {'name':'hostName','type':'STRING'}, + {'name':'apiPublisher','type':'STRING'}, + {'name':'applicationName','type':'STRING'}, + {'name':'applicationId','type':'STRING'} + ] + } diff --git a/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/streamDefn/responseStreamDefn b/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/streamDefn/responseStreamDefn new file mode 100644 index 0000000000..d0947f5be0 --- /dev/null +++ b/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/streamDefn/responseStreamDefn @@ -0,0 +1,28 @@ +{ + 'name':'org.wso2.apimgt.statistics.response', + 'version':'1.0.0', + 'nickName': 'API Manager Reponse Data', + 'description': 'Response Data', + 'metaData':[ + {'name':'clientType','type':'STRING'} + ], + 'payloadData':[ + {'name':'consumerKey','type':'STRING'}, + {'name':'context','type':'STRING'}, + {'name':'api_version','type':'STRING'}, + {'name':'api','type':'STRING'}, + {'name':'resourcePath','type':'STRING'}, + {'name':'method','type':'STRING'}, + {'name':'version','type':'STRING'}, + {'name':'response','type':'INT'}, + {'name':'responseTime','type':'LONG'}, + {'name':'serviceTime','type':'LONG'}, + {'name':'userId','type':'STRING'}, + {'name':'tenantDomain','type':'STRING'}, + {'name':'hostName','type':'STRING'}, + {'name':'apiPublisher','type':'STRING'}, + {'name':'applicationName','type':'STRING'}, + {'name':'applicationId','type':'STRING'} + ] + + } diff --git a/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/streamDefn/streams.properties b/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/streamDefn/streams.properties new file mode 100644 index 0000000000..2a85067599 --- /dev/null +++ b/modules/distribution/product/src/main/statistics/API_Manager_Analytics_Oracle/streamDefn/streams.properties @@ -0,0 +1,13 @@ +streams.definitions=defn1,defn2,defn3 +streams.definitions.defn1.filename=responseStreamDefn +streams.definitions.defn1.username=admin +streams.definitions.defn1.password=admin +streams.definitions.defn1.description=This is the datastream published from APIManager Stats Client +streams.definitions.defn2.filename=requestStreamDefn +streams.definitions.defn2.username=admin +streams.definitions.defn2.password=admin +streams.definitions.defn2.description=This is the datastream published from APIManager Stats Client +streams.definitions.defn3.filename=faultStreamDefn +streams.definitions.defn3.username=admin +streams.definitions.defn3.password=admin +streams.definitions.defn3.description=This is the datastream published from APIManager Stats Client for Faults diff --git a/modules/distribution/product/src/main/statistics/build.xml b/modules/distribution/product/src/main/statistics/build.xml new file mode 100644 index 0000000000..7a52414ab9 --- /dev/null +++ b/modules/distribution/product/src/main/statistics/build.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/product/src/main/statistics/pom.xml b/modules/distribution/product/src/main/statistics/pom.xml new file mode 100644 index 0000000000..657c63180d --- /dev/null +++ b/modules/distribution/product/src/main/statistics/pom.xml @@ -0,0 +1,83 @@ + + + + + + org.wso2.am + am-parent + 1.7.0-SNAPSHOT + ../../../../../../pom.xml + + + 4.0.0 + am-toolbox + pom + WSO2 API Manager - BAM Toolbox + http://wso2.org/projects/bam/java + WSO2 API Manager BAM Toolbox + + + + Apache License Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + + + + + WSO2 Inc + http://wso2.com + + + + + + maven-clean-plugin + 2.4.1 + + + auto-clean + initialize + + clean + + + + + + maven-antrun-plugin + 1.7 + + + process-resources + + + + + + + run + + + + + + + diff --git a/modules/distribution/resources/api_templates/default_api_template.xml b/modules/distribution/resources/api_templates/default_api_template.xml new file mode 100644 index 0000000000..721a1add56 --- /dev/null +++ b/modules/distribution/resources/api_templates/default_api_template.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + 500 + Status report + Internal Server Error + Faulty invoking through default API + + + + + + +
    + + + + + + + + +
    + + + + + + 30000 + fault + + + -1 + 0 + 1.0 + 0 + + + -1 + + + + + + + + + + + + + + + diff --git a/modules/distribution/resources/api_templates/prototype_template.xml b/modules/distribution/resources/api_templates/prototype_template.xml new file mode 100644 index 0000000000..65b02ec22f --- /dev/null +++ b/modules/distribution/resources/api_templates/prototype_template.xml @@ -0,0 +1,248 @@ + + + ##################### Define the macros ###################### + + #macro ( print_if_exist $field $default) + #if($field && $field !="") + $field + #else + $default + #end + #end + + #macro ( print_list $list $default) + #if($list && $list !="" && $list.size() > 0) + #foreach($item in $list) + $item #if( $foreach.hasNext ), #end + #end + #else + $default + #end + #end + + #macro ( timeout $config) + #if( $config.get("actionSelect") == "neverTimeout" ) + ## print nothing. + #else + + #print_if_exist( $config.get("actionDuration") 30000) + #print_if_exist( $config.get("actionSelect") "fault") + + #end + +#print_list( $config.get("suspendErrorCode") -1) +#print_if_exist( $config.get("suspendDuration") 0) +#print_if_exist( $config.get("factor") 1.0) +#print_if_exist( $config.get("suspendMaxDuration") 0) + + +#print_list( $config.get("retryErroCode") -1) +#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().equalsIgnoreCase("GET")) + + #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/resources/api_templates/velocity_template.xml b/modules/distribution/resources/api_templates/velocity_template.xml new file mode 100644 index 0000000000..aa9c7df514 --- /dev/null +++ b/modules/distribution/resources/api_templates/velocity_template.xml @@ -0,0 +1,294 @@ + + +##################### Define the macros ###################### + +#macro ( print_if_exist $field $default) + #if($field && $field !="") + $field + #else + $default + #end +#end + +#macro ( print_list $list $default) + #if($list && $list !="" && $list.size() > 0) + #foreach($item in $list) + $item #if( $foreach.hasNext ), #end + #end + #else + $default + #end +#end + +#macro ( timeout $config) + #if( $config.get("actionSelect") == "neverTimeout" ) + ## print nothing. + #else + + #print_if_exist( $config.get("actionDuration") 30000) + #print_if_exist( $config.get("actionSelect") "fault") + + #end + + #print_list( $config.get("suspendErrorCode") -1) + #print_if_exist( $config.get("suspendDuration") 0) + #print_if_exist( $config.get("factor") 1.0) + #print_if_exist( $config.get("suspendMaxDuration") 0) + + + #print_list( $config.get("retryErroCode") -1) + #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) + + + + ## check and set jwt + #if($jwtIsEnabled) + + #end + ## 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/resources/migration-1.0.0_to_1.2.0/mysql.sql b/modules/distribution/resources/migration-1.0.0_to_1.2.0/mysql.sql new file mode 100644 index 0000000000..823c79b441 --- /dev/null +++ b/modules/distribution/resources/migration-1.0.0_to_1.2.0/mysql.sql @@ -0,0 +1,12 @@ +create table BACKUP (SELECT * FROM IDN_OAUTH2_ACCESS_TOKEN); +CREATE TABLE IDN_OAUTH2_ACCESS_TOKEN1 (ACCESS_TOKEN varchar(255) NOT NULL DEFAULT '',TIME_CREATED timestamp NOT NULL); +INSERT INTO IDN_OAUTH2_ACCESS_TOKEN1 select ACCESS_TOKEN, TIME_CREATED from IDN_OAUTH2_ACCESS_TOKEN AS t where TIME_CREATED IN (SELECT MAX(TIME_CREATED) AS MAXTIME FROM IDN_OAUTH2_ACCESS_TOKEN group by CONSUMER_KEY, AUTHZ_USER,TOKEN_SCOPE,TOKEN_STATE,USER_TYPE); +DELETE FROM IDN_OAUTH2_ACCESS_TOKEN WHERE ACCESS_TOKEN NOT IN (SELECT ACCESS_TOKEN FROM IDN_OAUTH2_ACCESS_TOKEN1); +DROP TABLE IDN_OAUTH2_ACCESS_TOKEN1; +DELETE FROM IDN_OAUTH2_ACCESS_TOKEN WHERE USER_TYPE IS NULL; +update IDN_OAUTH2_ACCESS_TOKEN set USER_TYPE = 'APPLICATION' WHERE USER_TYPE = 'DEVELOPER'; +update IDN_OAUTH2_ACCESS_TOKEN set USER_TYPE = 'APPLICATION_USER' where USER_TYPE = 'APPLICATION'; +ALTER TABLE IDN_OAUTH2_ACCESS_TOKEN ADD(TOKEN_STATE_ID varchar(256) default 'NONE'); +CREATE INDEX IDX_AT_CK_AU ON IDN_OAUTH2_ACCESS_TOKEN(CONSUMER_KEY, AUTHZ_USER, TOKEN_STATE, USER_TYPE); +ALTER TABLE IDN_OAUTH2_ACCESS_TOKEN ADD CONSTRAINT CON_APP_KEY UNIQUE (CONSUMER_KEY, AUTHZ_USER,TOKEN_SCOPE,TOKEN_STATE,TOKEN_STATE_ID); +DELETE FROM IDN_OAUTH2_ACCESS_TOKEN WHERE USER_TYPE IS NULL; diff --git a/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/build.xml b/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/build.xml new file mode 100644 index 0000000000..5d6efe3168 --- /dev/null +++ b/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/build.xml @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/rxt/api.rxt b/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/rxt/api.rxt new file mode 100644 index 0000000000..1c6e093a07 --- /dev/null +++ b/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/rxt/api.rxt @@ -0,0 +1,143 @@ + + + /apimgt/applicationdata/provider/@{overview_provider}/@{overview_name}/@{overview_version}/api + overview_name + + + + + + + + + + + + + + + + + Provider + + + Name + + + Context + + + Version + + + Description + + + Endpoint URL + + + Sandbox URL + + + WSDL + + + WADL + + + Thumbnail + + + Is Latest + + false + true + + + + Tier + + Gold + Silver + Other + + + + Status + + CREATED + PUBLISHED + RETIRED + DEPRECATED + BLOCKED + + + + Technical Owner + + + Technical Owner Email + + + Business Owner + + + Business Owner Email + +
    + + + URL Pattern + HTTP Verb + Auth Type + + + URL Pattern0 + + + HTTP Verb0 + + + Auth Type0 + + + URL Pattern1 + + + HTTP Verb1 + + + Auth Type1 + + + URL Pattern2 + + + HTTP Verb2 + + + Auth Type2 + + + URL Pattern3 + + + HTTP Verb3 + + + Auth Type3 + + + URL Pattern4 + + + HTTP Verb4 + + + Auth Type4 + +
    +
    + +
    + diff --git a/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/src/org/wso2/carbon/registry/migration/Main.java b/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/src/org/wso2/carbon/registry/migration/Main.java new file mode 100644 index 0000000000..82d58c8eed --- /dev/null +++ b/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/src/org/wso2/carbon/registry/migration/Main.java @@ -0,0 +1,135 @@ +/* +* Copyright (c) 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.carbon.registry.migration; + +import org.apache.axis2.context.ConfigurationContext; +import org.apache.axis2.context.ConfigurationContextFactory; +import org.wso2.carbon.apimgt.api.*; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.governance.api.generic.GenericArtifactManager; +import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact; +import org.wso2.carbon.governance.api.util.GovernanceUtils; +import org.wso2.carbon.registry.core.Registry; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import org.wso2.carbon.registry.core.session.UserRegistry; + + +import org.wso2.carbon.registry.migration.utils.APIDao; +import org.wso2.carbon.registry.migration.utils.DBUtils; +import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient; +import org.wso2.carbon.registry.migration.utils.CommandHandler; +import org.wso2.carbon.apimgt.api.model.*; + +import java.io.File; +import java.sql.SQLException; +import java.util.LinkedHashSet; +import java.util.Set; + + +public class Main { + private static Registry registry; + + + public static void main(String[] args) { + CommandHandler.setInputs(args); + try { + String trustStore = System.getProperty("carbon.home") + File.separator + "repository" + File.separator + "resources" + File.separator + "security" + File.separator + "wso2carbon.jks"; + System.setProperty("javax.net.ssl.trustStore", trustStore); + System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon"); + System.setProperty("javax.net.ssl.trustStoreType", "JKS"); + System.setProperty("carbon.repo.write.mode", "true"); + + ConfigurationContext cc = ConfigurationContextFactory.createConfigurationContextFromFileSystem(System.getProperty("carbon.home") + "repository/deployment/client", System.getProperty("carbon.home") + "repository/conf/axis2/axis2_client.xml"); + registry = new WSRegistryServiceClient(CommandHandler.getServiceURL(), CommandHandler.getUsername(), CommandHandler.getPassword(), cc); + DBUtils.initializeDB(); + Main.migrate(); + System.out.println("Finished API data migration process."); + System.exit(0); + } catch (RegistryException e) { + System.out.println("Error while connecting to registry." + e); + return; + } catch (Exception e) { + System.out.println("Error while migrating data." + e); + return; + } + + } + + private static int migrate() throws RegistryException, SQLException, APIManagementException { + + Registry re = GovernanceUtils.getGovernanceUserRegistry(registry, CommandHandler.getUsername()); + GenericArtifactManager manager = new GenericArtifactManager(re, "api"); + GovernanceUtils.loadGovernanceArtifacts((UserRegistry) re); + GenericArtifact[] artifacts = manager.getAllGenericArtifacts(); + for (GenericArtifact artifact : artifacts) { + String[] attributes = artifact.getAttributes("uriTemplates_entry"); + if (attributes != null) { + String apiName; + artifact.removeAttribute("uriTemplates_entry"); + Set uriTemplates = new LinkedHashSet(); + for (int i = 0; i < attributes.length; i++) { + String attribute = attributes[i]; + String[] atd = attribute.split(":"); + String[] httpVerbs = atd[0].split("\\s"); + if (httpVerbs.length > 0) { + for (int j = 0; j < httpVerbs.length; j++) { + URITemplate template = new URITemplate(); + artifact.setAttribute("uriTemplates_urlPattern" + j, atd[1]); + template.setUriTemplate(atd[1]); + artifact.setAttribute("uriTemplates_httpVerb" + j, httpVerbs[j]); + template.setHTTPVerb(httpVerbs[j]); + artifact.setAttribute("uriTemplates_authType" + j, "Any"); + template.setAuthType("Any"); + uriTemplates.add(template); + } + + } else { + URITemplate template = new URITemplate(); + artifact.setAttribute("uriTemplates_urlPattern" + i, atd[1]); + template.setUriTemplate(atd[1]); + artifact.setAttribute("uriTemplates_httpVerb" + i, atd[0]); + template.setHTTPVerb(atd[0]); + artifact.setAttribute("uriTemplates_authType" + i, "Any"); + template.setAuthType("Any"); + uriTemplates.add(template); + } + } + manager.updateGenericArtifact(artifact); + String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER); + apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME); + String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION); + APIIdentifier apiId = new APIIdentifier(providerName, apiName, apiVersion); + int id = APIDao.getAPIID(apiId, DBUtils.getConnection()); + if (!APIDao.isURLMappingsExists(id, DBUtils.getConnection())) { + APIDao.addURLTemplates(id, uriTemplates, DBUtils.getConnection()); + } + System.out.println("Successfully migrate the API resources data for the API :" + apiName); + + + } else { + System.out.println("Already the API resources data has been migrated."); + + } + } + return -1; + + } + + +} diff --git a/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/src/org/wso2/carbon/registry/migration/utils/APIDao.java b/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/src/org/wso2/carbon/registry/migration/utils/APIDao.java new file mode 100644 index 0000000000..645beb1f42 --- /dev/null +++ b/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/src/org/wso2/carbon/registry/migration/utils/APIDao.java @@ -0,0 +1,131 @@ +/* +* Copyright (c) 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.carbon.registry.migration.utils; + +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; +import org.wso2.carbon.apimgt.api.model.URITemplate; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Iterator; +import java.util.Set; + + +public class APIDao { + + public static int getAPIID(APIIdentifier apiId, Connection connection) + throws APIManagementException { + PreparedStatement prepStmt = null; + ResultSet rs = null; + int id = -1; + String getAPIQuery = "SELECT " + + "API.API_ID FROM AM_API API" + + " WHERE " + + "API.API_PROVIDER = ?" + + "AND API.API_NAME = ?" + + "AND API.API_VERSION = ?"; + + try { + prepStmt = connection.prepareStatement(getAPIQuery); + prepStmt.setString(1, apiId.getProviderName()); + prepStmt.setString(2, apiId.getApiName()); + prepStmt.setString(3, apiId.getVersion()); + rs = prepStmt.executeQuery(); + if (rs.next()) { + id = rs.getInt("API_ID"); + } + if (id == -1) { + String msg = "Unable to find the API: " + apiId + " in the database"; + System.out.println(msg); + throw new APIManagementException(msg); + } + } catch (SQLException e) { + e.printStackTrace(); + } finally { + DBUtils.closeAllConnections(prepStmt, null, rs); + } + return id; + } + + + public static void addURLTemplates(int apiId, Set uriTemps, Connection connection) throws APIManagementException { + if(apiId == -1){ + //application addition has failed + return; + } + + PreparedStatement prepStmt = null; + String query = "INSERT INTO AM_API_URL_MAPPING (API_ID,HTTP_METHOD,AUTH_SCHEME,URL_PATTERN) VALUES (?,?,?,?)"; + try { + //connection = APIMgtDBUtil.getConnection(); + prepStmt = connection.prepareStatement(query); + + Iterator uriTemplateIterator = uriTemps.iterator(); + URITemplate uriTemplate; + for(;uriTemplateIterator.hasNext();){ + uriTemplate = uriTemplateIterator.next(); + prepStmt.setInt(1,apiId); + prepStmt.setString(2,uriTemplate.getHTTPVerb()); + prepStmt.setString(3,uriTemplate.getAuthType()); + prepStmt.setString(4,uriTemplate.getUriTemplate()); + prepStmt.addBatch(); + } + prepStmt.executeBatch(); + prepStmt.clearBatch(); + + + } catch (SQLException e) { + System.out.println("Error while adding URL template(s) to the database "+ e); + } + } + + + public static boolean isURLMappingsExists(int apiId, Connection connection) + throws APIManagementException { + boolean isExists = false; + + if (apiId == -1) { + //Avoid data migrating + return true; + } + ResultSet rs = null; + PreparedStatement prepStmt = null; + + String query = "SELECT API_ID FROM AM_API_URL_MAPPING WHERE API_ID = ?"; + try { + prepStmt = connection.prepareStatement(query); + prepStmt.setInt(1, apiId); + + rs = prepStmt.executeQuery(); + + while (rs.next()) { + isExists = true; + } + + } catch (SQLException e) { + System.out.println("Error when executing the SQL query to check the API URI Mappings has stored to database"+e); + } finally { + DBUtils.closeAllConnections(prepStmt, connection, rs); + } + return isExists; + } +} diff --git a/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/src/org/wso2/carbon/registry/migration/utils/CommandHandler.java b/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/src/org/wso2/carbon/registry/migration/utils/CommandHandler.java new file mode 100644 index 0000000000..0c68b36c4d --- /dev/null +++ b/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/src/org/wso2/carbon/registry/migration/utils/CommandHandler.java @@ -0,0 +1,155 @@ +/* +* Copyright (c) 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.carbon.registry.migration.utils; + +import java.util.HashMap; +import java.util.Map; + +public class CommandHandler { + + private static final Map inputs = new HashMap(); + + public static boolean setInputs(String[] arguments) { + + if (arguments.length == 0) { + printMessage(); + return false; + } + if (arguments.length == 1 && arguments[0].equals("--help")) { + printMessage(); + return false; + } + + // now loop through the arguments list to capture the options + for (int i = 0; i < arguments.length; i++) { + if (arguments[i].equals("-h")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Hostname of the registry is missing"); + } + inputs.put("-h", arguments[++i]); + + } else if (arguments[i].equals("-p")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Port of the registry is missing"); + } + inputs.put("-p", arguments[++i]); + + } else if (arguments[i].equals("-u")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Username of the admin is missing"); + } + inputs.put("-u", arguments[++i]); + + } else if (arguments[i].equals("-pw")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Password of the admin is missing"); + } + inputs.put("-pw", arguments[++i]); + }else if (arguments[i].equals("-dpw")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Password of the admin is missing"); + } + inputs.put("-dpw", arguments[++i]); + }else if (arguments[i].equals("-du")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Password of the admin is missing"); + } + inputs.put("-du", arguments[++i]); + }else if (arguments[i].equals("-durl")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Password of the admin is missing"); + } + inputs.put("-durl", arguments[++i]); + } else if (arguments[i].equals("-dr")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Password of the admin is missing"); + } + inputs.put("-dr", arguments[++i]); + } else if (arguments[i].equals("-cr")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Context root of the service is missing"); + } + inputs.put("-cr", arguments[++i]); + } + } + + return true; + } + + + private static void printMessage() { + System.out.println("Usage: migration-client "); + System.out.println("Valid options are:"); + System.out.println("\t-h :\t(Required) The hostname/ip of the registry to login."); + System.out.println("\t-p :\t(Required) The port of the registry to login."); + System.out.println("\t-u :\t(Required) The user name of the registry login."); + System.out.println("\t-pw:\t(Required) The password of the registry login."); + System.out.println(); + System.out.println("Example to migrate a registry running on localhost on default values"); + System.out.println("\te.g: migration-client -h localhost -p 9443 -u admin -pw admin"); + } + + public static String getRegistryURL() { + String contextRoot = inputs.get("-cr"); + + if (contextRoot == null) { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/registry/"; + } else { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/" + contextRoot + "/registry/"; + } + } + + public static String getHost() { + return inputs.get("-h"); + } + + public static String getServiceURL() { + String contextRoot = inputs.get("-cr"); + + if (contextRoot == null) { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/services/"; + } else { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/" + contextRoot + "/services/"; + } + } + + public static String getUsername() { + return inputs.get("-u"); + } + + public static String getPassword() { + return inputs.get("-pw"); + } + + public static String getDBUrl() { + return inputs.get("-durl"); + } + + public static String getDBDriver() { + return inputs.get("-dr"); + } + + public static String getDBPassword() { + return inputs.get("-dpw"); + } + + public static String getDBUsername() { + return inputs.get("-du"); + } +} + diff --git a/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/src/org/wso2/carbon/registry/migration/utils/DBUtils.java b/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/src/org/wso2/carbon/registry/migration/utils/DBUtils.java new file mode 100644 index 0000000000..ab4f04dcf7 --- /dev/null +++ b/modules/distribution/resources/migration-1.2.0_to_1.3.0/api_rxt_migration_client/src/org/wso2/carbon/registry/migration/utils/DBUtils.java @@ -0,0 +1,139 @@ +/* +* Copyright (c) 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.carbon.registry.migration.utils; + +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.apache.commons.dbcp.BasicDataSource; + +public class DBUtils { + static ApiMgtDAO apiMgtDAO; + private static volatile DataSource dataSource = null; + + public static void initializeDB() + throws APIManagementException, ClassNotFoundException, IllegalAccessException, + InstantiationException { + + String dbUrl = CommandHandler.getDBUrl(); + String driver = CommandHandler.getDBDriver(); + String username = CommandHandler.getDBUsername(); + String password = CommandHandler.getDBPassword(); + if (dbUrl == null || driver == null || username == null || password == null) { + System.out.println("Required DB configuration parameters unspecified. So API Store and API Publisher " + + "will not work as expected."); + } + + BasicDataSource basicDataSource = new BasicDataSource(); + basicDataSource.setDriverClassName(driver); + basicDataSource.setUrl(dbUrl); + basicDataSource.setUsername(username); + basicDataSource.setPassword(password); + dataSource = basicDataSource; + + } + + /** + * Utility method to get a new database connection + * + * @return Connection + * @throws java.sql.SQLException if failed to get Connection + */ + public static Connection getConnection() throws SQLException { + if (dataSource != null) { + return dataSource.getConnection(); + } + throw new SQLException("Data source is not configured properly."); + } + + /** + * Utility method to close the connection streams. + * + * @param preparedStatement PreparedStatement + * @param connection Connection + * @param resultSet ResultSet + */ + public static void closeAllConnections(PreparedStatement preparedStatement, + Connection connection, + ResultSet resultSet) { + closeConnection(connection); + closeResultSet(resultSet); + closeStatement(preparedStatement); + } + + /** + * Close Connection + * + * @param dbConnection Connection + */ + private static void closeConnection(Connection dbConnection) { + if (dbConnection != null) { + try { + dbConnection.close(); + } catch (SQLException e) { + e.printStackTrace(); + // log.warn("Database error. Could not close database connection. Continuing with " + + // "others. - " + e.getMessage(), e); + } + } + } + + /** + * Close ResultSet + * + * @param resultSet ResultSet + */ + private static void closeResultSet(ResultSet resultSet) { + if (resultSet != null) { + try { + resultSet.close(); + } catch (SQLException e) { + e.printStackTrace(); + //System.out.println("Database error. Could not close ResultSet - " + e.getMessage(), e); + } + } + + } + + /** + * Close PreparedStatement + * + * @param preparedStatement PreparedStatement + */ + private static void closeStatement(PreparedStatement preparedStatement) { + if (preparedStatement != null) { + try { + preparedStatement.close(); + } catch (SQLException e) { + e.printStackTrace(); + //log.warn("Database error. Could not close PreparedStatement. Continuing with" + + // " others. - " + e.getMessage(), e); + } + } + + } + + +} diff --git a/modules/distribution/resources/migration-1.2.0_to_1.3.0/h2.sql b/modules/distribution/resources/migration-1.2.0_to_1.3.0/h2.sql new file mode 100644 index 0000000000..e05d6eaecb --- /dev/null +++ b/modules/distribution/resources/migration-1.2.0_to_1.3.0/h2.sql @@ -0,0 +1,9 @@ +ALTER TABLE `AM_APPLICATION` ADD COLUMN `APPLICATION_TIER` VARCHAR(50) DEFAULT 'Unlimited' AFTER `SUBSCRIBER_ID`; +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, + PRIMARY KEY(URL_MAPPING_ID) +); diff --git a/modules/distribution/resources/migration-1.2.0_to_1.3.0/mysql.sql b/modules/distribution/resources/migration-1.2.0_to_1.3.0/mysql.sql new file mode 100644 index 0000000000..ae2e3b3243 --- /dev/null +++ b/modules/distribution/resources/migration-1.2.0_to_1.3.0/mysql.sql @@ -0,0 +1,9 @@ +ALTER TABLE `AM_APPLICATION` ADD COLUMN `APPLICATION_TIER` VARCHAR(50) DEFAULT 'Unlimited' AFTER `SUBSCRIBER_ID`; +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, + PRIMARY KEY (URL_MAPPING_ID) +)ENGINE INNODB; diff --git a/modules/distribution/resources/migration-1.2.0_to_1.3.0/oracle.sql b/modules/distribution/resources/migration-1.2.0_to_1.3.0/oracle.sql new file mode 100644 index 0000000000..a5396607e6 --- /dev/null +++ b/modules/distribution/resources/migration-1.2.0_to_1.3.0/oracle.sql @@ -0,0 +1,24 @@ +ALTER TABLE AM_APPLICATION ADD APPLICATION_TIER VARCHAR2(50) DEFAULT 'Unlimited'; + +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, + 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; +/ diff --git a/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/build.xml b/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/build.xml new file mode 100644 index 0000000000..a532ca44c3 --- /dev/null +++ b/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/build.xml @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/Main.java b/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/Main.java new file mode 100644 index 0000000000..a92292d599 --- /dev/null +++ b/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/Main.java @@ -0,0 +1,132 @@ +/* +* Copyright (c) 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.carbon.registry.migration; + +import org.apache.axis2.context.ConfigurationContext; +import org.apache.axis2.context.ConfigurationContextFactory; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; +import org.wso2.carbon.apimgt.api.model.Subscriber; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.governance.api.generic.GenericArtifactManager; +import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact; +import org.wso2.carbon.governance.api.util.GovernanceUtils; +import org.wso2.carbon.registry.core.Comment; +import org.wso2.carbon.registry.core.Registry; +import org.wso2.carbon.registry.core.RegistryConstants; +import org.wso2.carbon.registry.core.config.RegistryContext; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import org.wso2.carbon.registry.core.session.UserRegistry; +import org.wso2.carbon.registry.core.utils.RegistryUtils; +import org.wso2.carbon.registry.migration.utils.*; +import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient; + +import java.io.File; +import java.sql.SQLException; +import java.util.*; + + +public class Main { + private static Registry registry; + + + public static void main(String[] args) { + CommandHandler.setInputs(args); + try { + String trustStore = System.getProperty("carbon.home") + File.separator + "repository" + File.separator + + "resources" + File.separator + "security" + File.separator + "wso2carbon.jks"; + System.setProperty("javax.net.ssl.trustStore", trustStore); + System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon"); + System.setProperty("javax.net.ssl.trustStoreType", "JKS"); + System.setProperty("carbon.repo.write.mode", "true"); + + ConfigurationContext cc = ConfigurationContextFactory.createConfigurationContextFromFileSystem + (System.getProperty("carbon.home") + "repository/deployment/client", System.getProperty("carbon.home") + + "repository/conf/axis2/axis2_client.xml"); + registry = new WSRegistryServiceClient(CommandHandler.getServiceURL(), CommandHandler.getUsername(), + CommandHandler.getPassword(), cc); + DBUtils.initializeDB(); + Main.migrate(); + System.out.println("Finished API data migration process."); + System.exit(0); + } catch (RegistryException e) { + System.out.println("Error while connecting to registry." + e); + } catch (Exception e) { + System.out.println("Error while migrating data." + e); + } + + } + + private static void migrate() throws RegistryException, SQLException, APIManagementException { + Registry re = GovernanceUtils.getGovernanceUserRegistry(registry, CommandHandler.getUsername()); + GenericArtifactManager manager = new GenericArtifactManager(re, "api"); + GovernanceUtils.loadGovernanceArtifacts((UserRegistry) re); + GenericArtifact[] artifacts = manager.getAllGenericArtifacts(); + + Set subscribers = new HashSet(); + List apiCommentList = new ArrayList(); + subscribers = ApiDAO.getAllSubscribers(DBUtils.getConnection()); + + for (GenericArtifact artifact : artifacts) { + String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER); + String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME); + String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION); + APIIdentifier identifier = new APIIdentifier(providerName, apiName, apiVersion); + + String path = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion() + + RegistryConstants.PATH_SEPARATOR + APIConstants.API_KEY; + + String resourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), + RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + path); + + int apiId = ApiDAO.getAPIID(identifier, DBUtils.getConnection()); + Comment[] comments = registry.getComments(resourcePath); + + /* + Comments cannot be added to database while we are iterating in the following loop. Because, we need to sort the + comments from the comment_id first. + */ + for (Comment comment : comments) { + APIComment apiComment = new APIComment(apiId, comment.getCommentID(), comment); + apiCommentList.add(apiComment); + } + + /* + APIs can be rated without subscribing to an API. Therefore, we need to get the all subscribers in Store. + Taking the Subscribers of APIs would not enough. + */ + for (Subscriber subscriber : subscribers) { + int rating = registry.getRating(resourcePath, subscriber.getName()); + if (rating != 0) { + ApiDAO.addRating(apiId, DBUtils.getConnection(), rating, subscriber.getId()); + } + } + } + + //First sort the comments by comment_id and add to database + Collections.sort(apiCommentList, new APICommentIdComparator()); + for (APIComment comment : apiCommentList) { + ApiDAO.addComment(DBUtils.getConnection(), comment.getCommentId(), comment.getCommentText(), comment.getCommentedUser(), + comment.getCreatedDate(), comment.getApiId()); + } + } + +} diff --git a/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/utils/APIComment.java b/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/utils/APIComment.java new file mode 100644 index 0000000000..10fddc4fb0 --- /dev/null +++ b/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/utils/APIComment.java @@ -0,0 +1,61 @@ +/* +* Copyright (c) 2005-2010, 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.carbon.registry.migration.utils; + +import org.wso2.carbon.registry.core.Comment; + +import java.util.Date; + +public class APIComment extends Comment { + int apiId ; + long commentId; + String commentText; + String commentedUser; + Date createdTime; + + + public APIComment (int apiId, long commentId, Comment comment) { + this.apiId = apiId; + this.commentId = commentId; + this.commentText = comment.getDescription(); + this.commentedUser = comment.getUser(); + this.createdTime = comment.getCreatedTime(); + } + + public long getCommentId(){ + return this.commentId; + } + + public int getApiId() { + return this.apiId; + } + + public String getCommentText() { + return this.commentText; + } + + public String getCommentedUser() { + return this.commentedUser; + } + + public Date getCreatedDate() { + return this.createdTime; + } + +} diff --git a/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/utils/APICommentIdComparator.java b/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/utils/APICommentIdComparator.java new file mode 100644 index 0000000000..84b5763624 --- /dev/null +++ b/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/utils/APICommentIdComparator.java @@ -0,0 +1,28 @@ +/* +* Copyright (c) 2005-2010, 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.carbon.registry.migration.utils; + +import java.util.Comparator; + +public class APICommentIdComparator implements Comparator { + + public int compare(APIComment o1, APIComment o2) { + return o1.commentId > o2.commentId ? 1 : (o1.commentId < o2.commentId ? -1 : 0); + } +} diff --git a/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/utils/ApiDAO.java b/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/utils/ApiDAO.java new file mode 100644 index 0000000000..16363cc13e --- /dev/null +++ b/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/utils/ApiDAO.java @@ -0,0 +1,173 @@ +/* +* Copyright (c) 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.carbon.registry.migration.utils; + +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; +import org.wso2.carbon.apimgt.api.model.Subscriber; +import org.wso2.carbon.apimgt.impl.APIConstants; + +import java.sql.*; +import java.util.Calendar; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + + +public class ApiDAO { + + public static int getAPIID(APIIdentifier apiId, Connection connection) + throws APIManagementException { + PreparedStatement prepStmt = null; + ResultSet rs = null; + int id = -1; + String getAPIQuery = "SELECT API_ID " + + " FROM AM_API" + + " WHERE API_PROVIDER = ?" + + " AND API_NAME = ?" + + " AND API_VERSION = ?"; + + try { + prepStmt = connection.prepareStatement(getAPIQuery); + prepStmt.setString(1, apiId.getProviderName()); + prepStmt.setString(2, apiId.getApiName()); + prepStmt.setString(3, apiId.getVersion()); + rs = prepStmt.executeQuery(); + if (rs.next()) { + id = rs.getInt("API_ID"); + } + if (id == -1) { + String msg = "Unable to find the API: " + apiId + " in the database"; + System.out.println(msg); + throw new APIManagementException(msg); + } + } catch (SQLException e) { + e.printStackTrace(); + } finally { + DBUtils.closeAllConnections(prepStmt, connection, rs); + } + return id; + } + + public static void addComment(Connection connection, long commentId, String commentText, String user, Date createdTime, int apiId) { + if (apiId == -1) { + //application addition has failed + return; + } + PreparedStatement prepStmt = null; + String addCommentQuery = "INSERT " + + " INTO AM_API_COMMENTS (COMMENT_ID,COMMENT_TEXT,COMMENTED_USER,DATE_COMMENTED,API_ID)" + + " VALUES (?,?,?,?,?)"; + try { + /*Adding data to the AM_API_COMMENTS table*/ + prepStmt = connection.prepareStatement(addCommentQuery); + prepStmt.setLong(1, commentId); + prepStmt.setString(2, commentText); + prepStmt.setString(3, user); + Calendar c1 = Calendar.getInstance(); + c1.setTime(createdTime); + prepStmt.setTimestamp(4, new Timestamp(c1.getTimeInMillis()), Calendar.getInstance()); + prepStmt.setInt(5, apiId); + + prepStmt.executeUpdate(); + } catch (SQLException e) { + System.out.println("Error while adding comment to the database"); + e.printStackTrace(); + } finally { + DBUtils.closeAllConnections(prepStmt, connection, null); + } + } + + public static void addRating(int apiId, Connection connection, int rating, int subscriberId) { + if (apiId == -1) { + //application addition has failed + return; + } + PreparedStatement prepStmtSelect = null; + PreparedStatement prepStmtAdd = null; + ResultSet rs = null; + + boolean userRatingExists = false; + //This query to check the ratings already exists for the user in the AM_API_RATINGS table + String selectRatingQuery = "SELECT " + + "RATING FROM AM_API_RATINGS " + + " WHERE API_ID= ? AND SUBSCRIBER_ID=? "; + + String addRatingQuery = "INSERT " + + " INTO AM_API_RATINGS (API_ID, RATING, SUBSCRIBER_ID)" + + " VALUES (?,?,?)"; + try { + prepStmtSelect = connection.prepareStatement(selectRatingQuery); + prepStmtSelect.setInt(1, apiId); + prepStmtSelect.setInt(2, subscriberId); + rs = prepStmtSelect.executeQuery(); + while (rs.next()) { + userRatingExists = true; + } + + /*Adding data to the AM_API_COMMENTS table*/ + if (!userRatingExists) { + prepStmtAdd = connection.prepareStatement(addRatingQuery); + prepStmtAdd.setInt(1, apiId); + prepStmtAdd.setInt(2, rating); + prepStmtAdd.setInt(3, subscriberId); + + prepStmtAdd.executeUpdate(); + } + } catch (SQLException e) { + System.out.println("Error while adding rating to the database"); + e.printStackTrace(); + } finally { + DBUtils.closeAllConnections(prepStmtSelect, connection, rs); + DBUtils.closeAllConnections(prepStmtAdd, connection, null); + } + } + + public static Set getAllSubscribers(Connection connection) { + Set subscribers = new HashSet(); + PreparedStatement prepStmt = null; + ResultSet result = null; + + try { + String sqlQuery = "SELECT DISTINCT " + + " SUBSCRIBER_ID, USER_ID, DATE_SUBSCRIBED " + + " FROM AM_SUBSCRIBER"; + + prepStmt = connection.prepareStatement(sqlQuery); + result = prepStmt.executeQuery(); + if (result == null) { + return subscribers; + } + while (result.next()) { + Subscriber subscriber = + new Subscriber(result.getString(APIConstants.SUBSCRIBER_FIELD_USER_ID)); + subscriber.setSubscribedDate( + result.getTimestamp(APIConstants.SUBSCRIBER_FIELD_DATE_SUBSCRIBED)); + subscriber.setId(result.getInt(APIConstants.APPLICATION_SUBSCRIBER_ID)); + subscribers.add(subscriber); + } + } catch (SQLException e) { + System.out.println("Error while getting subscribers from database"); + e.printStackTrace(); + } finally { + DBUtils.closeAllConnections(prepStmt, connection, result); + } + return subscribers; + } +} diff --git a/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/utils/CommandHandler.java b/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/utils/CommandHandler.java new file mode 100644 index 0000000000..0c68b36c4d --- /dev/null +++ b/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/utils/CommandHandler.java @@ -0,0 +1,155 @@ +/* +* Copyright (c) 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.carbon.registry.migration.utils; + +import java.util.HashMap; +import java.util.Map; + +public class CommandHandler { + + private static final Map inputs = new HashMap(); + + public static boolean setInputs(String[] arguments) { + + if (arguments.length == 0) { + printMessage(); + return false; + } + if (arguments.length == 1 && arguments[0].equals("--help")) { + printMessage(); + return false; + } + + // now loop through the arguments list to capture the options + for (int i = 0; i < arguments.length; i++) { + if (arguments[i].equals("-h")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Hostname of the registry is missing"); + } + inputs.put("-h", arguments[++i]); + + } else if (arguments[i].equals("-p")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Port of the registry is missing"); + } + inputs.put("-p", arguments[++i]); + + } else if (arguments[i].equals("-u")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Username of the admin is missing"); + } + inputs.put("-u", arguments[++i]); + + } else if (arguments[i].equals("-pw")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Password of the admin is missing"); + } + inputs.put("-pw", arguments[++i]); + }else if (arguments[i].equals("-dpw")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Password of the admin is missing"); + } + inputs.put("-dpw", arguments[++i]); + }else if (arguments[i].equals("-du")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Password of the admin is missing"); + } + inputs.put("-du", arguments[++i]); + }else if (arguments[i].equals("-durl")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Password of the admin is missing"); + } + inputs.put("-durl", arguments[++i]); + } else if (arguments[i].equals("-dr")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Password of the admin is missing"); + } + inputs.put("-dr", arguments[++i]); + } else if (arguments[i].equals("-cr")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Context root of the service is missing"); + } + inputs.put("-cr", arguments[++i]); + } + } + + return true; + } + + + private static void printMessage() { + System.out.println("Usage: migration-client "); + System.out.println("Valid options are:"); + System.out.println("\t-h :\t(Required) The hostname/ip of the registry to login."); + System.out.println("\t-p :\t(Required) The port of the registry to login."); + System.out.println("\t-u :\t(Required) The user name of the registry login."); + System.out.println("\t-pw:\t(Required) The password of the registry login."); + System.out.println(); + System.out.println("Example to migrate a registry running on localhost on default values"); + System.out.println("\te.g: migration-client -h localhost -p 9443 -u admin -pw admin"); + } + + public static String getRegistryURL() { + String contextRoot = inputs.get("-cr"); + + if (contextRoot == null) { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/registry/"; + } else { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/" + contextRoot + "/registry/"; + } + } + + public static String getHost() { + return inputs.get("-h"); + } + + public static String getServiceURL() { + String contextRoot = inputs.get("-cr"); + + if (contextRoot == null) { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/services/"; + } else { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/" + contextRoot + "/services/"; + } + } + + public static String getUsername() { + return inputs.get("-u"); + } + + public static String getPassword() { + return inputs.get("-pw"); + } + + public static String getDBUrl() { + return inputs.get("-durl"); + } + + public static String getDBDriver() { + return inputs.get("-dr"); + } + + public static String getDBPassword() { + return inputs.get("-dpw"); + } + + public static String getDBUsername() { + return inputs.get("-du"); + } +} + diff --git a/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/utils/DBUtils.java b/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/utils/DBUtils.java new file mode 100644 index 0000000000..ab4f04dcf7 --- /dev/null +++ b/modules/distribution/resources/migration-1.3.0_to_1.4.0/api_comments_ratings_migration_client/src/org/wso2/carbon/registry/migration/utils/DBUtils.java @@ -0,0 +1,139 @@ +/* +* Copyright (c) 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.carbon.registry.migration.utils; + +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.apache.commons.dbcp.BasicDataSource; + +public class DBUtils { + static ApiMgtDAO apiMgtDAO; + private static volatile DataSource dataSource = null; + + public static void initializeDB() + throws APIManagementException, ClassNotFoundException, IllegalAccessException, + InstantiationException { + + String dbUrl = CommandHandler.getDBUrl(); + String driver = CommandHandler.getDBDriver(); + String username = CommandHandler.getDBUsername(); + String password = CommandHandler.getDBPassword(); + if (dbUrl == null || driver == null || username == null || password == null) { + System.out.println("Required DB configuration parameters unspecified. So API Store and API Publisher " + + "will not work as expected."); + } + + BasicDataSource basicDataSource = new BasicDataSource(); + basicDataSource.setDriverClassName(driver); + basicDataSource.setUrl(dbUrl); + basicDataSource.setUsername(username); + basicDataSource.setPassword(password); + dataSource = basicDataSource; + + } + + /** + * Utility method to get a new database connection + * + * @return Connection + * @throws java.sql.SQLException if failed to get Connection + */ + public static Connection getConnection() throws SQLException { + if (dataSource != null) { + return dataSource.getConnection(); + } + throw new SQLException("Data source is not configured properly."); + } + + /** + * Utility method to close the connection streams. + * + * @param preparedStatement PreparedStatement + * @param connection Connection + * @param resultSet ResultSet + */ + public static void closeAllConnections(PreparedStatement preparedStatement, + Connection connection, + ResultSet resultSet) { + closeConnection(connection); + closeResultSet(resultSet); + closeStatement(preparedStatement); + } + + /** + * Close Connection + * + * @param dbConnection Connection + */ + private static void closeConnection(Connection dbConnection) { + if (dbConnection != null) { + try { + dbConnection.close(); + } catch (SQLException e) { + e.printStackTrace(); + // log.warn("Database error. Could not close database connection. Continuing with " + + // "others. - " + e.getMessage(), e); + } + } + } + + /** + * Close ResultSet + * + * @param resultSet ResultSet + */ + private static void closeResultSet(ResultSet resultSet) { + if (resultSet != null) { + try { + resultSet.close(); + } catch (SQLException e) { + e.printStackTrace(); + //System.out.println("Database error. Could not close ResultSet - " + e.getMessage(), e); + } + } + + } + + /** + * Close PreparedStatement + * + * @param preparedStatement PreparedStatement + */ + private static void closeStatement(PreparedStatement preparedStatement) { + if (preparedStatement != null) { + try { + preparedStatement.close(); + } catch (SQLException e) { + e.printStackTrace(); + //log.warn("Database error. Could not close PreparedStatement. Continuing with" + + // " others. - " + e.getMessage(), e); + } + } + + } + + +} diff --git a/modules/distribution/resources/migration-1.3.0_to_1.4.0/h2.sql b/modules/distribution/resources/migration-1.3.0_to_1.4.0/h2.sql new file mode 100644 index 0000000000..2eb46a07b2 --- /dev/null +++ b/modules/distribution/resources/migration-1.3.0_to_1.4.0/h2.sql @@ -0,0 +1,33 @@ +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 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) +); + +INSERT INTO AM_APP_KEY_DOMAIN_MAPPING(CONSUMER_KEY,AUTHZ_DOMAIN) +SELECT IDN_OAUTH_CONSUMER_APPS.CONSUMER_KEY , 'ALL' +FROM IDN_OAUTH_CONSUMER_APPS; + +ALTER TABLE `AM_APPLICATION` ADD COLUMN `CALLBACK_URL` VARCHAR(512); +ALTER TABLE AM_SUBSCRIPTION ADD SUB_STATUS VARCHAR(50) DEFAULT 'UNBLOCKED' NOT NULL; diff --git a/modules/distribution/resources/migration-1.3.0_to_1.4.0/mysql.sql b/modules/distribution/resources/migration-1.3.0_to_1.4.0/mysql.sql new file mode 100644 index 0000000000..770163ff3e --- /dev/null +++ b/modules/distribution/resources/migration-1.3.0_to_1.4.0/mysql.sql @@ -0,0 +1,34 @@ +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 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) +)ENGINE INNODB; + +INSERT INTO AM_APP_KEY_DOMAIN_MAPPING(CONSUMER_KEY,AUTHZ_DOMAIN) +SELECT CONSUMER_KEY, "ALL" as new_val +FROM IDN_OAUTH_CONSUMER_APPS; + +ALTER TABLE `AM_APPLICATION` ADD COLUMN `CALLBACK_URL` VARCHAR(512) AFTER `APPLICATION_TIER`; + +ALTER TABLE AM_SUBSCRIPTION ADD SUB_STATUS VARCHAR(50) DEFAULT 'UNBLOCKED' NOT NULL diff --git a/modules/distribution/resources/migration-1.3.0_to_1.4.0/oracle.sql b/modules/distribution/resources/migration-1.3.0_to_1.4.0/oracle.sql new file mode 100644 index 0000000000..acd9f61f0d --- /dev/null +++ b/modules/distribution/resources/migration-1.3.0_to_1.4.0/oracle.sql @@ -0,0 +1,64 @@ +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_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) +) +/ + +INSERT INTO AM_APP_KEY_DOMAIN_MAPPING(CONSUMER_KEY,AUTHZ_DOMAIN) +SELECT IDN_OAUTH_CONSUMER_APPS.CONSUMER_KEY AS a , 'ALL' AS b +FROM IDN_OAUTH_CONSUMER_APPS; +/ + +ALTER TABLE AM_APPLICATION ADD CALLBACK_URL VARCHAR(512); + +ALTER TABLE AM_SUBSCRIPTION ADD SUB_STATUS VARCHAR(512) DEFAULT 'UNBLOCKED' NOT NULL; diff --git a/modules/distribution/resources/migration-1.3.0_to_1.4.0/swagger_resource_migration_script/build.xml b/modules/distribution/resources/migration-1.3.0_to_1.4.0/swagger_resource_migration_script/build.xml new file mode 100644 index 0000000000..52a7e78671 --- /dev/null +++ b/modules/distribution/resources/migration-1.3.0_to_1.4.0/swagger_resource_migration_script/build.xml @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/resources/migration-1.3.0_to_1.4.0/swagger_resource_migration_script/src/org/wso2/carbon/registry/migration/Main.java b/modules/distribution/resources/migration-1.3.0_to_1.4.0/swagger_resource_migration_script/src/org/wso2/carbon/registry/migration/Main.java new file mode 100644 index 0000000000..5ed7843b7d --- /dev/null +++ b/modules/distribution/resources/migration-1.3.0_to_1.4.0/swagger_resource_migration_script/src/org/wso2/carbon/registry/migration/Main.java @@ -0,0 +1,375 @@ +/* +* Copyright (c) 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.carbon.registry.migration; + +import java.io.File; +import java.rmi.RemoteException; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.axis2.Constants; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; +import org.apache.axis2.context.ConfigurationContext; +import org.apache.axis2.context.ConfigurationContextFactory; +import org.apache.axis2.context.ServiceContext; +import org.apache.axis2.transport.http.HTTPConstants; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.doc.model.APIDefinition; +import org.wso2.carbon.apimgt.api.doc.model.APIResource; +import org.wso2.carbon.apimgt.api.doc.model.Operation; +import org.wso2.carbon.apimgt.api.doc.model.Parameter; +import org.wso2.carbon.apimgt.api.model.API; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; +import org.wso2.carbon.apimgt.api.model.URITemplate; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.utils.APIUtil; +import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub; +import org.wso2.carbon.authenticator.stub.LoginAuthenticationExceptionException; +import org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact; +import org.wso2.carbon.governance.api.exception.GovernanceException; +import org.wso2.carbon.governance.api.generic.GenericArtifactManager; +import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact; +import org.wso2.carbon.governance.api.util.GovernanceUtils; +import org.wso2.carbon.registry.core.Registry; +import org.wso2.carbon.registry.core.Resource; +import org.wso2.carbon.registry.core.Tag; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import org.wso2.carbon.registry.core.session.UserRegistry; +import org.wso2.carbon.registry.migration.utils.ApiDAO; +import org.wso2.carbon.registry.migration.utils.CommandHandler; +import org.wso2.carbon.registry.migration.utils.DBUtils; +import org.wso2.carbon.registry.resource.stub.ResourceAdminServiceResourceServiceExceptionException; +import org.wso2.carbon.registry.resource.stub.ResourceAdminServiceStub; +import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient; + +import com.google.gson.Gson; + + +public class Main { + private static Registry registry; + static ConfigurationContext cc; + + + public static void main(String[] args) { + CommandHandler.setInputs(args); + try { + String trustStore = System.getProperty("carbon.home") + File.separator + "repository" + File.separator + + "resources" + File.separator + "security" + File.separator + "wso2carbon.jks"; + System.setProperty("javax.net.ssl.trustStore", trustStore); + System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon"); + System.setProperty("javax.net.ssl.trustStoreType", "JKS"); + System.setProperty("carbon.repo.write.mode", "true"); + + cc = ConfigurationContextFactory.createConfigurationContextFromFileSystem + (System.getProperty("carbon.home") + "repository/deployment/client", System.getProperty("carbon.home") + + "repository/conf/axis2/axis2_client.xml"); + registry = new WSRegistryServiceClient(CommandHandler.getServiceURL(), CommandHandler.getUsername(), + CommandHandler.getPassword(), cc); + DBUtils.initializeDB(); + Main.migrate(); + System.out.println("Finished API data migration process."); + System.exit(0); + } catch (RegistryException e) { + System.out.println("Error while connecting to registry." + e); + } catch (Exception e) { + System.out.println("Error while migrating data." + e); + } + + } + + private static void migrate() throws RegistryException, SQLException, APIManagementException, RemoteException, ResourceAdminServiceResourceServiceExceptionException, LoginAuthenticationExceptionException { + Registry re = GovernanceUtils.getGovernanceUserRegistry(registry, CommandHandler.getUsername()); + GenericArtifactManager manager = new GenericArtifactManager(re, "api"); + GovernanceUtils.loadGovernanceArtifacts((UserRegistry) re); + GenericArtifact[] artifacts = manager.getAllGenericArtifacts(); + + for (GenericArtifact artifact : artifacts) { + API api = getAPI(artifact, re); + createUpdateAPIDefinition(api); + } + + } + + /** + * Create API Definition in JSON and save in the registry + * + * @param api API + * @throws org.wso2.carbon.apimgt.api.APIManagementException + * if failed to generate the content and save + * @throws ResourceAdminServiceResourceServiceExceptionException + * @throws RemoteException + * @throws LoginAuthenticationExceptionException + */ + private static void createUpdateAPIDefinition(API api) throws APIManagementException, RemoteException, ResourceAdminServiceResourceServiceExceptionException, LoginAuthenticationExceptionException { + APIIdentifier identifier = api.getId(); + + try{ + String jsonText = createSwaggerJSONContent(api); + + String resourcePath = "_system/governance" + APIUtil.getAPIDefinitionFilePath(identifier.getApiName(), identifier.getVersion()); + + Resource resource = registry.newResource(); + + resource.setContent(jsonText); + resource.setMediaType("application/json"); + registry.put(resourcePath, resource); + + String sessionCookie = login(CommandHandler.getUsername(), + CommandHandler.getPassword(), CommandHandler.getHost()); + //String permissionString = "ra^false:rd^false:wa^false:wd^false:da^false:dd^false:aa^false:ad^false"; + ResourceAdminServiceStub stub = new ResourceAdminServiceStub(CommandHandler.getServiceURL() + "ResourceAdminService"); + + ServiceClient client = stub._getServiceClient(); + Options option = client.getOptions(); + option.setManageSession(true); + option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, sessionCookie); + stub.addRolePermission(resourcePath, APIConstants.ANONYMOUS_ROLE, "2", "1"); + /*Set permissions to anonymous role */ + //APIUtil.setResourcePermissions(api.getId().getProviderName(), null, null, resourcePath); + + } catch (RegistryException e) { + System.out.println("Error while adding API Definition for " + identifier.getApiName() + "-" + identifier.getVersion()); + } catch (APIManagementException e) { + System.out.println("Error while adding API Definition for " + identifier.getApiName() + "-" + identifier.getVersion()); + } + } + + /** + * Create API Definition in JSON + * + * @param api API + * @throws org.wso2.carbon.apimgt.api.APIManagementException + * if failed to generate the content and save + */ + private static String createSwaggerJSONContent(API api) throws APIManagementException { + APIIdentifier identifier = api.getId(); + + /*APIManagerConfiguration config = ServiceReferenceHolder.getInstance(). + getAPIManagerConfigurationService().getAPIManagerConfiguration(); + String endpoints = config.getFirstProperty(APIConstants.API_GATEWAY_API_ENDPOINT);*/ + + + String endpoint = CommandHandler.getGatewayURL(); + + String apiContext = api.getContext(); + String version = identifier.getVersion(); + Set uriTemplates = api.getUriTemplates(); + String description = api.getDescription(); + String urlPrefix = apiContext + "/" +version; + + if (description == null || description.equals("")) { + description = "no-info"; + } + + Map> uriTemplateDefinitions = new HashMap>(); + List apis = new ArrayList(); + for (URITemplate template : uriTemplates) { + List ops; + List parameters = null; + String path = urlPrefix + + APIUtil.removeAnySymbolFromUriTempate(template.getUriTemplate()); + /* path exists in uriTemplateDefinitions */ + if (uriTemplateDefinitions.get(path) != null) { + ops = uriTemplateDefinitions.get(path); + parameters = new ArrayList(); + if (!(template.getAuthType().equals(APIConstants.AUTH_NO_AUTHENTICATION))) { + Parameter authParam = new Parameter(APIConstants.AuthParameter.AUTH_PARAM_NAME, + APIConstants.AuthParameter.AUTH_PARAM_DESCRIPTION, APIConstants.AuthParameter.AUTH_PARAM_TYPE, true, false, "String"); + parameters.add(authParam); + } + String httpVerb = template.getHTTPVerb(); + /* For GET and DELETE Parameter name - Query Parameters*/ + if (httpVerb.equals(Constants.Configuration.HTTP_METHOD_GET) || + httpVerb.equals(Constants.Configuration.HTTP_METHOD_DELETE)) { + Parameter queryParam = new Parameter(APIConstants.AuthParameter.PAYLOAD_PARAM_NAME, + APIConstants.AuthParameter.PAYLOAD_PARAM_DESCRIPTION, APIConstants.AuthParameter.PAYLOAD_PARAM_TYPE, false, false, "String"); + parameters.add(queryParam); + } else {/* For POST and PUT Parameter name - Payload*/ + Parameter payLoadParam = new Parameter(APIConstants.AuthParameter.PAYLOAD_PARAM_NAME, + APIConstants.AuthParameter.PAYLOAD_PARAM_DESCRIPTION, APIConstants.AuthParameter.PAYLOAD_PARAM_TYPE, false, false, "String"); + parameters.add(payLoadParam); + } + Operation op = new Operation(httpVerb, description, description, parameters); + ops.add(op); + } else {/* path not exists in uriTemplateDefinitions */ + ops = new ArrayList(); + parameters = new ArrayList(); + if (!(template.getAuthType().equals(APIConstants.AUTH_NO_AUTHENTICATION))) { + Parameter authParam = new Parameter(APIConstants.AuthParameter.AUTH_PARAM_NAME, + APIConstants.AuthParameter.AUTH_PARAM_DESCRIPTION, APIConstants.AuthParameter.AUTH_PARAM_TYPE, true, false, "String"); + parameters.add(authParam); + } + String httpVerb = template.getHTTPVerb(); + /* For GET and DELETE Parameter name - Query Parameters*/ + if (httpVerb.equals(Constants.Configuration.HTTP_METHOD_GET) || + httpVerb.equals(Constants.Configuration.HTTP_METHOD_DELETE)) { + Parameter queryParam = new Parameter(APIConstants.AuthParameter.PAYLOAD_PARAM_NAME, + APIConstants.AuthParameter.PAYLOAD_PARAM_DESCRIPTION, APIConstants.AuthParameter.PAYLOAD_PARAM_TYPE, false, false, "String"); + parameters.add(queryParam); + } else {/* For POST and PUT Parameter name - Payload*/ + Parameter payLoadParam = new Parameter(APIConstants.AuthParameter.PAYLOAD_PARAM_NAME, + APIConstants.AuthParameter.PAYLOAD_PARAM_DESCRIPTION, APIConstants.AuthParameter.PAYLOAD_PARAM_TYPE, false, false, "String"); + parameters.add(payLoadParam); + } + Operation op = new Operation(httpVerb, description, description, parameters); + ops.add(op); + uriTemplateDefinitions.put(path, ops); + } + } + + Set resPaths = uriTemplateDefinitions.keySet(); + + for (String resPath: resPaths) { + APIResource apiResource = new APIResource(resPath, description, uriTemplateDefinitions.get(resPath)); + apis.add(apiResource); + } + + APIDefinition apidefinition = new APIDefinition(version, APIConstants.SWAGGER_VERSION, endpoint, apiContext, apis); + + Gson gson = new Gson(); + return gson.toJson(apidefinition); + } + + private static String login(String userName, String password, String host) + throws LoginAuthenticationExceptionException, RemoteException { + Boolean loginStatus; + ServiceContext serviceContext; + String sessionCookie; + AuthenticationAdminStub authenticationAdminStub = new AuthenticationAdminStub(CommandHandler.getServiceURL() + "AuthenticationAdmin"); + loginStatus = authenticationAdminStub.login(userName, password, host); + + if (!loginStatus) { + throw new LoginAuthenticationExceptionException("Login Unsuccessful. Return false as a login status by Server"); + } + serviceContext = authenticationAdminStub._getServiceClient().getLastOperationContext().getServiceContext(); + sessionCookie = (String) serviceContext.getProperty(HTTPConstants.COOKIE_STRING); + return sessionCookie; + } + + public static API getAPI(GovernanceArtifact artifact, Registry registry) + throws APIManagementException, SQLException { + + API api; + try { + String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER); + String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME); + String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION); + APIIdentifier apiId=new APIIdentifier(providerName, apiName, apiVersion); + api = new API(apiId); + // set rating + String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId()); + // BigDecimal bigDecimal = new BigDecimal(getAverageRating(apiId)); + //BigDecimal res = bigDecimal.setScale(1, RoundingMode.HALF_UP); + + //set description + api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION)); + //set last access time + api.setLastUpdated(registry.get(artifactPath).getLastModified()); + // set url + api.setUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_URL)); + api.setSandboxUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_SANDBOX_URL)); + api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL)); + api.setWsdlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WSDL)); + api.setWadlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WADL)); + api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER)); + api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL)); + api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER)); + api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL)); + api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY)); + api.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES)); + api.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS)); + api.setEndpointSecured(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED))); + api.setEndpointUTUsername(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME)); + api.setEndpointUTPassword(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD)); + + + api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT)); + api.setLatest(Boolean.valueOf(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_LATEST))); + + + Set uriTemplates = new LinkedHashSet(); + List uriTemplateNames = new ArrayList(); + + + HashMap urlPatternsSet; + urlPatternsSet = ApiDAO.getURITemplatesPerAPIAsString(api.getId(), DBUtils.getConnection()); + Set urlPatternsKeySet = urlPatternsSet.keySet(); + for (String urlPattern : urlPatternsKeySet) { + URITemplate uriTemplate = new URITemplate(); + String uTemplate = urlPattern.split("::")[0]; + String method = urlPattern.split("::")[1]; + String authType = urlPattern.split("::")[2]; + + uriTemplate.setHTTPVerb(method); + uriTemplate.setAuthType(authType); + uriTemplate.setHttpVerbs(method); + uriTemplate.setAuthTypes(authType); + uriTemplate.setUriTemplate(uTemplate); + uriTemplate.setResourceURI(api.getUrl()); + uriTemplate.setResourceSandboxURI(api.getSandboxUrl()); + + /*//Checking for duplicate uri template names + if (uriTemplateNames.contains(uTemplate)) { + for (URITemplate tmp : uriTemplates) { + if (uTemplate.equals(tmp.getUriTemplate())) { + tmp.setHttpVerbs(method); + tmp.setAuthTypes(authType); + break; + } + } + + } else { + uriTemplates.add(uriTemplate); + } + + uriTemplateNames.add(uTemplate);*/ + uriTemplates.add(uriTemplate); + + + } + api.setUriTemplates(uriTemplates); + + + Set tags = new HashSet(); + org.wso2.carbon.registry.core.Tag[] tag = registry.getTags(artifactPath); + for (Tag tag1 : tag) { + tags.add(tag1.getTagName()); + } + api.addTags(tags); + api.setLastUpdated(registry.get(artifactPath).getLastModified()); + + } catch (GovernanceException e) { + String msg = "Failed to get API fro artifact "; + throw new APIManagementException(msg, e); + } catch (RegistryException e) { + String msg = "Failed to add Resource"; + throw new APIManagementException(msg, e); + } + return api; + } + +} + diff --git a/modules/distribution/resources/migration-1.3.0_to_1.4.0/swagger_resource_migration_script/src/org/wso2/carbon/registry/migration/utils/ApiDAO.java b/modules/distribution/resources/migration-1.3.0_to_1.4.0/swagger_resource_migration_script/src/org/wso2/carbon/registry/migration/utils/ApiDAO.java new file mode 100644 index 0000000000..d764a3d23e --- /dev/null +++ b/modules/distribution/resources/migration-1.3.0_to_1.4.0/swagger_resource_migration_script/src/org/wso2/carbon/registry/migration/utils/ApiDAO.java @@ -0,0 +1,222 @@ +/* +* Copyright (c) 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.carbon.registry.migration.utils; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.LinkedHashMap; + +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; + + +public class ApiDAO { + + public static HashMap getURITemplatesPerAPIAsString(APIIdentifier identifier, Connection conn) + throws APIManagementException { + ResultSet resultSet = null; + PreparedStatement ps = null; + int apiId = -1; + HashMap urlMappings = new LinkedHashMap(); + + try { + apiId = getAPIID(identifier,conn); + conn = DBUtils.getConnection(); + String sqlQuery = + "SELECT " + + "URL_PATTERN" + + ",HTTP_METHOD" + + ",AUTH_SCHEME " + + "FROM " + + "AM_API_URL_MAPPING " + + "WHERE " + + "API_ID = ? " + + "ORDER BY " + + "URL_MAPPING_ID ASC "; + + + ps = conn.prepareStatement(sqlQuery); + ps.setInt(1, apiId); + resultSet = ps.executeQuery(); + while (resultSet.next()) { + String uriPattern = resultSet.getString("URL_PATTERN"); + String httpMethod = resultSet.getString("HTTP_METHOD"); + String authScheme = resultSet.getString("AUTH_SCHEME"); + urlMappings.put(uriPattern + "::" + httpMethod + "::" + authScheme,null); + } + } catch (SQLException e) { + if (conn != null) { + try { + conn.rollback(); + } catch (SQLException e1) { + e.printStackTrace(); + throw new APIManagementException(e1); + } + } + e.printStackTrace(); + } finally { + DBUtils.closeAllConnections(ps, conn, resultSet); + } + return urlMappings; + } + + public static int getAPIID(APIIdentifier apiId, Connection connection) + throws APIManagementException, SQLException { + PreparedStatement prepStmt = null; + ResultSet rs = null; + int id = -1; + String getAPIQuery = "SELECT API_ID " + + " FROM AM_API" + + " WHERE API_PROVIDER = ?" + + " AND API_NAME = ?" + + " AND API_VERSION = ?"; + + try { + prepStmt = connection.prepareStatement(getAPIQuery); + prepStmt.setString(1, apiId.getProviderName()); + prepStmt.setString(2, apiId.getApiName()); + prepStmt.setString(3, apiId.getVersion()); + rs = prepStmt.executeQuery(); + if (rs.next()) { + id = rs.getInt("API_ID"); + } + if (id == -1) { + String msg = "Unable to find the API: " + apiId + " in the database"; + System.out.println(msg); + throw new APIManagementException(msg); + } + } catch (SQLException e) { + e.printStackTrace(); + throw e; + } finally { + DBUtils.closeAllConnections(prepStmt, connection, rs); + } + return id; + } + + /*public static void addComment(Connection connection, long commentId, String commentText, String user, Date createdTime, int apiId) { + if (apiId == -1) { + //application addition has failed + return; + } + PreparedStatement prepStmt = null; + String addCommentQuery = "INSERT " + + " INTO AM_API_COMMENTS (COMMENT_ID,COMMENT_TEXT,COMMENTED_USER,DATE_COMMENTED,API_ID)" + + " VALUES (?,?,?,?,?)"; + try { + Adding data to the AM_API_COMMENTS table + prepStmt = connection.prepareStatement(addCommentQuery); + prepStmt.setLong(1, commentId); + prepStmt.setString(2, commentText); + prepStmt.setString(3, user); + Calendar c1 = Calendar.getInstance(); + c1.setTime(createdTime); + prepStmt.setTimestamp(4, new Timestamp(c1.getTimeInMillis()), Calendar.getInstance()); + prepStmt.setInt(5, apiId); + + prepStmt.executeUpdate(); + } catch (SQLException e) { + System.out.println("Error while adding comment to the database"); + e.printStackTrace(); + } finally { + DBUtils.closeAllConnections(prepStmt, connection, null); + } + } + + public static void addRating(int apiId, Connection connection, int rating, int subscriberId) { + if (apiId == -1) { + //application addition has failed + return; + } + PreparedStatement prepStmtSelect = null; + PreparedStatement prepStmtAdd = null; + ResultSet rs = null; + + boolean userRatingExists = false; + //This query to check the ratings already exists for the user in the AM_API_RATINGS table + String selectRatingQuery = "SELECT " + + "RATING FROM AM_API_RATINGS " + + " WHERE API_ID= ? AND SUBSCRIBER_ID=? "; + + String addRatingQuery = "INSERT " + + " INTO AM_API_RATINGS (API_ID, RATING, SUBSCRIBER_ID)" + + " VALUES (?,?,?)"; + try { + prepStmtSelect = connection.prepareStatement(selectRatingQuery); + prepStmtSelect.setInt(1, apiId); + prepStmtSelect.setInt(2, subscriberId); + rs = prepStmtSelect.executeQuery(); + while (rs.next()) { + userRatingExists = true; + } + + Adding data to the AM_API_COMMENTS table + if (!userRatingExists) { + prepStmtAdd = connection.prepareStatement(addRatingQuery); + prepStmtAdd.setInt(1, apiId); + prepStmtAdd.setInt(2, rating); + prepStmtAdd.setInt(3, subscriberId); + + prepStmtAdd.executeUpdate(); + } + } catch (SQLException e) { + System.out.println("Error while adding rating to the database"); + e.printStackTrace(); + } finally { + DBUtils.closeAllConnections(prepStmtSelect, connection, rs); + DBUtils.closeAllConnections(prepStmtAdd, connection, null); + } + } + + public static Set getAllSubscribers(Connection connection) { + Set subscribers = new HashSet(); + PreparedStatement prepStmt = null; + ResultSet result = null;/TestAPI-1.0.0/api-doc.json + + try { + String sqlQuery = "SELECT DISTINCT " + + " SUBSCRIBER_ID, USER_ID, DATE_SUBSCRIBED " + + " FROM AM_SUBSCRIBER"; + + prepStmt = connection.prepareStatement(sqlQuery); + result = prepStmt.executeQuery(); + if (result == null) { + return subscribers; + } + while (result.next()) { + Subscriber subscriber = + new Subscriber(result.getString(APIConstants.SUBSCRIBER_FIELD_USER_ID)); + subscriber.setSubscribedDate( + result.getTimestamp(APIConstants.SUBSCRIBER_FIELD_DATE_SUBSCRIBED)); + subscriber.setId(result.getInt(APIConstants.APPLICATION_SUBSCRIBER_ID)); + subscribers.add(subscriber); + } + } catch (SQLException e) { + System.out.println("Error while getting subscribers from database"); + e.printStackTrace(); + } finally { + DBUtils.closeAllConnections(prepStmt, connection, result); + } + return subscribers; + }*/ +} + diff --git a/modules/distribution/resources/migration-1.3.0_to_1.4.0/swagger_resource_migration_script/src/org/wso2/carbon/registry/migration/utils/CommandHandler.java b/modules/distribution/resources/migration-1.3.0_to_1.4.0/swagger_resource_migration_script/src/org/wso2/carbon/registry/migration/utils/CommandHandler.java new file mode 100644 index 0000000000..fc41c7ed93 --- /dev/null +++ b/modules/distribution/resources/migration-1.3.0_to_1.4.0/swagger_resource_migration_script/src/org/wso2/carbon/registry/migration/utils/CommandHandler.java @@ -0,0 +1,171 @@ +/* +* Copyright (c) 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.carbon.registry.migration.utils; + +import java.util.HashMap; +import java.util.Map; + +public class CommandHandler { + + private static final Map inputs = new HashMap(); + + public static boolean setInputs(String[] arguments) { + + if (arguments.length == 0) { + printMessage(); + return false; + } + if (arguments.length == 1 && arguments[0].equals("--help")) { + printMessage(); + return false; + } + + // now loop through the arguments list to capture the options + for (int i = 0; i < arguments.length; i++) { + if (arguments[i].equals("-h")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Hostname of the registry is missing"); + } + inputs.put("-h", arguments[++i]); + + } else if (arguments[i].equals("-p")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Port of the registry is missing"); + } + inputs.put("-p", arguments[++i]); + + } else if (arguments[i].equals("-u")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Username of the admin is missing"); + } + inputs.put("-u", arguments[++i]); + + } else if (arguments[i].equals("-pw")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Password of the admin is missing"); + } + inputs.put("-pw", arguments[++i]); + }else if (arguments[i].equals("-dpw")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Password of the admin is missing"); + } + inputs.put("-dpw", arguments[++i]); + }else if (arguments[i].equals("-du")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Password of the database missing"); + } + inputs.put("-du", arguments[++i]); + }else if (arguments[i].equals("-durl")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Username of the database is missing"); + } + inputs.put("-durl", arguments[++i]); + } else if (arguments[i].equals("-dr")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Database is missing"); + } + inputs.put("-dr", arguments[++i]); + } else if (arguments[i].equals("-cr")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Context root of the service is missing"); + } + inputs.put("-cr", arguments[++i]); + } else if (arguments[i].equals("-gh")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Hostname of the API gateway is missing"); + } + inputs.put("-gh", arguments[++i]); + } else if (arguments[i].equals("-gp")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Port of the API gateway is missing"); + } + inputs.put("-gp", arguments[++i]); + } + } + + return true; + } + + + private static void printMessage() { + System.out.println("Usage: migration-client "); + System.out.println("Valid options are:"); + System.out.println("\t-h :\t(Required) The hostname/ip of the registry to login."); + System.out.println("\t-p :\t(Required) The port of the registry to login."); + System.out.println("\t-u :\t(Required) The user name of the registry login."); + System.out.println("\t-pw:\t(Required) The password of the registry login."); + System.out.println(); + System.out.println("Example to migrate a registry running on localhost on default values"); + System.out.println("\te.g: migration-client -h localhost -p 9443 -u admin -pw admin"); + } + + public static String getRegistryURL() { + String contextRoot = inputs.get("-cr"); + + if (contextRoot == null) { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/registry/"; + } else { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/" + contextRoot + "/registry/"; + } + } + + public static String getHost() { + return inputs.get("-h"); + } + + public static String getServiceURL() { + String contextRoot = inputs.get("-cr"); + + if (contextRoot == null) { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/services/"; + } else { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/" + contextRoot + "/services/"; + } + } + + public static String getGatewayURL() { + int gatewayPort = Integer.parseInt(inputs.get("-gp")); + gatewayPort = 8280 + (gatewayPort - 9443); + return "https://" + inputs.get("-gh") + ":" + gatewayPort + "/services/"; + } + + public static String getUsername() { + return inputs.get("-u"); + } + + public static String getPassword() { + return inputs.get("-pw"); + } + + public static String getDBUrl() { + return inputs.get("-durl"); + } + + public static String getDBDriver() { + return inputs.get("-dr"); + } + + public static String getDBPassword() { + return inputs.get("-dpw"); + } + + public static String getDBUsername() { + return inputs.get("-du"); + } +} + diff --git a/modules/distribution/resources/migration-1.3.0_to_1.4.0/swagger_resource_migration_script/src/org/wso2/carbon/registry/migration/utils/DBUtils.java b/modules/distribution/resources/migration-1.3.0_to_1.4.0/swagger_resource_migration_script/src/org/wso2/carbon/registry/migration/utils/DBUtils.java new file mode 100644 index 0000000000..ab4f04dcf7 --- /dev/null +++ b/modules/distribution/resources/migration-1.3.0_to_1.4.0/swagger_resource_migration_script/src/org/wso2/carbon/registry/migration/utils/DBUtils.java @@ -0,0 +1,139 @@ +/* +* Copyright (c) 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.carbon.registry.migration.utils; + +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.apache.commons.dbcp.BasicDataSource; + +public class DBUtils { + static ApiMgtDAO apiMgtDAO; + private static volatile DataSource dataSource = null; + + public static void initializeDB() + throws APIManagementException, ClassNotFoundException, IllegalAccessException, + InstantiationException { + + String dbUrl = CommandHandler.getDBUrl(); + String driver = CommandHandler.getDBDriver(); + String username = CommandHandler.getDBUsername(); + String password = CommandHandler.getDBPassword(); + if (dbUrl == null || driver == null || username == null || password == null) { + System.out.println("Required DB configuration parameters unspecified. So API Store and API Publisher " + + "will not work as expected."); + } + + BasicDataSource basicDataSource = new BasicDataSource(); + basicDataSource.setDriverClassName(driver); + basicDataSource.setUrl(dbUrl); + basicDataSource.setUsername(username); + basicDataSource.setPassword(password); + dataSource = basicDataSource; + + } + + /** + * Utility method to get a new database connection + * + * @return Connection + * @throws java.sql.SQLException if failed to get Connection + */ + public static Connection getConnection() throws SQLException { + if (dataSource != null) { + return dataSource.getConnection(); + } + throw new SQLException("Data source is not configured properly."); + } + + /** + * Utility method to close the connection streams. + * + * @param preparedStatement PreparedStatement + * @param connection Connection + * @param resultSet ResultSet + */ + public static void closeAllConnections(PreparedStatement preparedStatement, + Connection connection, + ResultSet resultSet) { + closeConnection(connection); + closeResultSet(resultSet); + closeStatement(preparedStatement); + } + + /** + * Close Connection + * + * @param dbConnection Connection + */ + private static void closeConnection(Connection dbConnection) { + if (dbConnection != null) { + try { + dbConnection.close(); + } catch (SQLException e) { + e.printStackTrace(); + // log.warn("Database error. Could not close database connection. Continuing with " + + // "others. - " + e.getMessage(), e); + } + } + } + + /** + * Close ResultSet + * + * @param resultSet ResultSet + */ + private static void closeResultSet(ResultSet resultSet) { + if (resultSet != null) { + try { + resultSet.close(); + } catch (SQLException e) { + e.printStackTrace(); + //System.out.println("Database error. Could not close ResultSet - " + e.getMessage(), e); + } + } + + } + + /** + * Close PreparedStatement + * + * @param preparedStatement PreparedStatement + */ + private static void closeStatement(PreparedStatement preparedStatement) { + if (preparedStatement != null) { + try { + preparedStatement.close(); + } catch (SQLException e) { + e.printStackTrace(); + //log.warn("Database error. Could not close PreparedStatement. Continuing with" + + // " others. - " + e.getMessage(), e); + } + } + + } + + +} diff --git a/modules/distribution/resources/migration-1.4.0_to_1.5.0/apimgt_db/h2.sql b/modules/distribution/resources/migration-1.4.0_to_1.5.0/apimgt_db/h2.sql new file mode 100644 index 0000000000..1fa2d564f2 --- /dev/null +++ b/modules/distribution/resources/migration-1.4.0_to_1.5.0/apimgt_db/h2.sql @@ -0,0 +1,41 @@ +ALTER TABLE AM_API_URL_MAPPING ADD THROTTLING_TIER varchar(512) DEFAULT 'Unlimited'; + +ALTER TABLE AM_APPLICATION ADD DESCRIPTION VARCHAR(512); + +ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD COLUMN GRANT_TYPES VARCHAR (1024); + +ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD COLUMN LOGIN_PAGE_URL VARCHAR (1024); + +ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD COLUMN ERROR_PAGE_URL VARCHAR (1024); + +ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD COLUMN CONSENT_PAGE_URL VARCHAR (1024); + +ALTER TABLE IDN_OAUTH2_AUTHORIZATION_CODE ADD COLUMN CALLBACK_URL VARCHAR(1024); + +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_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 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) +); diff --git a/modules/distribution/resources/migration-1.4.0_to_1.5.0/apimgt_db/mysql.sql b/modules/distribution/resources/migration-1.4.0_to_1.5.0/apimgt_db/mysql.sql new file mode 100644 index 0000000000..74312b1515 --- /dev/null +++ b/modules/distribution/resources/migration-1.4.0_to_1.5.0/apimgt_db/mysql.sql @@ -0,0 +1,41 @@ +ALTER TABLE AM_API_URL_MAPPING ADD THROTTLING_TIER varchar(512) DEFAULT 'Unlimited'; + +ALTER TABLE AM_APPLICATION ADD DESCRIPTION VARCHAR(512); + +ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD COLUMN GRANT_TYPES VARCHAR (1024); + +ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD COLUMN LOGIN_PAGE_URL VARCHAR (1024); + +ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD COLUMN ERROR_PAGE_URL VARCHAR (1024); + +ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD COLUMN CONSENT_PAGE_URL VARCHAR (1024); + +ALTER TABLE IDN_OAUTH2_AUTHORIZATION_CODE ADD COLUMN CALLBACK_URL VARCHAR(1024); + +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_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 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) +)ENGINE INNODB; diff --git a/modules/distribution/resources/migration-1.4.0_to_1.5.0/apimgt_db/oracle.sql b/modules/distribution/resources/migration-1.4.0_to_1.5.0/apimgt_db/oracle.sql new file mode 100644 index 0000000000..8c60e3b286 --- /dev/null +++ b/modules/distribution/resources/migration-1.4.0_to_1.5.0/apimgt_db/oracle.sql @@ -0,0 +1,63 @@ +ALTER TABLE AM_API_URL_MAPPING ADD THROTTLING_TIER varchar(512) DEFAULT 'Unlimited' +/ +ALTER TABLE AM_APPLICATION ADD DESCRIPTION VARCHAR(512) +/ +ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD GRANT_TYPES VARCHAR (1024) +/ + +ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD LOGIN_PAGE_URL VARCHAR (1024) +/ + +ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD ERROR_PAGE_URL VARCHAR (1024) +/ + +ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD CONSENT_PAGE_URL VARCHAR (1024) +/ + +ALTER TABLE IDN_OAUTH2_AUTHORIZATION_CODE ADD CALLBACK_URL VARCHAR(1024) +/ + +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 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_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 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, + PRIMARY KEY (SESSION_ID) +) +/ + diff --git a/modules/distribution/resources/migration-1.4.0_to_1.5.0/userstore_db/h2.sql b/modules/distribution/resources/migration-1.4.0_to_1.5.0/userstore_db/h2.sql new file mode 100644 index 0000000000..15fae447b8 --- /dev/null +++ b/modules/distribution/resources/migration-1.4.0_to_1.5.0/userstore_db/h2.sql @@ -0,0 +1,118 @@ +CREATE TABLE UM_DOMAIN( + UM_DOMAIN_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_DOMAIN_NAME VARCHAR(255), + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_DOMAIN_ID, UM_TENANT_ID) +); + +CREATE TABLE UM_SYSTEM_USER ( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_USER_NAME VARCHAR(255) NOT NULL, + UM_USER_PASSWORD VARCHAR(255) NOT NULL, + UM_SALT_VALUE VARCHAR(31), + UM_REQUIRE_CHANGE BOOLEAN DEFAULT FALSE, + UM_CHANGED_TIME TIMESTAMP NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_ID, UM_TENANT_ID), + UNIQUE(UM_USER_NAME, UM_TENANT_ID) +); + +ALTER TABLE UM_ROLE ADD COLUMN UM_SHARED_ROLE BOOLEAN DEFAULT FALSE; + +CREATE TABLE UM_MODULE( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_MODULE_NAME VARCHAR(100), + UNIQUE(UM_MODULE_NAME), + PRIMARY KEY(UM_ID) +); + +CREATE TABLE UM_MODULE_ACTIONS( + UM_ACTION VARCHAR(255) NOT NULL, + UM_MODULE_ID INTEGER NOT NULL, + PRIMARY KEY(UM_ACTION, UM_MODULE_ID), + FOREIGN KEY (UM_MODULE_ID) REFERENCES UM_MODULE(UM_ID) ON DELETE CASCADE +); + +ALTER TABLE UM_PERMISSION ADD COLUMN UM_MODULE_ID INTEGER DEFAULT 0; +ALTER TABLE UM_ROLE_PERMISSION ADD COLUMN UM_DOMAIN_ID INTEGER; +ALTER TABLE UM_ROLE_PERMISSION ADD CONSTRAINT UQ_UM_ROLE_PERMISSION UNIQUE (UM_PERMISSION_ID, UM_ROLE_NAME, UM_TENANT_ID, UM_DOMAIN_ID); +ALTER TABLE UM_ROLE_PERMISSION ADD CONSTRAINT UM_ROLE_PERMISSION_UM_DOMAIN FOREIGN KEY (UM_DOMAIN_ID, UM_TENANT_ID) REFERENCES UM_DOMAIN(UM_DOMAIN_ID, UM_TENANT_ID) ON DELETE CASCADE; + + +INSERT INTO UM_DOMAIN (UM_DOMAIN_NAME, UM_TENANT_ID) VALUES ('PRIMARY', -1234); +INSERT INTO UM_DOMAIN (UM_DOMAIN_NAME, UM_TENANT_ID) VALUES ('SYSTEM', -1234); +INSERT INTO UM_DOMAIN (UM_DOMAIN_NAME, UM_TENANT_ID) VALUES ('INTERNAL', -1234); + + +INSERT INTO UM_DOMAIN (UM_TENANT_ID) SELECT UM_ID FROM UM_TENANT; +UPDATE UM_DOMAIN SET UM_DOMAIN_NAME = 'SYSTEM' WHERE UM_DOMAIN_NAME IS NULL AND UM_TENANT_ID IN (SELECT UM_ID FROM UM_TENANT); + +INSERT INTO UM_DOMAIN (UM_TENANT_ID) SELECT UM_ID FROM UM_TENANT; +UPDATE UM_DOMAIN SET UM_DOMAIN_NAME = 'INTERNAL' WHERE UM_DOMAIN_NAME IS NULL AND UM_TENANT_ID IN (SELECT UM_ID FROM UM_TENANT); + +INSERT INTO UM_DOMAIN (UM_TENANT_ID) SELECT UM_ID FROM UM_TENANT; +UPDATE UM_DOMAIN SET UM_DOMAIN_NAME = 'PRIMARY' WHERE UM_DOMAIN_NAME IS NULL AND UM_TENANT_ID IN (SELECT UM_ID FROM UM_TENANT); + +/** +SYSTEM +INTERNAL +PRIMARY +**/ + +UPDATE UM_ROLE_PERMISSION SET UM_ROLE_PERMISSION.UM_DOMAIN_ID = (SELECT UM_DOMAIN.UM_DOMAIN_ID FROM UM_DOMAIN WHERE UM_DOMAIN.UM_TENANT_ID = UM_ROLE_PERMISSION.UM_TENANT_ID AND UM_ROLE_PERMISSION.UM_DOMAIN_ID IS NULL AND UM_DOMAIN.UM_DOMAIN_NAME = 'PRIMARY') WHERE UM_ROLE_PERMISSION.UM_DOMAIN_ID IS NULL; + +UPDATE UM_ROLE_PERMISSION SET UM_ROLE_PERMISSION.UM_DOMAIN_ID = (SELECT UM_DOMAIN.UM_DOMAIN_ID FROM UM_DOMAIN WHERE UM_DOMAIN.UM_TENANT_ID = UM_ROLE_PERMISSION.UM_TENANT_ID AND UM_ROLE_PERMISSION.UM_ROLE_NAME = 'everyone' AND UM_DOMAIN.UM_DOMAIN_NAME = 'INTERNAL') WHERE UM_ROLE_PERMISSION.UM_ROLE_NAME = 'everyone'; + +UPDATE UM_ROLE_PERMISSION SET UM_ROLE_PERMISSION.UM_DOMAIN_ID = (SELECT UM_DOMAIN.UM_DOMAIN_ID FROM UM_DOMAIN WHERE UM_DOMAIN.UM_TENANT_ID = UM_ROLE_PERMISSION.UM_TENANT_ID AND UM_ROLE_PERMISSION.UM_ROLE_NAME = 'wso2.anonymous.role' AND UM_DOMAIN.UM_DOMAIN_NAME = 'SYSTEM') WHERE UM_ROLE_PERMISSION.UM_ROLE_NAME = 'wso2.anonymous.role'; + +CREATE TABLE UM_SHARED_USER_ROLE( + UM_ROLE_ID INTEGER NOT NULL, + UM_USER_ID INTEGER NOT NULL, + UM_USER_TENANT_ID INTEGER NOT NULL, + UM_ROLE_TENANT_ID INTEGER NOT NULL, + UNIQUE(UM_USER_ID,UM_ROLE_ID,UM_USER_TENANT_ID, UM_ROLE_TENANT_ID), + FOREIGN KEY(UM_ROLE_ID,UM_ROLE_TENANT_ID) REFERENCES UM_ROLE(UM_ID,UM_TENANT_ID) ON DELETE CASCADE, + FOREIGN KEY(UM_USER_ID,UM_USER_TENANT_ID) REFERENCES UM_USER(UM_ID,UM_TENANT_ID) ON DELETE CASCADE +); + +CREATE TABLE UM_ACCOUNT_MAPPING( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_USER_NAME VARCHAR(255) NOT NULL, + UM_TENANT_ID INTEGER NOT NULL, + UM_USER_STORE_DOMAIN VARCHAR(100), + UM_ACC_LINK_ID INTEGER NOT NULL, + UNIQUE(UM_USER_NAME, UM_TENANT_ID, UM_USER_STORE_DOMAIN, UM_ACC_LINK_ID), + FOREIGN KEY (UM_TENANT_ID) REFERENCES UM_TENANT(UM_ID) ON DELETE CASCADE, + PRIMARY KEY (UM_ID) +); + + +ALTER TABLE UM_CLAIM ADD COLUMN UM_MAPPED_ATTRIBUTE_DOMAIN VARCHAR(255); +ALTER TABLE UM_CLAIM ADD COLUMN UM_CHECKED_ATTRIBUTE SMALLINT; +ALTER TABLE UM_CLAIM ADD COLUMN UM_READ_ONLY SMALLINT; + +ALTER TABLE UM_CLAIM ADD CONSTRAINT UNIQUE(UM_DIALECT_ID, UM_CLAIM_URI, UM_TENANT_ID,UM_MAPPED_ATTRIBUTE_DOMAIN); + +DROP TABLE IF EXISTS UM_CLAIM_BEHAVIOR; + +ALTER TABLE UM_HYBRID_USER_ROLE ADD COLUMN UM_DOMAIN_ID INTEGER; + +ALTER TABLE UM_HYBRID_USER_ROLE ADD CONSTRAINT UNIQUE (UM_USER_NAME, UM_ROLE_ID, UM_TENANT_ID, UM_DOMAIN_ID); +ALTER TABLE UM_HYBRID_USER_ROLE ADD CONSTRAINT FOREIGN KEY (UM_DOMAIN_ID, UM_TENANT_ID) REFERENCES UM_DOMAIN(UM_DOMAIN_ID, UM_TENANT_ID) ON DELETE CASCADE; + +CREATE TABLE UM_SYSTEM_ROLE( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_ROLE_NAME VARCHAR(255), + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_ID, UM_TENANT_ID) +); + +CREATE TABLE UM_SYSTEM_USER_ROLE( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_USER_NAME VARCHAR(255), + UM_ROLE_ID INTEGER NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + UNIQUE (UM_USER_NAME, UM_ROLE_ID, UM_TENANT_ID), + FOREIGN KEY (UM_ROLE_ID, UM_TENANT_ID) REFERENCES UM_SYSTEM_ROLE(UM_ID, UM_TENANT_ID), + PRIMARY KEY (UM_ID, UM_TENANT_ID) +); diff --git a/modules/distribution/resources/migration-1.4.0_to_1.5.0/userstore_db/mssql.sql b/modules/distribution/resources/migration-1.4.0_to_1.5.0/userstore_db/mssql.sql new file mode 100644 index 0000000000..a3b0d0ccf8 --- /dev/null +++ b/modules/distribution/resources/migration-1.4.0_to_1.5.0/userstore_db/mssql.sql @@ -0,0 +1,135 @@ +--CREATE TABLE UM_DOMAIN +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[dbo].[UM_DOMAIN]') AND TYPE IN (N'U')) +CREATE TABLE UM_DOMAIN( + UM_DOMAIN_ID INTEGER IDENTITY(1,1) NOT NULL, + UM_DOMAIN_NAME VARCHAR(255), + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_DOMAIN_ID, UM_TENANT_ID) +); + + +--CREATE TABLE UM_SYSTEM_USER +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[dbo].[UM_SYSTEM_USER]') AND TYPE IN (N'U')) +CREATE TABLE UM_SYSTEM_USER ( + UM_ID INTEGER IDENTITY(1,1) NOT NULL, + UM_USER_NAME VARCHAR(255) NOT NULL, + UM_USER_PASSWORD VARCHAR(255) NOT NULL, + UM_SALT_VALUE VARCHAR(31), + UM_REQUIRE_CHANGE BIT DEFAULT 0, + UM_CHANGED_TIME DATETIME NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_ID, UM_TENANT_ID), + UNIQUE(UM_USER_NAME, UM_TENANT_ID) +); + + +ALTER TABLE UM_ROLE ADD UM_SHARED_ROLE BIT DEFAULT 0; + + +--CREATES TABLE UM_MODULE +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[dbo].[UM_MODULE]') AND TYPE IN (N'U')) +CREATE TABLE UM_MODULE( + UM_ID INTEGER IDENTITY(1,1) NOT NULL, + UM_MODULE_NAME VARCHAR(100), + UNIQUE(UM_MODULE_NAME), + PRIMARY KEY(UM_ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[dbo].[UM_MODULE_ACTIONS]') AND TYPE IN (N'U')) +CREATE TABLE UM_MODULE_ACTIONS( + UM_ACTION VARCHAR(255) NOT NULL, + UM_MODULE_ID INTEGER NOT NULL, + PRIMARY KEY(UM_ACTION, UM_MODULE_ID), + FOREIGN KEY (UM_MODULE_ID) REFERENCES UM_MODULE(UM_ID) ON DELETE CASCADE +); + +ALTER TABLE UM_PERMISSION ADD UM_MODULE_ID INTEGER DEFAULT 0; + +ALTER TABLE UM_ROLE_PERMISSION ADD UM_DOMAIN_ID INTEGER; + +declare @Command nvarchar(1000); +select @Command = +'ALTER TABLE UM_ROLE_PERMISSION DROP CONSTRAINT ' + k.name from sys.tables t join sys.key_constraints k on t.object_id = k.parent_object_id where t.name = 'UM_ROLE_PERMISSION' and k.name like 'UQ%'; +EXECUTE(@command); + +ALTER TABLE UM_ROLE_PERMISSION ADD CONSTRAINT UQ_UM_ROLE_PERMISSION UNIQUE (UM_PERMISSION_ID, UM_ROLE_NAME, UM_TENANT_ID, UM_DOMAIN_ID); +ALTER TABLE UM_ROLE_PERMISSION ADD CONSTRAINT UM_ROLE_PERMISSION_UM_DOMAIN FOREIGN KEY (UM_DOMAIN_ID, UM_TENANT_ID) REFERENCES UM_DOMAIN(UM_DOMAIN_ID, UM_TENANT_ID) ON DELETE CASCADE + + +INSERT INTO UM_DOMAIN (UM_DOMAIN_NAME, UM_TENANT_ID) VALUES ('PRIMARY', -1234); +INSERT INTO UM_DOMAIN (UM_DOMAIN_NAME, UM_TENANT_ID) VALUES ('SYSTEM', -1234); +INSERT INTO UM_DOMAIN (UM_DOMAIN_NAME, UM_TENANT_ID) VALUES ('INTERNAL', -1234); + + +INSERT INTO UM_DOMAIN (UM_TENANT_ID) SELECT UM_ID FROM UM_TENANT; +UPDATE UM_DOMAIN SET UM_DOMAIN_NAME = 'PRIMARY' WHERE UM_DOMAIN_NAME IS NULL AND UM_TENANT_ID IN (SELECT UM_ID FROM UM_TENANT); + +INSERT INTO UM_DOMAIN (UM_TENANT_ID) SELECT UM_ID FROM UM_TENANT; +UPDATE UM_DOMAIN SET UM_DOMAIN_NAME = 'SYSTEM' WHERE UM_DOMAIN_NAME IS NULL AND UM_TENANT_ID IN (SELECT UM_ID FROM UM_TENANT); + +INSERT INTO UM_DOMAIN (UM_TENANT_ID) SELECT UM_ID FROM UM_TENANT; +UPDATE UM_DOMAIN SET UM_DOMAIN_NAME = 'INTERNAL' WHERE UM_DOMAIN_NAME IS NULL AND UM_TENANT_ID IN (SELECT UM_ID FROM UM_TENANT); + + +UPDATE UM_ROLE_PERMISSION SET UM_ROLE_PERMISSION.UM_DOMAIN_ID = UM_DOMAIN.UM_DOMAIN_ID FROM UM_ROLE_PERMISSION INNER JOIN UM_DOMAIN ON +UM_DOMAIN.UM_TENANT_ID = UM_ROLE_PERMISSION.UM_TENANT_ID WHERE UM_ROLE_PERMISSION.UM_DOMAIN_ID IS NULL AND UM_DOMAIN.UM_DOMAIN_NAME = 'PRIMARY'; + + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[dbo].[UM_SHARED_USER_ROLE]') AND TYPE IN (N'U')) +CREATE TABLE UM_SHARED_USER_ROLE( + UM_ROLE_ID INTEGER NOT NULL, + UM_USER_ID INTEGER NOT NULL, + UM_USER_TENANT_ID INTEGER NOT NULL, + UM_ROLE_TENANT_ID INTEGER NOT NULL, + UNIQUE(UM_USER_ID,UM_ROLE_ID,UM_USER_TENANT_ID, UM_ROLE_TENANT_ID), + FOREIGN KEY(UM_ROLE_ID,UM_ROLE_TENANT_ID) REFERENCES UM_ROLE(UM_ID,UM_TENANT_ID) ON DELETE CASCADE , + FOREIGN KEY(UM_USER_ID,UM_USER_TENANT_ID) REFERENCES UM_USER(UM_ID,UM_TENANT_ID) ON DELETE CASCADE +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[dbo].[UM_ACCOUNT_MAPPING]') AND TYPE IN (N'U')) +CREATE TABLE UM_ACCOUNT_MAPPING( + UM_ID INTEGER IDENTITY(1,1), + UM_USER_NAME VARCHAR(255) NOT NULL, + UM_TENANT_ID INTEGER NOT NULL, + UM_USER_STORE_DOMAIN VARCHAR(100), + UM_ACC_LINK_ID INTEGER NOT NULL, + UNIQUE(UM_USER_NAME, UM_TENANT_ID, UM_USER_STORE_DOMAIN, UM_ACC_LINK_ID), + FOREIGN KEY (UM_TENANT_ID) REFERENCES UM_TENANT(UM_ID) ON DELETE CASCADE, + PRIMARY KEY (UM_ID) +); + + +ALTER TABLE UM_CLAIM ADD UM_MAPPED_ATTRIBUTE_DOMAIN VARCHAR(255); +ALTER TABLE UM_CLAIM ADD UM_CHECKED_ATTRIBUTE SMALLINT; +ALTER TABLE UM_CLAIM ADD UM_READ_ONLY SMALLINT; +ALTER TABLE UM_CLAIM ADD CONSTRAINT UQ_UM_CLAIM UNIQUE(UM_DIALECT_ID, UM_CLAIM_URI, UM_TENANT_ID,UM_MAPPED_ATTRIBUTE_DOMAIN); + +declare @Command1 nvarchar(1000); +select @Command1 = +'ALTER TABLE UM_HYBRID_USER_ROLE DROP CONSTRAINT ' + k.name from sys.tables t join sys.key_constraints k on t.object_id = k.parent_object_id where t.name = 'UM_HYBRID_USER_ROLE' and k.name like 'UQ%'; +EXECUTE(@command1); + +ALTER TABLE UM_HYBRID_USER_ROLE ADD UM_DOMAIN_ID INTEGER; +ALTER TABLE UM_HYBRID_USER_ROLE ADD CONSTRAINT UM_HYBRID_USER_ROLE_UM_DOMAIN FOREIGN KEY (UM_DOMAIN_ID, UM_TENANT_ID) REFERENCES UM_DOMAIN(UM_DOMAIN_ID, UM_TENANT_ID) ON DELETE CASCADE; +ALTER TABLE UM_HYBRID_USER_ROLE ADD CONSTRAINT UQ_UM_HYBRID_USER_ROLE UNIQUE (UM_USER_NAME, UM_ROLE_ID, UM_TENANT_ID, UM_DOMAIN_ID); + + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[dbo].[UM_SYSTEM_ROLE]') AND TYPE IN (N'U')) +CREATE TABLE UM_SYSTEM_ROLE( + UM_ID INTEGER IDENTITY(1, 1) NOT NULL, + UM_ROLE_NAME VARCHAR(255), + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_ID, UM_TENANT_ID) +); + +-- create table UM_SYSTEM_USER_ROLE +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[dbo].[UM_SYSTEM_USER_ROLE]') AND TYPE IN (N'U')) +CREATE TABLE UM_SYSTEM_USER_ROLE( + UM_ID INTEGER IDENTITY(1, 1), + UM_USER_NAME VARCHAR(255), + UM_ROLE_ID INTEGER NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + UNIQUE (UM_USER_NAME, UM_ROLE_ID, UM_TENANT_ID), + FOREIGN KEY (UM_ROLE_ID, UM_TENANT_ID) REFERENCES UM_SYSTEM_ROLE(UM_ID, UM_TENANT_ID), + PRIMARY KEY (UM_ID, UM_TENANT_ID) +); diff --git a/modules/distribution/resources/migration-1.4.0_to_1.5.0/userstore_db/mysql.sql b/modules/distribution/resources/migration-1.4.0_to_1.5.0/userstore_db/mysql.sql new file mode 100644 index 0000000000..b2768c0d8f --- /dev/null +++ b/modules/distribution/resources/migration-1.4.0_to_1.5.0/userstore_db/mysql.sql @@ -0,0 +1,143 @@ +CREATE TABLE UM_DOMAIN( + UM_DOMAIN_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_DOMAIN_NAME VARCHAR(255), + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_DOMAIN_ID, UM_TENANT_ID) +)ENGINE INNODB; + +CREATE TABLE UM_SYSTEM_USER ( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_USER_NAME VARCHAR(255) NOT NULL, + UM_USER_PASSWORD VARCHAR(255) NOT NULL, + UM_SALT_VALUE VARCHAR(31), + UM_REQUIRE_CHANGE BOOLEAN DEFAULT FALSE, + UM_CHANGED_TIME TIMESTAMP NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_ID, UM_TENANT_ID), + UNIQUE(UM_USER_NAME, UM_TENANT_ID) +)ENGINE INNODB; + +ALTER TABLE UM_ROLE ADD COLUMN UM_SHARED_ROLE BOOLEAN DEFAULT FALSE; + +CREATE TABLE UM_MODULE( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_MODULE_NAME VARCHAR(100), + UNIQUE(UM_MODULE_NAME), + PRIMARY KEY(UM_ID) +)ENGINE INNODB; + +CREATE TABLE UM_MODULE_ACTIONS( + UM_ACTION VARCHAR(255) NOT NULL, + UM_MODULE_ID INTEGER NOT NULL, + PRIMARY KEY(UM_ACTION, UM_MODULE_ID), + FOREIGN KEY (UM_MODULE_ID) REFERENCES UM_MODULE(UM_ID) ON DELETE CASCADE +)ENGINE INNODB; + +ALTER TABLE UM_PERMISSION ADD COLUMN UM_MODULE_ID INTEGER DEFAULT 0; +ALTER TABLE UM_ROLE_PERMISSION ADD COLUMN UM_DOMAIN_ID INTEGER; +ALTER TABLE UM_ROLE_PERMISSION ADD CONSTRAINT UNIQUE (UM_PERMISSION_ID, UM_ROLE_NAME, UM_TENANT_ID, UM_DOMAIN_ID); +ALTER TABLE UM_ROLE_PERMISSION ADD CONSTRAINT FOREIGN KEY (UM_DOMAIN_ID, UM_TENANT_ID) REFERENCES UM_DOMAIN(UM_DOMAIN_ID, UM_TENANT_ID) ON DELETE CASCADE; + + +INSERT INTO UM_DOMAIN (UM_DOMAIN_NAME, UM_TENANT_ID) VALUES ('PRIMARY', -1234); +INSERT INTO UM_DOMAIN (UM_DOMAIN_NAME, UM_TENANT_ID) VALUES ('SYSTEM', -1234); +INSERT INTO UM_DOMAIN (UM_DOMAIN_NAME, UM_TENANT_ID) VALUES ('INTERNAL', -1234); + + +INSERT INTO UM_DOMAIN (UM_TENANT_ID) SELECT UM_ID FROM UM_TENANT; +UPDATE UM_DOMAIN SET UM_DOMAIN_NAME = 'SYSTEM' WHERE UM_DOMAIN_NAME IS NULL AND UM_TENANT_ID IN (SELECT UM_ID FROM UM_TENANT); + +INSERT INTO UM_DOMAIN (UM_TENANT_ID) SELECT UM_ID FROM UM_TENANT; +UPDATE UM_DOMAIN SET UM_DOMAIN_NAME = 'INTERNAL' WHERE UM_DOMAIN_NAME IS NULL AND UM_TENANT_ID IN (SELECT UM_ID FROM UM_TENANT); + +INSERT INTO UM_DOMAIN (UM_TENANT_ID) SELECT UM_ID FROM UM_TENANT; +UPDATE UM_DOMAIN SET UM_DOMAIN_NAME = 'PRIMARY' WHERE UM_DOMAIN_NAME IS NULL AND UM_TENANT_ID IN (SELECT UM_ID FROM UM_TENANT); + +/** +SYSTEM +INTERNAL +PRIMARY +**/ + +UPDATE UM_ROLE_PERMISSION, UM_DOMAIN SET UM_ROLE_PERMISSION.UM_DOMAIN_ID = UM_DOMAIN.UM_DOMAIN_ID +WHERE UM_DOMAIN.UM_TENANT_ID = UM_ROLE_PERMISSION.UM_TENANT_ID AND UM_ROLE_PERMISSION.UM_DOMAIN_ID IS NULL AND UM_DOMAIN.UM_DOMAIN_NAME = 'PRIMARY'; + +UPDATE UM_ROLE_PERMISSION, UM_DOMAIN SET UM_ROLE_PERMISSION.UM_DOMAIN_ID = UM_DOMAIN.UM_DOMAIN_ID +WHERE UM_DOMAIN.UM_TENANT_ID = UM_ROLE_PERMISSION.UM_TENANT_ID AND UM_ROLE_PERMISSION.UM_ROLE_NAME = 'everyone' AND UM_DOMAIN.UM_DOMAIN_NAME = 'INTERNAL'; + +UPDATE UM_ROLE_PERMISSION, UM_DOMAIN SET UM_ROLE_PERMISSION.UM_DOMAIN_ID = UM_DOMAIN.UM_DOMAIN_ID +WHERE UM_DOMAIN.UM_TENANT_ID = UM_ROLE_PERMISSION.UM_TENANT_ID AND UM_ROLE_PERMISSION.UM_ROLE_NAME = 'wso2.anonymous.role' AND UM_DOMAIN.UM_DOMAIN_NAME = 'SYSTEM' ; + +CREATE TABLE UM_SHARED_USER_ROLE( + UM_ROLE_ID INTEGER NOT NULL, + UM_USER_ID INTEGER NOT NULL, + UM_USER_TENANT_ID INTEGER NOT NULL, + UM_ROLE_TENANT_ID INTEGER NOT NULL, + UNIQUE(UM_USER_ID,UM_ROLE_ID,UM_USER_TENANT_ID, UM_ROLE_TENANT_ID), + FOREIGN KEY(UM_ROLE_ID,UM_ROLE_TENANT_ID) REFERENCES UM_ROLE(UM_ID,UM_TENANT_ID) ON DELETE CASCADE, + FOREIGN KEY(UM_USER_ID,UM_USER_TENANT_ID) REFERENCES UM_USER(UM_ID,UM_TENANT_ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE UM_ACCOUNT_MAPPING( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_USER_NAME VARCHAR(255) NOT NULL, + UM_TENANT_ID INTEGER NOT NULL, + UM_USER_STORE_DOMAIN VARCHAR(100), + UM_ACC_LINK_ID INTEGER NOT NULL, + UNIQUE(UM_USER_NAME, UM_TENANT_ID, UM_USER_STORE_DOMAIN, UM_ACC_LINK_ID), + FOREIGN KEY (UM_TENANT_ID) REFERENCES UM_TENANT(UM_ID) ON DELETE CASCADE, + PRIMARY KEY (UM_ID) +)ENGINE INNODB; + + +ALTER TABLE UM_CLAIM ADD COLUMN UM_MAPPED_ATTRIBUTE_DOMAIN VARCHAR(255); +ALTER TABLE UM_CLAIM ADD COLUMN UM_CHECKED_ATTRIBUTE SMALLINT; +ALTER TABLE UM_CLAIM ADD COLUMN UM_READ_ONLY SMALLINT; + + +SELECT DATABASE() into @db FROM DUAL; + +select CONSTRAINT_NAME +INTO @myvar from +INFORMATION_SCHEMA.TABLE_CONSTRAINTS where TABLE_NAME = 'UM_CLAIM' and CONSTRAINT_TYPE = +'UNIQUE' and TABLE_SCHEMA = @db; + +SET @STMT = CONCAT(' ALTER TABLE UM_CLAIM DROP INDEX ', @myvar); +PREPARE STMT2 FROM @STMT; +EXECUTE STMT2; + + +ALTER TABLE UM_CLAIM ADD CONSTRAINT UNIQUE(UM_DIALECT_ID, UM_CLAIM_URI, UM_TENANT_ID,UM_MAPPED_ATTRIBUTE_DOMAIN); + +DROP TABLE IF EXISTS UM_CLAIM_BEHAVIOR; + +ALTER TABLE UM_HYBRID_USER_ROLE ADD COLUMN UM_DOMAIN_ID INTEGER; + +select CONSTRAINT_NAME +INTO @myvar2 from +INFORMATION_SCHEMA.TABLE_CONSTRAINTS where TABLE_NAME = 'UM_HYBRID_USER_ROLE' and CONSTRAINT_TYPE = +'UNIQUE' and TABLE_SCHEMA = @db; + +SET @STMT1 = CONCAT(' ALTER TABLE UM_HYBRID_USER_ROLE DROP INDEX ', @myvar2); +PREPARE STMT3 FROM @STMT1; +EXECUTE STMT3; + +ALTER TABLE UM_HYBRID_USER_ROLE ADD CONSTRAINT UNIQUE (UM_USER_NAME, UM_ROLE_ID, UM_TENANT_ID, UM_DOMAIN_ID); +ALTER TABLE UM_HYBRID_USER_ROLE ADD CONSTRAINT FOREIGN KEY (UM_DOMAIN_ID, UM_TENANT_ID) REFERENCES UM_DOMAIN(UM_DOMAIN_ID, UM_TENANT_ID) ON DELETE CASCADE; + +CREATE TABLE UM_SYSTEM_ROLE( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_ROLE_NAME VARCHAR(255), + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_ID, UM_TENANT_ID) +)ENGINE INNODB; + +CREATE TABLE UM_SYSTEM_USER_ROLE( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_USER_NAME VARCHAR(255), + UM_ROLE_ID INTEGER NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + UNIQUE (UM_USER_NAME, UM_ROLE_ID, UM_TENANT_ID), + FOREIGN KEY (UM_ROLE_ID, UM_TENANT_ID) REFERENCES UM_SYSTEM_ROLE(UM_ID, UM_TENANT_ID), + PRIMARY KEY (UM_ID, UM_TENANT_ID) +)ENGINE INNODB; diff --git a/modules/distribution/resources/migration-1.4.0_to_1.5.0/userstore_db/oracle.sql b/modules/distribution/resources/migration-1.4.0_to_1.5.0/userstore_db/oracle.sql new file mode 100644 index 0000000000..1ca3838b02 --- /dev/null +++ b/modules/distribution/resources/migration-1.4.0_to_1.5.0/userstore_db/oracle.sql @@ -0,0 +1,230 @@ + +CREATE TABLE UM_DOMAIN( + UM_DOMAIN_ID INTEGER, + UM_DOMAIN_NAME VARCHAR(255), + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_DOMAIN_ID, UM_TENANT_ID) +); + + +CREATE SEQUENCE UM_DOMAIN_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE; + +CREATE OR REPLACE TRIGGER UM_DOMAIN_TRIGGER + BEFORE INSERT + ON UM_DOMAIN + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT UM_DOMAIN_SEQUENCE.nextval INTO :NEW.UM_DOMAIN_ID FROM dual; + END; +/ + + + +CREATE TABLE UM_SYSTEM_USER ( + UM_ID INTEGER, + UM_USER_NAME VARCHAR(255) NOT NULL, + UM_USER_PASSWORD VARCHAR(255) NOT NULL, + UM_SALT_VALUE VARCHAR(31), + UM_REQUIRE_CHANGE NUMBER(1) DEFAULT 0, + UM_CHANGED_TIME TIMESTAMP NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_ID, UM_TENANT_ID), + UNIQUE(UM_USER_NAME, UM_TENANT_ID)); + +CREATE SEQUENCE UM_SYSTEM_USER_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE; + +CREATE OR REPLACE TRIGGER UM_SYSTEM_USER_TRIGGER + BEFORE INSERT + ON UM_SYSTEM_USER + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT UM_SYSTEM_USER_SEQUENCE.nextval INTO :NEW.UM_ID FROM dual; + END; +/ +ALTER TABLE UM_ROLE ADD UM_SHARED_ROLE CHAR(1) DEFAULT 0; + + + +CREATE TABLE UM_MODULE( + UM_ID INTEGER, + UM_MODULE_NAME VARCHAR(100), + UNIQUE(UM_MODULE_NAME), + PRIMARY KEY(UM_ID) +); + +CREATE SEQUENCE UM_MODULE_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE; + +CREATE OR REPLACE TRIGGER UM_MODULE_TRIGGER + BEFORE INSERT + ON UM_MODULE + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT UM_MODULE_SEQUENCE.nextval INTO :NEW.UM_ID FROM dual; + END; +/ +CREATE TABLE UM_MODULE_ACTIONS( + UM_ACTION VARCHAR(255) NOT NULL, + UM_MODULE_ID INTEGER NOT NULL, + PRIMARY KEY(UM_ACTION, UM_MODULE_ID), + FOREIGN KEY (UM_MODULE_ID) REFERENCES UM_MODULE(UM_ID) ON DELETE CASCADE +); + +ALTER TABLE UM_PERMISSION ADD UM_MODULE_ID INTEGER DEFAULT 0; + + +ALTER TABLE UM_ROLE_PERMISSION ADD UM_DOMAIN_ID INTEGER; +/ +begin + for r in (select table_name, constraint_name + from user_constraints + where constraint_type = 'U' and table_name = 'UM_ROLE_PERMISSION') + loop + execute immediate 'alter table '||r.table_name + ||' drop constraint '||r.constraint_name; + end loop; +end loop; +/ +ALTER TABLE UM_ROLE_PERMISSION ADD CONSTRAINT UQ_UM_ROLE_PERMISSION UNIQUE (UM_PERMISSION_ID, UM_ROLE_NAME, UM_TENANT_ID, UM_DOMAIN_ID); +ALTER TABLE UM_ROLE_PERMISSION ADD CONSTRAINT UM_ROLE_PERMISSION_UM_DOMAIN FOREIGN KEY (UM_DOMAIN_ID, UM_TENANT_ID) REFERENCES UM_DOMAIN(UM_DOMAIN_ID, UM_TENANT_ID) ON DELETE CASCADE; + +INSERT INTO UM_DOMAIN (UM_DOMAIN_NAME, UM_TENANT_ID) VALUES ('PRIMARY', -1234); +INSERT INTO UM_DOMAIN (UM_DOMAIN_NAME, UM_TENANT_ID) VALUES ('SYSTEM', -1234); +INSERT INTO UM_DOMAIN (UM_DOMAIN_NAME, UM_TENANT_ID) VALUES ('INTERNAL', -1234); + + +INSERT INTO UM_DOMAIN (UM_TENANT_ID) SELECT UM_ID FROM UM_TENANT; +UPDATE UM_DOMAIN SET UM_DOMAIN_NAME = 'SYSTEM' WHERE UM_DOMAIN_NAME IS NULL AND UM_TENANT_ID IN (SELECT UM_ID FROM UM_TENANT); + +INSERT INTO UM_DOMAIN (UM_TENANT_ID) SELECT UM_ID FROM UM_TENANT; +UPDATE UM_DOMAIN SET UM_DOMAIN_NAME = 'INTERNAL' WHERE UM_DOMAIN_NAME IS NULL AND UM_TENANT_ID IN (SELECT UM_ID FROM UM_TENANT); + +INSERT INTO UM_DOMAIN (UM_TENANT_ID) SELECT UM_ID FROM UM_TENANT; +UPDATE UM_DOMAIN SET UM_DOMAIN_NAME = 'PRIMARY' WHERE UM_DOMAIN_NAME IS NULL AND UM_TENANT_ID IN (SELECT UM_ID FROM UM_TENANT); + +/** +SYSTEM +INTERNAL +PRIMARY +**/ + +UPDATE UM_ROLE_PERMISSION SET UM_ROLE_PERMISSION.UM_DOMAIN_ID = (SELECT UM_DOMAIN.UM_DOMAIN_ID FROM UM_DOMAIN WHERE UM_DOMAIN.UM_TENANT_ID = UM_ROLE_PERMISSION.UM_TENANT_ID AND UM_ROLE_PERMISSION.UM_DOMAIN_ID IS NULL AND UM_DOMAIN.UM_DOMAIN_NAME = 'PRIMARY') WHERE UM_ROLE_PERMISSION.UM_DOMAIN_ID IS NULL; + +UPDATE UM_ROLE_PERMISSION SET UM_ROLE_PERMISSION.UM_DOMAIN_ID = (SELECT UM_DOMAIN.UM_DOMAIN_ID FROM UM_DOMAIN WHERE UM_DOMAIN.UM_TENANT_ID = UM_ROLE_PERMISSION.UM_TENANT_ID AND UM_ROLE_PERMISSION.UM_ROLE_NAME = 'everyone' AND UM_DOMAIN.UM_DOMAIN_NAME = 'INTERNAL') WHERE UM_ROLE_PERMISSION.UM_ROLE_NAME = 'everyone'; + +UPDATE UM_ROLE_PERMISSION SET UM_ROLE_PERMISSION.UM_DOMAIN_ID = (SELECT UM_DOMAIN.UM_DOMAIN_ID FROM UM_DOMAIN WHERE UM_DOMAIN.UM_TENANT_ID = UM_ROLE_PERMISSION.UM_TENANT_ID AND UM_ROLE_PERMISSION.UM_ROLE_NAME = 'wso2.anonymous.role' AND UM_DOMAIN.UM_DOMAIN_NAME = 'SYSTEM') WHERE UM_ROLE_PERMISSION.UM_ROLE_NAME = 'wso2.anonymous.role'; + +CREATE TABLE UM_SHARED_USER_ROLE( + UM_ROLE_ID INTEGER NOT NULL, + UM_USER_ID INTEGER NOT NULL, + UM_USER_TENANT_ID INTEGER NOT NULL, + UM_ROLE_TENANT_ID INTEGER NOT NULL, + UNIQUE(UM_USER_ID,UM_ROLE_ID,UM_USER_TENANT_ID, UM_ROLE_TENANT_ID), + FOREIGN KEY(UM_ROLE_ID,UM_ROLE_TENANT_ID) REFERENCES UM_ROLE(UM_ID,UM_TENANT_ID) ON DELETE CASCADE , + FOREIGN KEY(UM_USER_ID,UM_USER_TENANT_ID) REFERENCES UM_USER(UM_ID,UM_TENANT_ID) ON DELETE CASCADE +); + +CREATE TABLE UM_ACCOUNT_MAPPING( + UM_ID INTEGER, + UM_USER_NAME VARCHAR(255) NOT NULL, + UM_TENANT_ID INTEGER NOT NULL, + UM_USER_STORE_DOMAIN VARCHAR(100), + UM_ACC_LINK_ID INTEGER NOT NULL, + UNIQUE(UM_USER_NAME, UM_TENANT_ID, UM_USER_STORE_DOMAIN, UM_ACC_LINK_ID), + FOREIGN KEY (UM_TENANT_ID) REFERENCES UM_TENANT(UM_ID) ON DELETE CASCADE, + PRIMARY KEY (UM_ID) +); + +CREATE SEQUENCE UM_ACCOUNT_MAPPING_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE; +CREATE OR REPLACE TRIGGER UM_ACCOUNT_MAPPING_TRIGGER + BEFORE INSERT + ON UM_ACCOUNT_MAPPING + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT UM_ACCOUNT_MAPPING_SEQUENCE.nextval INTO :NEW.UM_ID FROM dual; + END; +/ + +ALTER TABLE UM_CLAIM ADD UM_MAPPED_ATTRIBUTE_DOMAIN VARCHAR(255); +ALTER TABLE UM_CLAIM ADD UM_CHECKED_ATTRIBUTE SMALLINT; +ALTER TABLE UM_CLAIM ADD UM_READ_ONLY SMALLINT; +/ + + +begin + for r in (select table_name, constraint_name + from user_constraints + where constraint_type = 'U' and table_name = 'UM_CLAIM') + loop + execute immediate 'alter table '||r.table_name + ||' drop constraint '||r.constraint_name; + end loop; +end loop; +/ +ALTER TABLE UM_CLAIM ADD CONSTRAINT UQ_UM_CLAIM UNIQUE(UM_DIALECT_ID, UM_CLAIM_URI, UM_MAPPED_ATTRIBUTE_DOMAIN, UM_TENANT_ID); + + +ALTER TABLE UM_HYBRID_USER_ROLE ADD UM_DOMAIN_ID INTEGER; + +/ + +begin + for r in (select table_name, constraint_name + from user_constraints + where constraint_type = 'U' and table_name = 'UM_HYBRID_USER_ROLE') + loop + execute immediate 'alter table '||r.table_name + ||' drop constraint '||r.constraint_name; + end loop; +end loop; +/ + +ALTER TABLE UM_HYBRID_USER_ROLE ADD CONSTRAINT HYBRID_ROLE_DOMAIN FOREIGN KEY (UM_DOMAIN_ID, UM_TENANT_ID) REFERENCES UM_DOMAIN(UM_DOMAIN_ID,UM_TENANT_ID) ON DELETE CASCADE; +ALTER TABLE UM_HYBRID_USER_ROLE ADD CONSTRAINT UQ_UM_HYBRID_USER_ROLE UNIQUE (UM_USER_NAME, UM_ROLE_ID, UM_TENANT_ID, UM_DOMAIN_ID); + + + + + +CREATE TABLE UM_SYSTEM_ROLE( + UM_ID INTEGER, + UM_ROLE_NAME VARCHAR(255), + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_ID, UM_TENANT_ID) +); + +CREATE SEQUENCE UM_SYSTEM_ROLE_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE; +CREATE OR REPLACE TRIGGER UM_SYSTEM_ROLE_TRIGGER + BEFORE INSERT + ON UM_SYSTEM_ROLE + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT UM_SYSTEM_ROLE_SEQUENCE.nextval INTO :NEW.UM_ID FROM dual; + END; +/ + + +CREATE TABLE UM_SYSTEM_USER_ROLE( + UM_ID INTEGER, + UM_USER_NAME VARCHAR(255), + UM_ROLE_ID INTEGER NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + UNIQUE (UM_USER_NAME, UM_ROLE_ID, UM_TENANT_ID), + FOREIGN KEY (UM_ROLE_ID, UM_TENANT_ID) REFERENCES UM_SYSTEM_ROLE(UM_ID, UM_TENANT_ID), + PRIMARY KEY (UM_ID, UM_TENANT_ID) +); + +CREATE SEQUENCE UM_SYSTEM_USER_ROLE_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE; +CREATE OR REPLACE TRIGGER UM_SYSTEM_USER_ROLE_TRIGGER + BEFORE INSERT + ON UM_SYSTEM_USER_ROLE + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT UM_SYSTEM_USER_ROLE_SEQUENCE.nextval INTO :NEW.UM_ID FROM dual; + END; +/ diff --git a/modules/distribution/resources/migration-1.5.0_to_1.6.0/endpoint-migration/build.xml b/modules/distribution/resources/migration-1.5.0_to_1.6.0/endpoint-migration/build.xml new file mode 100644 index 0000000000..e3c6100542 --- /dev/null +++ b/modules/distribution/resources/migration-1.5.0_to_1.6.0/endpoint-migration/build.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/resources/migration-1.5.0_to_1.6.0/endpoint-migration/src/org/wso2/carbon/registry/migration/Main.java b/modules/distribution/resources/migration-1.5.0_to_1.6.0/endpoint-migration/src/org/wso2/carbon/registry/migration/Main.java new file mode 100644 index 0000000000..fe4c9a4445 --- /dev/null +++ b/modules/distribution/resources/migration-1.5.0_to_1.6.0/endpoint-migration/src/org/wso2/carbon/registry/migration/Main.java @@ -0,0 +1,134 @@ +/* +* Copyright (c) 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.carbon.registry.migration; + +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.sql.SQLException; + +import org.apache.axis2.context.ConfigurationContext; +import org.apache.axis2.context.ConfigurationContextFactory; +import org.json.simple.JSONObject; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.model.API; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact; +import org.wso2.carbon.governance.api.exception.GovernanceException; +import org.wso2.carbon.governance.api.generic.GenericArtifactManager; +import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact; +import org.wso2.carbon.governance.api.util.GovernanceUtils; +import org.wso2.carbon.registry.core.Registry; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import org.wso2.carbon.registry.core.session.UserRegistry; +import org.wso2.carbon.registry.migration.utils.CommandHandler; +import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient; + + +public class Main { + private static Registry registry; + static ConfigurationContext cc; + + + public static void main(String[] args) { + CommandHandler.setInputs(args); + try { + String trustStore = System.getProperty("carbon.home") + File.separator + "repository" + File.separator + + "resources" + File.separator + "security" + File.separator + "wso2carbon.jks"; + System.setProperty("javax.net.ssl.trustStore", trustStore); + System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon"); + System.setProperty("javax.net.ssl.trustStoreType", "JKS"); + System.setProperty("carbon.repo.write.mode", "true"); + + cc = ConfigurationContextFactory.createConfigurationContextFromFileSystem + (System.getProperty("carbon.home") + "repository/deployment/client", System.getProperty("carbon.home") + + "repository/conf/axis2/axis2_client.xml"); + registry = new WSRegistryServiceClient(CommandHandler.getServiceURL(), CommandHandler.getUsername(), + CommandHandler.getPassword(), cc); + Main.migrate(); + System.out.println("Finished API data migration process."); + System.exit(0); + } catch (RegistryException e) { + System.out.println("Error while connecting to registry." + e); + } catch (Exception e) { + System.out.println("Error while migrating data." + e); + } + + } + + private static void migrate() throws RegistryException, APIManagementException, SQLException, IOException { + Registry re = GovernanceUtils.getGovernanceUserRegistry(registry, CommandHandler.getUsername()); + GenericArtifactManager manager = new GenericArtifactManager(re, "api"); + GovernanceUtils.loadGovernanceArtifacts((UserRegistry) re); + GenericArtifact[] artifacts = manager.getAllGenericArtifacts(); + + for (GenericArtifact artifact : artifacts) { + API api = getAPI(artifact, re); + + JSONObject endpoint_config = new JSONObject(); + + JSONObject production_config = new JSONObject(); + production_config.put("url", api.getUrl()); + + JSONObject sandbox_config = new JSONObject(); + sandbox_config.put("url", api.getSandboxUrl()); + + if (api.getUrl() != null && !api.getUrl().equals("")) { + endpoint_config.put("production_endpoints", production_config); + } + + if (api.getSandboxUrl() != null && !api.getSandboxUrl().equals("")) { + endpoint_config.put("sandbox_endpoints", sandbox_config); + } + endpoint_config.put("endpoint_type", "http"); + + StringWriter out = new StringWriter(); + endpoint_config.writeJSONString(out); + String endpoint_config_text = out.toString(); + artifact.setAttribute("overview_endpointConfig", endpoint_config_text); + manager.updateGenericArtifact(artifact); + } + + } + + public static API getAPI(GovernanceArtifact artifact, Registry registry) + throws APIManagementException, SQLException { + + API api; + try { + String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER); + String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME); + String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION); + APIIdentifier apiId=new APIIdentifier(providerName, apiName, apiVersion); + api = new API(apiId); + + api.setUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_URL)); + api.setSandboxUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_SANDBOX_URL)); + + + } catch (GovernanceException e) { + String msg = "Failed to get API fro artifact "; + throw new APIManagementException(msg, e); + } + return api; + } + +} + diff --git a/modules/distribution/resources/migration-1.5.0_to_1.6.0/endpoint-migration/src/org/wso2/carbon/registry/migration/utils/CommandHandler.java b/modules/distribution/resources/migration-1.5.0_to_1.6.0/endpoint-migration/src/org/wso2/carbon/registry/migration/utils/CommandHandler.java new file mode 100644 index 0000000000..225f230f4a --- /dev/null +++ b/modules/distribution/resources/migration-1.5.0_to_1.6.0/endpoint-migration/src/org/wso2/carbon/registry/migration/utils/CommandHandler.java @@ -0,0 +1,121 @@ +/* +* Copyright (c) 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.carbon.registry.migration.utils; + +import java.util.HashMap; +import java.util.Map; + +public class CommandHandler { + + private static final Map inputs = new HashMap(); + + public static boolean setInputs(String[] arguments) { + + if (arguments.length == 0) { + printMessage(); + return false; + } + if (arguments.length == 1 && arguments[0].equals("--help")) { + printMessage(); + return false; + } + + // now loop through the arguments list to capture the options + for (int i = 0; i < arguments.length; i++) { + if (arguments[i].equals("-h")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Hostname of the registry is missing"); + } + inputs.put("-h", arguments[++i]); + + } else if (arguments[i].equals("-p")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Port of the registry is missing"); + } + inputs.put("-p", arguments[++i]); + + } else if (arguments[i].equals("-u")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Username of the admin is missing"); + } + inputs.put("-u", arguments[++i]); + + } else if (arguments[i].equals("-pw")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Password of the admin is missing"); + } + inputs.put("-pw", arguments[++i]); + } else if (arguments[i].equals("-cr")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Context root of the service is missing"); + } + inputs.put("-cr", arguments[++i]); + } + } + + return true; + } + + + private static void printMessage() { + System.out.println("Usage: migration-client "); + System.out.println("Valid options are:"); + System.out.println("\t-h :\t(Required) The hostname/ip of the registry to login."); + System.out.println("\t-p :\t(Required) The port of the registry to login."); + System.out.println("\t-u :\t(Required) The user name of the registry login."); + System.out.println("\t-pw:\t(Required) The password of the registry login."); + System.out.println(); + System.out.println("Example to migrate a registry running on localhost on default values"); + System.out.println("\te.g: migration-client -h localhost -p 9443 -u admin -pw admin"); + } + + public static String getRegistryURL() { + String contextRoot = inputs.get("-cr"); + + if (contextRoot == null) { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/registry/"; + } else { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/" + contextRoot + "/registry/"; + } + } + + public static String getHost() { + return inputs.get("-h"); + } + + public static String getServiceURL() { + String contextRoot = inputs.get("-cr"); + + if (contextRoot == null) { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/services/"; + } else { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/" + contextRoot + "/services/"; + } + } + + public static String getUsername() { + return inputs.get("-u"); + } + + public static String getPassword() { + return inputs.get("-pw"); + } + + +} + diff --git a/modules/distribution/resources/migration-1.5.0_to_1.6.0/h2.sql b/modules/distribution/resources/migration-1.5.0_to_1.6.0/h2.sql new file mode 100644 index 0000000000..a81a5538b2 --- /dev/null +++ b/modules/distribution/resources/migration-1.5.0_to_1.6.0/h2.sql @@ -0,0 +1,16 @@ +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, + 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) +); + +ALTER TABLE AM_APPLICATION ADD APPLICATION_STATUS varchar(50) DEFAULT 'APPROVED'; diff --git a/modules/distribution/resources/migration-1.5.0_to_1.6.0/mssql.sql b/modules/distribution/resources/migration-1.5.0_to_1.6.0/mssql.sql new file mode 100644 index 0000000000..d3a5778c6b --- /dev/null +++ b/modules/distribution/resources/migration-1.5.0_to_1.6.0/mssql.sql @@ -0,0 +1,15 @@ +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, + WF_UPDATED_TIME DATETIME, + WF_STATUS_DESC VARCHAR(1000), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + WF_EXTERNAL_REFERENCE VARCHAR(255) NOT NULL UNIQUE, + PRIMARY KEY (WF_ID) +); + +ALTER TABLE AM_APPLICATION ADD APPLICATION_STATUS VARCHAR(50) DEFAULT 'APPROVED'; diff --git a/modules/distribution/resources/migration-1.5.0_to_1.6.0/mysql.sql b/modules/distribution/resources/migration-1.5.0_to_1.6.0/mysql.sql new file mode 100644 index 0000000000..960ce0c8ab --- /dev/null +++ b/modules/distribution/resources/migration-1.5.0_to_1.6.0/mysql.sql @@ -0,0 +1,16 @@ +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, + 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; + +ALTER TABLE AM_APPLICATION ADD APPLICATION_STATUS VARCHAR(50) DEFAULT 'APPROVED'; diff --git a/modules/distribution/resources/migration-1.5.0_to_1.6.0/oracle.sql b/modules/distribution/resources/migration-1.5.0_to_1.6.0/oracle.sql new file mode 100644 index 0000000000..74dbcd44ce --- /dev/null +++ b/modules/distribution/resources/migration-1.5.0_to_1.6.0/oracle.sql @@ -0,0 +1,30 @@ +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, + WF_UPDATED_TIME 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 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; +/ + +ALTER TABLE AM_APPLICATION ADD APPLICATION_STATUS VARCHAR2(50) DEFAULT 'APPROVED' +/ diff --git a/modules/distribution/resources/migration-1.5.0_to_1.6.0/postgresql.sql b/modules/distribution/resources/migration-1.5.0_to_1.6.0/postgresql.sql new file mode 100644 index 0000000000..65c6732b5b --- /dev/null +++ b/modules/distribution/resources/migration-1.5.0_to_1.6.0/postgresql.sql @@ -0,0 +1,18 @@ +CREATE SEQUENCE AM_WORKFLOWS_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE AM_WORKFLOWS( + WF_ID INTEGER DEFAULT nextval('am_worflows_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) +) +; + +ALTER TABLE AM_APPLICATION ADD APPLICATION_STATUS VARCHAR(50) DEFAULT 'APPROVED'; diff --git a/modules/distribution/resources/migration-1.5.0_to_1.6.0/rxt/api.rxt b/modules/distribution/resources/migration-1.5.0_to_1.6.0/rxt/api.rxt new file mode 100644 index 0000000000..56272e0b24 --- /dev/null +++ b/modules/distribution/resources/migration-1.5.0_to_1.6.0/rxt/api.rxt @@ -0,0 +1,201 @@ + + + /apimgt/applicationdata/provider/@{overview_provider}/@{overview_name}/@{overview_version}/api + overview_name + + + + + + + + + + + + + + + + + Provider + + + Name + + + Context + + + Version + + + Transports + + + Redirect URL + + + Advertise Only + + + API Owner + + + Description + + + Endpoint Type + + Secured + Non Secured + + + + Endpoint URL + + + Endpoint Config + + + Endpoint Username + + + Endpoint Password + + + Sandbox URL + + + InSequence + + + OutSequence + + + WSDL + + + WADL + + + Thumbnail + + + Visibility + + + Visible Roles + + + Visible Tenants + + + Is Latest + + false + true + + + + Tier + + Gold + Silver + Other + + + + Status + + CREATED + PUBLISHED + RETIRED + DEPRECATED + BLOCKED + + + + Technical Owner + + + Technical Owner Email + + + Business Owner + + + Business Owner Email + + + Subscription Availability + + + Tenants + + + Response Caching + + Enabled + Disabled + + + + Cache Timeout + +
    + + + URL Pattern + HTTP Verb + Auth Type + + + URL Pattern0 + + + HTTP Verb0 + + + Auth Type0 + + + URL Pattern1 + + + HTTP Verb1 + + + Auth Type1 + + + URL Pattern2 + + + HTTP Verb2 + + + Auth Type2 + + + URL Pattern3 + + + HTTP Verb3 + + + Auth Type3 + + + URL Pattern4 + + + HTTP Verb4 + + + Auth Type4 + +
    +
    + +
    diff --git a/modules/distribution/resources/migration-1.6.0_to_1.7.0/h2.sql b/modules/distribution/resources/migration-1.6.0_to_1.7.0/h2.sql new file mode 100644 index 0000000000..1f31517588 --- /dev/null +++ b/modules/distribution/resources/migration-1.6.0_to_1.7.0/h2.sql @@ -0,0 +1,371 @@ +ALTER TABLE IDN_OAUTH_CONSUMER_APPS DROP LOGIN_PAGE_URL; +ALTER TABLE IDN_OAUTH_CONSUMER_APPS DROP ERROR_PAGE_URL; +ALTER TABLE IDN_OAUTH_CONSUMER_APPS DROP CONSENT_PAGE_URL; + +ALTER TABLE IDN_OAUTH2_ACCESS_TOKEN ALTER TOKEN_SCOPE VARCHAR (2048); + +ALTER TABLE AM_API_URL_MAPPING ADD MEDIATION_SCRIPT BLOB DEFAULT NULL; + +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, + PRIMARY KEY (RESOURCE_PATH), + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) +); + +CREATE TABLE IF NOT EXISTS IDN_SCIM_GROUP ( + ID INTEGER GENERATED ALWAYS AS 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) +); + +CREATE TABLE IF NOT EXISTS IDN_SCIM_PROVIDER ( + CONSUMER_ID VARCHAR(255) NOT NULL, + PROVIDER_ID VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + USER_PASSWORD VARCHAR(255) NOT NULL, + USER_URL VARCHAR(1024) NOT NULL, + GROUP_URL VARCHAR(1024), + BULK_URL VARCHAR(1024), + PRIMARY KEY (CONSUMER_ID,PROVIDER_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_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', + 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) NOT NULL, + 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, + PRIMARY KEY (SESSION_ID) +); + +-- End of IDN Tables -- + + +-- Start of IDN-APPLICATION-MGT Tables-- + +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', + SUBJECT_CLAIM_URI VARCHAR (512), + IS_SAAS_APP 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_INBOUND_AUTH ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + INBOUND_AUTH_KEY VARCHAR (255) NOT NULL, + 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'); + +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); + +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, + PRIMARY KEY (ID), + UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME), + 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); + +-- End of IDN-APPLICATION-MGT Tables-- + +ALTER TABLE AM_APPLICATION_KEY_MAPPING ADD STATE VARCHAR(30) DEFAULT 'COMPLETED'; + +ALTER TABLE AM_APPLICATION_KEY_MAPPING DROP PRIMARY KEY; + +ALTER TABLE AM_APPLICATION_KEY_MAPPING ADD PRIMARY KEY(APPLICATION_ID,KEY_TYPE); + +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), + 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) +); + + diff --git a/modules/distribution/resources/migration-1.6.0_to_1.7.0/mysql.sql b/modules/distribution/resources/migration-1.6.0_to_1.7.0/mysql.sql new file mode 100644 index 0000000000..42302b64ca --- /dev/null +++ b/modules/distribution/resources/migration-1.6.0_to_1.7.0/mysql.sql @@ -0,0 +1,383 @@ +ALTER TABLE IDN_OAUTH_CONSUMER_APPS DROP LOGIN_PAGE_URL; +ALTER TABLE IDN_OAUTH_CONSUMER_APPS DROP ERROR_PAGE_URL; +ALTER TABLE IDN_OAUTH_CONSUMER_APPS DROP CONSENT_PAGE_URL; + +ALTER TABLE AM_API_URL_MAPPING ADD MEDIATION_SCRIPT BLOB DEFAULT NULL; + +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, + PRIMARY KEY (RESOURCE_PATH), + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) +)ENGINE INNODB; + +CREATE TABLE 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 IDN_SCIM_PROVIDER ( + CONSUMER_ID VARCHAR(255) NOT NULL, + PROVIDER_ID VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + USER_PASSWORD VARCHAR(255) NOT NULL, + USER_URL VARCHAR(1024) NOT NULL, + GROUP_URL VARCHAR(1024), + BULK_URL VARCHAR(1024), + PRIMARY KEY (CONSUMER_ID,PROVIDER_ID) +)ENGINE INNODB; + +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) +)ENGINE INNODB; + +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', + PRIMARY KEY (HANDLE) +)ENGINE INNODB; + +CREATE TABLE 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 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) NOT NULL, + PRIMARY KEY (TENANT_ID, USER_NAME, DATA_KEY) +)ENGINE INNODB; + +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) +)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, + PRIMARY KEY (SESSION_ID) +)ENGINE INNODB; + +-- End of IDN Tables -- + + +-- Start of IDN-APPLICATION-MGT Tables-- + +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', + SUBJECT_CLAIM_URI VARCHAR (512), + IS_SAAS_APP 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_INBOUND_AUTH ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + INBOUND_AUTH_KEY VARCHAR (255) NOT NULL, + 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'); + +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; + +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, + PRIMARY KEY (ID), + UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME), + 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; +-- End of IDN-APPLICATION-MGT Tables-- + +ALTER TABLE AM_APPLICATION_KEY_MAPPING ADD STATE VARCHAR(30) DEFAULT 'COMPLETED',; + +ALTER TABLE AM_APPLICATION_KEY_MAPPING DROP PRIMARY KEY, ADD PRIMARY KEY(APPLICATION_ID,KEY_TYPE); + +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), + 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) +); diff --git a/modules/distribution/resources/migration-1.6.0_to_1.7.0/rxt/api.rxt b/modules/distribution/resources/migration-1.6.0_to_1.7.0/rxt/api.rxt new file mode 100644 index 0000000000..213c150bf9 --- /dev/null +++ b/modules/distribution/resources/migration-1.6.0_to_1.7.0/rxt/api.rxt @@ -0,0 +1,238 @@ + + + /apimgt/applicationdata/provider/@{overview_provider}/@{overview_name}/@{overview_version}/api + overview_name + + + + + + + + + + + + + + + + + Provider + + + Name + + + Context + + + Version + + + Is Default Version + + false + true + + + + Transports + + + Redirect URL + + + Advertise Only + + + API Owner + + + Description + + + Endpoint Type + + Secured + Non Secured + + + + Endpoint URL + + + Implementation + + + Endpoint Config + + + Endpoint Username + + + Endpoint Password + + + Sandbox URL + + + InSequence + + + OutSequence + + + FaultSequence + + + WSDL + + + WADL + + + Thumbnail + + + Visibility + + + Visible Roles + + + Visible Tenants + + + Is Latest + + false + true + + + + Tier + + Gold + Silver + Other + + + + Status + + CREATED + PUBLISHED + PROTOTYPED + RETIRED + DEPRECATED + BLOCKED + + + + Technical Owner + + + Technical Owner Email + + + Business Owner + + + Business Owner Email + + + Subscription Availability + + + Tenants + + + Response Caching + + Enabled + Disabled + + + + Cache Timeout + + + Destination Stats Enabled + + Enabled + Disabled + + +
    + + + URL Pattern + HTTP Verb + Auth Type + Mediation Script + + + URL Pattern0 + + + HTTP Verb0 + + + Auth Type0 + + + Mediation Script0 + + + URL Pattern1 + + + HTTP Verb1 + + + Auth Type1 + + + Mediation Script1 + + + URL Pattern2 + + + HTTP Verb2 + + + Auth Type2 + + + Mediation Script2 + + + URL Pattern3 + + + HTTP Verb3 + + + Auth Type3 + + + Mediation Script3 + + + URL Pattern4 + + + HTTP Verb4 + + + Auth Type4 + + + Mediation Script4 + +
    +
    + +
    diff --git a/modules/distribution/resources/migration-1.6.0_to_1.7.0/rxt/documentation.rxt b/modules/distribution/resources/migration-1.6.0_to_1.7.0/rxt/documentation.rxt new file mode 100644 index 0000000000..1b6bc205d9 --- /dev/null +++ b/modules/distribution/resources/migration-1.6.0_to_1.7.0/rxt/documentation.rxt @@ -0,0 +1,63 @@ + + + /apimgt/applicationdata/provider/@{overview_apiBasePath}/documentation/@{overview_name} + overview_name + + + + + + + + + + + Name + + + ApiBasePath + + + Summary + + + ApiBasePath + + + Type + + How To + Samples and SDK + Public Forum + Support Forum + API Message Formats + Other + + + + Source Type + + In Line + URL + File + + + + Visibility + + API_Level + Private + Shared + + + + Source URL + + + File Path + +
    +
    + +
    + diff --git a/modules/distribution/resources/migration-1.6.0_to_1.7.0/swagger-resource-migration/build.xml b/modules/distribution/resources/migration-1.6.0_to_1.7.0/swagger-resource-migration/build.xml new file mode 100644 index 0000000000..e3c6100542 --- /dev/null +++ b/modules/distribution/resources/migration-1.6.0_to_1.7.0/swagger-resource-migration/build.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/resources/migration-1.6.0_to_1.7.0/swagger-resource-migration/src/org/wso2/carbon/registry/migration/Main.java b/modules/distribution/resources/migration-1.6.0_to_1.7.0/swagger-resource-migration/src/org/wso2/carbon/registry/migration/Main.java new file mode 100644 index 0000000000..5a5f6e3c36 --- /dev/null +++ b/modules/distribution/resources/migration-1.6.0_to_1.7.0/swagger-resource-migration/src/org/wso2/carbon/registry/migration/Main.java @@ -0,0 +1,188 @@ +/* +* Copyright (c) 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.carbon.registry.migration; + +import java.io.File; +import java.io.IOException; +import java.rmi.RemoteException; +import java.sql.SQLException; + +import org.apache.axis2.context.ConfigurationContext; +import org.apache.axis2.context.ConfigurationContextFactory; +import org.apache.axis2.context.ServiceContext; +import org.apache.axis2.transport.http.HTTPConstants; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.model.API; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.utils.APIUtil; +import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub; +import org.wso2.carbon.authenticator.stub.LoginAuthenticationExceptionException; +import org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact; +import org.wso2.carbon.governance.api.exception.GovernanceException; +import org.wso2.carbon.governance.api.generic.GenericArtifactManager; +import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact; +import org.wso2.carbon.governance.api.util.GovernanceUtils; +import org.wso2.carbon.registry.core.Registry; +import org.wso2.carbon.registry.core.RegistryConstants; +import org.wso2.carbon.registry.core.Resource; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import org.wso2.carbon.registry.core.session.UserRegistry; +import org.wso2.carbon.registry.migration.utils.CommandHandler; +import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient; +import org.wso2.carbon.registry.resource.stub.ResourceAdminServiceStub; +import org.wso2.carbon.registry.resource.stub.ResourceAdminServiceResourceServiceExceptionException; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; + + +public class Main { + private static Registry registry; + static ConfigurationContext cc; + + + public static void main(String[] args) { + CommandHandler.setInputs(args); + try { + String trustStore = System.getProperty("carbon.home") + File.separator + "repository" + File.separator + + "resources" + File.separator + "security" + File.separator + "wso2carbon.jks"; + System.setProperty("javax.net.ssl.trustStore", trustStore); + System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon"); + System.setProperty("javax.net.ssl.trustStoreType", "JKS"); + System.setProperty("carbon.repo.write.mode", "true"); + + cc = ConfigurationContextFactory.createConfigurationContextFromFileSystem + (System.getProperty("carbon.home") + "repository/deployment/client", System.getProperty("carbon.home") + + "repository/conf/axis2/axis2_client.xml"); + registry = new WSRegistryServiceClient(CommandHandler.getServiceURL(), CommandHandler.getUsername(), + CommandHandler.getPassword(), cc); + Main.migrate(); + System.out.println("Finished API data migration process."); + System.exit(0); + } catch (RegistryException e) { + System.out.println("Error while connecting to registry." + e); + } catch (Exception e) { + System.out.println("Error while migrating data." + e); + } + + } + + private static void migrate() throws RegistryException, APIManagementException, LoginAuthenticationExceptionException, + ResourceAdminServiceResourceServiceExceptionException, SQLException, IOException { + Registry re = GovernanceUtils.getGovernanceUserRegistry(registry, CommandHandler.getUsername()); + GenericArtifactManager manager = new GenericArtifactManager(re, "api"); + GovernanceUtils.loadGovernanceArtifacts((UserRegistry) re); + GenericArtifact[] artifacts = manager.getAllGenericArtifacts(); + + for (GenericArtifact artifact : artifacts) { + API api = getAPI(artifact, re); + APIIdentifier apiIdentfier = api.getId(); + + String apiDefinitionFilePath = getAPIDefinitionFilePath(apiIdentfier.getApiName(), apiIdentfier.getVersion(), apiIdentfier.getProviderName()); + /*apiDefinitionFilePath = RegistryConstants.PATH_SEPARATOR + "registry" + + RegistryConstants.PATH_SEPARATOR + "resource" + + RegistryConstants.PATH_SEPARATOR + "_system" + + RegistryConstants.PATH_SEPARATOR + "governance" + + apiDefinitionFilePath;*/ + + apiDefinitionFilePath = APIUtil.prependTenantPrefix(apiDefinitionFilePath, apiIdentfier.getProviderName()); + Resource resource = re.get(apiDefinitionFilePath); + String text = new String ((byte[]) resource.getContent()); + + String newContentPath = APIUtil.getAPIDefinitionFilePath(apiIdentfier.getApiName(), apiIdentfier.getVersion(),apiIdentfier.getProviderName()); + + try { + Resource docContent = re.newResource(); + docContent.setContent(text); + docContent.setMediaType("text/plain"); + re.put(newContentPath, docContent); + + String visibleRolesList = api.getVisibleRoles(); + String[] visibleRoles = new String[0]; + if (visibleRolesList != null) { + visibleRoles = visibleRolesList.split(","); + } + String sessionCookie = login(CommandHandler.getUsername(), + CommandHandler.getPassword(), CommandHandler.getHost()); + //String permissionString = "ra^false:rd^false:wa^false:wd^false:da^false:dd^false:aa^false:ad^false"; + ResourceAdminServiceStub stub = new ResourceAdminServiceStub(CommandHandler.getServiceURL() + "ResourceAdminService"); + + ServiceClient client = stub._getServiceClient(); + Options option = client.getOptions(); + option.setManageSession(true); + option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, sessionCookie); + stub.addRolePermission("_system/governance" + newContentPath, APIConstants.ANONYMOUS_ROLE, "2", "1"); + } catch (RegistryException e) { + String msg = "Failed to add the API Definition content of : " + + APIConstants.API_DEFINITION_DOC_NAME + " of API :" + apiIdentfier.getApiName(); + throw new APIManagementException(msg, e); + } + + + } + + } + + private static String login(String userName, String password, String host) + throws LoginAuthenticationExceptionException, RemoteException { + Boolean loginStatus; + ServiceContext serviceContext; + String sessionCookie; + AuthenticationAdminStub authenticationAdminStub = new AuthenticationAdminStub(CommandHandler.getServiceURL() + "AuthenticationAdmin"); + loginStatus = authenticationAdminStub.login(userName, password, host); + + if (!loginStatus) { + throw new LoginAuthenticationExceptionException("Login Unsuccessful. Return false as a login status by Server"); + } + serviceContext = authenticationAdminStub._getServiceClient().getLastOperationContext().getServiceContext(); + sessionCookie = (String) serviceContext.getProperty(HTTPConstants.COOKIE_STRING); + return sessionCookie; + } + + private static String getAPIDefinitionFilePath(String apiName, String apiVersion,String apiProvider) { + String resourcePath = APIConstants.API_DOC_LOCATION + RegistryConstants.PATH_SEPARATOR + + apiName +"-" + apiVersion + RegistryConstants.PATH_SEPARATOR + APIConstants.API_DOC_RESOURCE_NAME; + + return resourcePath; + } + + public static API getAPI(GovernanceArtifact artifact, Registry registry) + throws APIManagementException, SQLException { + + API api; + try { + String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER); + String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME); + String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION); + APIIdentifier apiId=new APIIdentifier(providerName, apiName, apiVersion); + api = new API(apiId); + + api.setUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_URL)); + api.setSandboxUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_SANDBOX_URL)); + api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY)); + api.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES)); + + } catch (GovernanceException e) { + String msg = "Failed to get API fro artifact "; + throw new APIManagementException(msg, e); + } + return api; + } + +} diff --git a/modules/distribution/resources/migration-1.6.0_to_1.7.0/swagger-resource-migration/src/org/wso2/carbon/registry/migration/utils/CommandHandler.java b/modules/distribution/resources/migration-1.6.0_to_1.7.0/swagger-resource-migration/src/org/wso2/carbon/registry/migration/utils/CommandHandler.java new file mode 100644 index 0000000000..225f230f4a --- /dev/null +++ b/modules/distribution/resources/migration-1.6.0_to_1.7.0/swagger-resource-migration/src/org/wso2/carbon/registry/migration/utils/CommandHandler.java @@ -0,0 +1,121 @@ +/* +* Copyright (c) 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.carbon.registry.migration.utils; + +import java.util.HashMap; +import java.util.Map; + +public class CommandHandler { + + private static final Map inputs = new HashMap(); + + public static boolean setInputs(String[] arguments) { + + if (arguments.length == 0) { + printMessage(); + return false; + } + if (arguments.length == 1 && arguments[0].equals("--help")) { + printMessage(); + return false; + } + + // now loop through the arguments list to capture the options + for (int i = 0; i < arguments.length; i++) { + if (arguments[i].equals("-h")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Hostname of the registry is missing"); + } + inputs.put("-h", arguments[++i]); + + } else if (arguments[i].equals("-p")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Port of the registry is missing"); + } + inputs.put("-p", arguments[++i]); + + } else if (arguments[i].equals("-u")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Username of the admin is missing"); + } + inputs.put("-u", arguments[++i]); + + } else if (arguments[i].equals("-pw")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Password of the admin is missing"); + } + inputs.put("-pw", arguments[++i]); + } else if (arguments[i].equals("-cr")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Context root of the service is missing"); + } + inputs.put("-cr", arguments[++i]); + } + } + + return true; + } + + + private static void printMessage() { + System.out.println("Usage: migration-client "); + System.out.println("Valid options are:"); + System.out.println("\t-h :\t(Required) The hostname/ip of the registry to login."); + System.out.println("\t-p :\t(Required) The port of the registry to login."); + System.out.println("\t-u :\t(Required) The user name of the registry login."); + System.out.println("\t-pw:\t(Required) The password of the registry login."); + System.out.println(); + System.out.println("Example to migrate a registry running on localhost on default values"); + System.out.println("\te.g: migration-client -h localhost -p 9443 -u admin -pw admin"); + } + + public static String getRegistryURL() { + String contextRoot = inputs.get("-cr"); + + if (contextRoot == null) { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/registry/"; + } else { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/" + contextRoot + "/registry/"; + } + } + + public static String getHost() { + return inputs.get("-h"); + } + + public static String getServiceURL() { + String contextRoot = inputs.get("-cr"); + + if (contextRoot == null) { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/services/"; + } else { + return "https://" + inputs.get("-h") + ":" + inputs.get("-p") + "/" + contextRoot + "/services/"; + } + } + + public static String getUsername() { + return inputs.get("-u"); + } + + public static String getPassword() { + return inputs.get("-pw"); + } + + +} + diff --git a/modules/distribution/resources/scripts/resource_level_throttling_test.jmx b/modules/distribution/resources/scripts/resource_level_throttling_test.jmx new file mode 100644 index 0000000000..948b98f43c --- /dev/null +++ b/modules/distribution/resources/scripts/resource_level_throttling_test.jmx @@ -0,0 +1,1139 @@ + + + + + + false + false + + + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + TestAPI1 + = + + + context + /testapi1 + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + super_tenant_user + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + csvPath + /home/sanjeewa/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 5 + = + + + report_path + /home/sanjeewa/Desktop/results_issue.csv + = + + + + + + continue + + false + 1 + + 1 + 1 + 1342532280000 + 1342532280000 + false + + + + + + + + String report_path = vars.get("report_path"); + +FileOutputStream f = new FileOutputStream(report_path); + + + + + false + + + + false + true + true + false + + + + + + false + rfc2109 + + + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://10.200.3.131:8285/response + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Gold + = + true + tier + + + false + https://lh6.ggpht.com/RNc8dD2hXG_rWGzlj09ZwAe1sXVvLWkeYT3ePx7zePCy4ZVV2XMGIxAzup4cKM85NFtL=w124 + = + true + thumbUrl + + + false + Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + GET + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Application User + = + true + resourceMethodAuthType-0 + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Silver + = + true + resourceMethodThrottlingTier-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${noOfSubscribers} + + + + 1 + 10000 + 1 + subsCount + # + false + + + + + + + false + addUser + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + false + ${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}@test.com|| + = + true + allFieldsValues + + + false + + = + true + + + false + + = + true + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/sign-up/ajax/user-add.jag + POST + true + false + true + false + Java + false + + + + + 50 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//int eq = resp.indexOf("=", def - 8); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + ${publisherName} + = + true + provider + + + false + Gold + = + true + tier + + + false + 1.0.0 + = + true + version + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${publisherName} + = + true + provider + + + false + Platinum + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${subsPrefix}_${subsCount}&password=subscriber@123&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + +String report_path = vars.get("report_path"); +f = new FileOutputStream(report_path, true); + +p = new PrintStream(f); + +this.interpreter.setOut(p); + +print(accessToken); + + + + true + true + true + false + + + + + true + 6 + + + + true + + + + false + <request><value>Request</value></request> + = + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version} + GET + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + HTTP/1.1 200 OK + + Assertion.response_headers + false + 16 + + + + + + + + + false + + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/distribution/resources/scripts/tenant_Creation/tennant_and_role_creation.jmx b/modules/distribution/resources/scripts/tenant_Creation/tennant_and_role_creation.jmx new file mode 100644 index 0000000000..7d91fe8ca9 --- /dev/null +++ b/modules/distribution/resources/scripts/tenant_Creation/tennant_and_role_creation.jmx @@ -0,0 +1,592 @@ + + + + + + false + true + + + + + + + + + + tenant_user_name + tenant + Name of Tenant + = + + + domain_name + domain.com + Name of Domain + = + + + password + 1qaz2wsx@ + Password + = + + + email + ace@wso2.com + Email + = + + + firstName + firstName + First Name + = + + + lastName + lastName + Last Name + = + + + usagePlan + Demo + Usage Plan + = + + + createdDate + 2013-02-22T08:22:54 + Created Date + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + Twitter_Search + = + + + context + /twitter + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + Tester_Acc2 + = + + + publisherName + admin + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://localhost:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + + + https://localhost:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <ser:getTenant> + <!--Optional:--> + <ser:tenantDomain>${domain_name}</ser:tenantDomain> + </ser:getTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:getTenant + true + false + + + + undefined + tenant_exists + //*[local-name()='active']/text() + false + false + true + tenant_exists + + + + false + true + true + false + + + + + ${tenant_exists}==false + false + + + + + + + https://localhost:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org" xmlns:xsd="http://beans.common.stratos.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <ser:addTenant> + <!--Optional:--> + <ser:tenantInfoBean> + <!--Optional:--> + <xsd:active>1</xsd:active> + <!--Optional:--> + <xsd:admin>${tenant_user_name}</xsd:admin> + <!--Optional:--> + <xsd:adminPassword>${password}</xsd:adminPassword> + <!--Optional:--> + <xsd:createdDate>${createdDate}</xsd:createdDate> + <!--Optional:--> + <xsd:email>${email}</xsd:email> + <!--Optional:--> + <xsd:firstname>${firstName}</xsd:firstname> + <!--Optional:--> + <xsd:lastname>${lastName}</xsd:lastname> + <!--Optional:--> + <xsd:tenantDomain>${domain_name}</xsd:tenantDomain> + <!--Optional:--> + <xsd:tenantId>0</xsd:tenantId> + <!--Optional:--> + <xsd:usagePlan>${usagePlan}</xsd:usagePlan> + </ser:tenantInfoBean> + </ser:addTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:addTenant + true + false + + + + + + + + https://localhost:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + 202 + + Assertion.response_code + false + 1 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + + 1363957740000 + 1363957740000 + false + + + + + + + false + + + + + + + https://localhost:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>${tenant_user_name}@${domain_name}</aut:username> + <!--Optional:--> + <aut:password>${password}</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + + + https://localhost:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://mgt.user.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <mgt:getAllRolesNames/> + </soapenv:Body> +</soapenv:Envelope> + + urn:getAllRolesNames + true + false + + + + undefined + publisher_role_exists + //*[local-name()='itemName']/text()='publisher' + false + false + true + + + + undefined + subscriber_role_exists + //*[local-name()='itemName']/text()='subscriber' + false + false + true + + + + false + true + true + false + + + + + ${subscriber_role_exists}==false + false + role_exists + + + + + + + https://localhost:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://mgt.user.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addRole> + <!--Optional:--> + <mgt:roleName>subscriber</mgt:roleName> + <mgt:permissions>/permission/admin/login</mgt:permissions> + <mgt:permissions>/permission/admin/manage/api/subscribe</mgt:permissions> + </mgt:addRole> + </soapenv:Body> +</soapenv:Envelope> + + urn:addRole + true + false + + + + + ${publisher_role_exists}==false + false + role_exists + + + + + + + https://localhost:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://mgt.user.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addRole> + <!--Optional:--> + <mgt:roleName>publisher</mgt:roleName> + <mgt:permissions>/permission/admin/configure/governance</mgt:permissions> + <mgt:permissions>/permission/admin/configure/governance/generic</mgt:permissions> + <mgt:permissions>/permission/admin/configure/governance/lifecycles</mgt:permissions> + <mgt:permissions>/permission/admin/configure/governance/manage-rxt</mgt:permissions> + <mgt:permissions>/permission/admin/login</mgt:permissions> + <mgt:permissions>/permission/admin/manage/api/create</mgt:permissions> + <mgt:permissions>/permission/admin/manage/api/publish</mgt:permissions> + <mgt:permissions>/permission/admin/manage/resources/govern</mgt:permissions> + <mgt:permissions>/permission/admin/manage/resources/govern/generic</mgt:permissions> + <mgt:permissions>/permission/admin/manage/resources/govern/generic/add</mgt:permissions> + <mgt:permissions>/permission/admin/manage/resources/govern/generic/list</mgt:permissions> + <mgt:permissions>/permission/admin/manage/resources/govern/lifecycles</mgt:permissions> + <mgt:permissions>/permission/admin/manage/resources/govern/metadata</mgt:permissions> + </mgt:addRole> + </soapenv:Body> +</soapenv:Envelope> + + urn:addRole + true + false + + + + + + + + https://localhost:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/aggregate_report.jtl + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + + diff --git a/modules/distribution/resources/sql/h2-sample-data.sql b/modules/distribution/resources/sql/h2-sample-data.sql new file mode 100644 index 0000000000..2e83b8585d --- /dev/null +++ b/modules/distribution/resources/sql/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 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 ) 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 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 ) 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/resources/sql/h2.sql b/modules/distribution/resources/sql/h2.sql new file mode 100644 index 0000000000..177a23b375 --- /dev/null +++ b/modules/distribution/resources/sql/h2.sql @@ -0,0 +1,593 @@ +-- 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 ( + 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) ON DELETE CASCADE +); + +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) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_AUTHORIZATION_CODE ( + AUTHORIZATION_CODE VARCHAR (512), + CONSUMER_KEY VARCHAR (512), + CALLBACK_URL VARCHAR (1024), + 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) ON DELETE CASCADE +); + +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 (25), + TIME_CREATED TIMESTAMP DEFAULT 0, + VALIDITY_PERIOD BIGINT, + TOKEN_SCOPE VARCHAR (2048), + TOKEN_STATE VARCHAR (25) DEFAULT 'ACTIVE', + TOKEN_STATE_ID VARCHAR (256) DEFAULT 'NONE', + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) ON DELETE CASCADE, + CONSTRAINT CON_APP_KEY UNIQUE (CONSUMER_KEY, AUTHZ_USER, USER_TYPE, TOKEN_STATE, TOKEN_STATE_ID, TOKEN_SCOPE) +); + +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, + PRIMARY KEY (RESOURCE_PATH), + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +CREATE TABLE IF NOT EXISTS IDN_SCIM_GROUP ( + ID INTEGER GENERATED ALWAYS AS 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) +); + +CREATE TABLE IF NOT EXISTS IDN_SCIM_PROVIDER ( + CONSUMER_ID VARCHAR(255) NOT NULL, + PROVIDER_ID VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + USER_PASSWORD VARCHAR(255) NOT NULL, + USER_URL VARCHAR(1024) NOT NULL, + GROUP_URL VARCHAR(1024), + BULK_URL VARCHAR(1024), + PRIMARY KEY (CONSUMER_ID,PROVIDER_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', + 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) NOT NULL, + 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, + PRIMARY KEY (SESSION_ID) +); + +-- End of IDN Tables -- + + +-- Start of IDN-APPLICATION-MGT Tables-- +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', + SUBJECT_CLAIM_URI VARCHAR (512), + IS_SAAS_APP 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_INBOUND_AUTH ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + INBOUND_AUTH_KEY VARCHAR (255) NOT NULL, + 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'); + +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); + +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, + PRIMARY KEY (ID), + UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME), + 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); + +-- End of IDN-APPLICATION-MGT Tables-- + + +-- Start of API-MGT Tables -- + +CREATE TABLE IF NOT EXISTS AM_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 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', + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID) +); + +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), + PRIMARY KEY(API_ID), + 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), + 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) +); + +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, + 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(50) 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), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) +); + +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, + 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 AM_APPLICATION_REGISTRATION ( + REG_ID INT AUTO_INCREMENT, + SUBSCRIBER_ID INT, + WF_REF VARCHAR(255) NOT NULL, + APP_ID INT, + TOKEN_TYPE VARCHAR(30), + 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 INDEX IDX_AT_CK_AU ON IDN_OAUTH2_ACCESS_TOKEN(CONSUMER_KEY, AUTHZ_USER, TOKEN_STATE, USER_TYPE); + +-- End of API-MGT Tables -- diff --git a/modules/distribution/resources/sql/mssql.sql b/modules/distribution/resources/sql/mssql.sql new file mode 100644 index 0000000000..d7bf1f24a4 --- /dev/null +++ b/modules/distribution/resources/sql/mssql.sql @@ -0,0 +1,660 @@ +-- 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 ( + 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) +); + +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 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) 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 VARCHAR(512), + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR(512), + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) ON DELETE CASCADE +); + +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 ( + AUTHORIZATION_CODE VARCHAR(512), + CONSUMER_KEY VARCHAR(512), + CALLBACK_URL VARCHAR(1024), + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR(512), + TIME_CREATED DATETIME, + VALIDITY_PERIOD BIGINT, + PRIMARY KEY (AUTHORIZATION_CODE), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) 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 ( + ACCESS_TOKEN VARCHAR(255), + REFRESH_TOKEN VARCHAR(255), + CONSUMER_KEY VARCHAR(512), + AUTHZ_USER VARCHAR(255), + USER_TYPE VARCHAR (25), + TIME_CREATED DATETIME, + VALIDITY_PERIOD BIGINT, + TOKEN_SCOPE VARCHAR(2048), + TOKEN_STATE VARCHAR(25) DEFAULT 'ACTIVE', + TOKEN_STATE_ID VARCHAR (256) DEFAULT 'NONE', + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) ON DELETE CASCADE, + CONSTRAINT CON_APP_KEY UNIQUE (CONSUMER_KEY, AUTHZ_USER,USER_TYPE,TOKEN_STATE,TOKEN_STATE_ID, TOKEN_SCOPE) +); + +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, + 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_SCIM_PROVIDER]') AND TYPE IN (N'U')) +CREATE TABLE IDN_SCIM_PROVIDER ( + CONSUMER_ID VARCHAR(255) NOT NULL, + PROVIDER_ID VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + USER_PASSWORD VARCHAR(255) NOT NULL, + USER_URL VARCHAR(1024) NOT NULL, + GROUP_URL VARCHAR(1024), + BULK_URL VARCHAR(1024), + PRIMARY KEY (CONSUMER_ID,PROVIDER_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', + 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) NOT NULL, + 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, + PRIMARY KEY (SESSION_ID) +); + +-- End of IDN Tables -- + + +-- Start of IDN-APPLICATION-MGT Tables-- +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', + SUBJECT_CLAIM_URI VARCHAR (512), + IS_SAAS_APP CHAR(1) DEFAULT '0', + PRIMARY KEY (ID)); + +ALTER TABLE SP_APP ADD CONSTRAINT APPLICATION_NAME_CONSTRAINT UNIQUE(APP_NAME, TENANT_ID); + +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) NOT NULL, + 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; + +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)); + +ALTER TABLE SP_AUTH_STEP ADD 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)); + +ALTER TABLE SP_FEDERATED_IDP ADD 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)); + +ALTER TABLE SP_CLAIM_MAPPING ADD 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)); + +ALTER TABLE SP_ROLE_MAPPING ADD 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)); + +ALTER TABLE SP_REQ_PATH_AUTHENTICATOR ADD 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)); + +ALTER TABLE SP_PROVISIONING_CONNECTOR ADD 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(254), + 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, 'saml2sso'); + +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); + +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, + PRIMARY KEY (ID), + UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME), + 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); + +-- End of IDN-APPLICATION-MGT Tables-- + + + +-- 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, + 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), + 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, + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID) +); + +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), + 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), + 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) +); + +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, + 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), + 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), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) +); + +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 (API_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, + WF_UPDATED_TIME DATETIME, + 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); diff --git a/modules/distribution/resources/sql/mysql.sql b/modules/distribution/resources/sql/mysql.sql new file mode 100644 index 0000000000..70d7d65845 --- /dev/null +++ b/modules/distribution/resources/sql/mysql.sql @@ -0,0 +1,606 @@ +-- Start of IDN Tables -- +CREATE TABLE 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 ( + CONSUMER_KEY VARCHAR(255), + 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) +)ENGINE INNODB; + +CREATE TABLE IDN_OAUTH1A_REQUEST_TOKEN ( + REQUEST_TOKEN VARCHAR(255), + REQUEST_TOKEN_SECRET VARCHAR(512), + CONSUMER_KEY VARCHAR(255), + 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) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IDN_OAUTH1A_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR(255), + ACCESS_TOKEN_SECRET VARCHAR(512), + CONSUMER_KEY VARCHAR(255), + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR(512), + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IDN_OAUTH2_AUTHORIZATION_CODE ( + AUTHORIZATION_CODE VARCHAR(255), + CONSUMER_KEY VARCHAR(255), + CALLBACK_URL VARCHAR(1024), + 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) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IDN_OAUTH2_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR(255), + REFRESH_TOKEN VARCHAR(255), + CONSUMER_KEY VARCHAR(255), + AUTHZ_USER VARCHAR(100), + USER_TYPE VARCHAR (25), + TIME_CREATED TIMESTAMP DEFAULT 0, + 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) ON DELETE CASCADE, + CONSTRAINT CON_APP_KEY UNIQUE (CONSUMER_KEY, AUTHZ_USER,USER_TYPE,TOKEN_STATE,TOKEN_STATE_ID,TOKEN_SCOPE) +)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, + PRIMARY KEY (RESOURCE_PATH), + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE INNODB; + +CREATE TABLE 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 IDN_SCIM_PROVIDER ( + CONSUMER_ID VARCHAR(255) NOT NULL, + PROVIDER_ID VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + USER_PASSWORD VARCHAR(255) NOT NULL, + USER_URL VARCHAR(1024) NOT NULL, + GROUP_URL VARCHAR(1024), + BULK_URL VARCHAR(1024), + PRIMARY KEY (CONSUMER_ID,PROVIDER_ID) +)ENGINE INNODB; + +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) +)ENGINE INNODB; + +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) +)ENGINE INNODB; + +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', + PRIMARY KEY (HANDLE) +)ENGINE INNODB; + +CREATE TABLE 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 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) NOT NULL, + PRIMARY KEY (TENANT_ID, USER_NAME, DATA_KEY) +)ENGINE INNODB; + +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) +)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, + PRIMARY KEY (SESSION_ID) +)ENGINE INNODB; + +-- End of IDN Tables -- + + +-- Start of IDN-APPLICATION-MGT Tables-- + +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', + SUBJECT_CLAIM_URI VARCHAR (512), + IS_SAAS_APP 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_INBOUND_AUTH ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + INBOUND_AUTH_KEY VARCHAR (255) NOT NULL, + 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'); + +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; + +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, + PRIMARY KEY (ID), + UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME), + 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; +-- End of IDN-APPLICATION-MGT Tables-- + + +-- Start of API-MGT Tables -- +CREATE TABLE IF NOT EXISTS AM_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 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', + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID) +)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), + 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), + 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) +)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, + 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(50) 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), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) +)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, + 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), + 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) +); + +CREATE INDEX IDX_SUB_APP_ID ON AM_SUBSCRIPTION (APPLICATION_ID, SUBSCRIPTION_ID); diff --git a/modules/distribution/resources/sql/oracle.sql b/modules/distribution/resources/sql/oracle.sql new file mode 100644 index 0000000000..798118c82c --- /dev/null +++ b/modules/distribution/resources/sql/oracle.sql @@ -0,0 +1,1003 @@ +-- 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 ( + CONSUMER_KEY VARCHAR2 (512), + CONSUMER_SECRET VARCHAR2 (512), + USERNAME VARCHAR2 (255), + TENANT_ID INTEGER DEFAULT 0, + APP_NAME VARCHAR2 (255), + OAUTH_VERSION VARCHAR2 (128), + CALLBACK_URL VARCHAR2 (1024), + GRANT_TYPES VARCHAR (1024), + PRIMARY KEY (CONSUMER_KEY)) +/ +CREATE TABLE IDN_OAUTH1A_REQUEST_TOKEN ( + REQUEST_TOKEN VARCHAR2 (512), + REQUEST_TOKEN_SECRET VARCHAR2 (512), + CONSUMER_KEY VARCHAR2 (512), + CALLBACK_URL VARCHAR2 (1024), + SCOPE VARCHAR2(2048), + AUTHORIZED VARCHAR2 (128), + OAUTH_VERIFIER VARCHAR2 (512), + AUTHZ_USER VARCHAR2 (512), + PRIMARY KEY (REQUEST_TOKEN), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) ON DELETE CASCADE) +/ +CREATE TABLE IDN_OAUTH1A_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR2 (512), + ACCESS_TOKEN_SECRET VARCHAR2 (512), + CONSUMER_KEY VARCHAR2 (512), + SCOPE VARCHAR2(2048), + AUTHZ_USER VARCHAR2 (512), + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) ON DELETE CASCADE) +/ +CREATE TABLE IDN_OAUTH2_AUTHORIZATION_CODE ( + AUTHORIZATION_CODE VARCHAR2 (512), + CONSUMER_KEY VARCHAR2 (512), + CALLBACK_URL VARCHAR2 (1024), + SCOPE VARCHAR2(2048), + AUTHZ_USER VARCHAR2 (512), + TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD NUMBER(19), + PRIMARY KEY (AUTHORIZATION_CODE), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) ON DELETE CASCADE) +/ +CREATE TABLE IDN_OAUTH2_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR2 (255), + REFRESH_TOKEN VARCHAR2 (255), + CONSUMER_KEY VARCHAR2 (255), + AUTHZ_USER VARCHAR2 (255), + USER_TYPE VARCHAR (25), + TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD NUMBER(19), + TOKEN_SCOPE VARCHAR2 (2048), + TOKEN_STATE VARCHAR2 (25) DEFAULT 'ACTIVE', + TOKEN_STATE_ID VARCHAR (256) DEFAULT 'NONE', + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) ON DELETE CASCADE, + CONSTRAINT CON_APP_KEY UNIQUE (CONSUMER_KEY, AUTHZ_USER,USER_TYPE,TOKEN_STATE,TOKEN_STATE_ID,TOKEN_SCOPE)) +/ +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 NOT NULL, + 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, + 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_SCIM_PROVIDER ( + CONSUMER_ID VARCHAR(255) NOT NULL, + PROVIDER_ID VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + USER_PASSWORD VARCHAR(255) NOT NULL, + USER_URL VARCHAR(1024) NOT NULL, + GROUP_URL VARCHAR(1024), + BULK_URL VARCHAR(1024), + PRIMARY KEY (CONSUMER_ID,PROVIDER_ID)) +/ +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', + 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) NOT NULL, + 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, + PRIMARY KEY (SESSION_ID) +) +/ + +-- End of IDN Tables -- + + +-- Start of IDN-APPLICATION-MGT Tables-- +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', + SUBJECT_CLAIM_URI VARCHAR (512), + IS_SAAS_APP 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_INBOUND_AUTH ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + INBOUND_AUTH_KEY VARCHAR (255) NOT NULL, + 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_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 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_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', + PRIMARY KEY (ID), + DISPLAY_NAME VARCHAR(254), + 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; +/ +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 NOCACHE +/ +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, 'saml2sso') +/ +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; +/ +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, + PRIMARY KEY (ID), + UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME), + 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; +/ + +-- End of IDN-APPLICATION-MGT 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, + 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', + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON DELETE CASCADE, + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID) +) +/ + +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), + 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), + 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) +) +/ + +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, + 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), + 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), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) +) +/ + +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, + WF_UPDATED_TIME 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) +/ + diff --git a/modules/distribution/resources/sql/postgresql.sql b/modules/distribution/resources/sql/postgresql.sql new file mode 100644 index 0000000000..0ea17e6e10 --- /dev/null +++ b/modules/distribution/resources/sql/postgresql.sql @@ -0,0 +1,701 @@ +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; +CREATE TABLE IDN_OAUTH_CONSUMER_APPS ( + CONSUMER_KEY VARCHAR(255), + 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) +); + +DROP TABLE IF EXISTS IDN_OAUTH1A_REQUEST_TOKEN; +CREATE TABLE IDN_OAUTH1A_REQUEST_TOKEN ( + REQUEST_TOKEN VARCHAR(255), + REQUEST_TOKEN_SECRET VARCHAR(512), + CONSUMER_KEY VARCHAR(255), + 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) ON DELETE CASCADE +); + +DROP TABLE IF EXISTS IDN_OAUTH1A_ACCESS_TOKEN; +CREATE TABLE IDN_OAUTH1A_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR(255), + ACCESS_TOKEN_SECRET VARCHAR(512), + CONSUMER_KEY VARCHAR(255), + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR(512), + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) ON DELETE CASCADE +); + +DROP TABLE IF EXISTS IDN_OAUTH2_AUTHORIZATION_CODE; +CREATE TABLE IDN_OAUTH2_AUTHORIZATION_CODE ( + AUTHORIZATION_CODE VARCHAR(255), + CONSUMER_KEY VARCHAR(255), + CALLBACK_URL VARCHAR(1024), + 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) ON DELETE CASCADE +); + +DROP TABLE IF EXISTS IDN_OAUTH2_ACCESS_TOKEN; +CREATE TABLE IDN_OAUTH2_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR(255), + REFRESH_TOKEN VARCHAR(255), + CONSUMER_KEY VARCHAR(255), + AUTHZ_USER VARCHAR(100), + USER_TYPE VARCHAR (25), + TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD BIGINT, + TOKEN_SCOPE VARCHAR(2048), + 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) ON DELETE CASCADE, + CONSTRAINT CON_APP_KEY UNIQUE (CONSUMER_KEY, AUTHZ_USER,USER_TYPE,TOKEN_STATE,TOKEN_STATE_ID,TOKEN_SCOPE) +); + +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 NOT NULL, + 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, + 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_SCIM_PROVIDER; +CREATE TABLE IDN_SCIM_PROVIDER ( + CONSUMER_ID VARCHAR(255) NOT NULL, + PROVIDER_ID VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + USER_PASSWORD VARCHAR(255) NOT NULL, + USER_URL VARCHAR(1024) NOT NULL, + GROUP_URL VARCHAR(1024), + BULK_URL VARCHAR(1024), + PRIMARY KEY (CONSUMER_ID,PROVIDER_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', + 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) NOT NULL, + 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, + PRIMARY KEY (SESSION_ID) +); + +-- End of IDN Tables -- + + +-- Start of IDN-APPLICATION-MGT Tables-- +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', + SUBJECT_CLAIM_URI VARCHAR (512), + IS_SAAS_APP 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_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) NOT NULL, + 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_AUTHENTICATOR; +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_PROVISIONING_CONNECTOR; +DROP SEQUENCE IF EXISTS SP_PROV_CONNECTOR_SEQ CASCADE; +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(254), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, NAME)); + +INSERT INTO IDP (TENANT_ID, NAME, HOME_REALM_ID) VALUES (-1234, 'LOCAL', 'localhost'); + +DROP TABLE IF EXISTS IDP_ROLE; +DROP SEQUENCE IF EXISTS IDP_ROLE_SEQ; +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, 'saml2sso'); + +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); + +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 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); + +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, + PRIMARY KEY (ID), + UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME), + 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); + +-- End of IDN-APPLICATION-MGT Tables-- + + +CREATE SEQUENCE AM_SUBSCRIBER_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE 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 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 AM_API_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE 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), + 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 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 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), + 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) +) +; + +CREATE TABLE 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), + 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), + 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 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 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 AM_API_COMMENTS_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE 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 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 AM_API_RATINGS_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE 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 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 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) +) +; + +DROP TABLE IF EXISTS AM_API_SCOPES; +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 +); + +DROP TABLE IF EXISTS AM_API_DEFAULT_VERSION; +DROP SEQUENCE IF EXISTS AM_API_DEFAULT_VERSION_PK_SEQ; +CREATE SEQUENCE AM_API_DEFAULT_VERSION_PK_SEQ; +CREATE TABLE 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) +; +commit; diff --git a/modules/features/pom.xml b/modules/features/pom.xml new file mode 100644 index 0000000000..2d7d1521f8 --- /dev/null +++ b/modules/features/pom.xml @@ -0,0 +1,49 @@ + + + + + + + org.wso2.am + am-parent + 1.7.0-SNAPSHOT + ../../pom.xml + + + 4.0.0 + am-features-parent + pom + WSO2 API Manager - Features Parent + http://wso2.com/products/api-manager + WSO2 API Manager Features Parent + + + + Apache License Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + + + + + product + service + + diff --git a/modules/features/product/etc/feature.properties b/modules/features/product/etc/feature.properties new file mode 100644 index 0000000000..ad7a55338c --- /dev/null +++ b/modules/features/product/etc/feature.properties @@ -0,0 +1,242 @@ +################################################################################ +# Copyright 2009 WSO2, Inc. (http://wso2.com) +# +# 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. +################################################################################ + +providerName=WSO2 Inc. + +########################## license properties ################################## +licenseURL=http://www.apache.org/licenses/LICENSE-2.0 + +license=\ + Apache License\n\ + Version 2.0, January 2004\n\ + http://www.apache.org/licenses/\n\ +\n\ + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\ +\n\ + 1. Definitions.\n\ +\n\ + "License" shall mean the terms and conditions for use, reproduction,\n\ + and distribution as defined by Sections 1 through 9 of this document.\n\ +\n\ + "Licensor" shall mean the copyright owner or entity authorized by\n\ + the copyright owner that is granting the License.\n\ +\n\ + "Legal Entity" shall mean the union of the acting entity and all\n\ + other entities that control, are controlled by, or are under common\n\ + control with that entity. For the purposes of this definition,\n\ + "control" means (i) the power, direct or indirect, to cause the\n\ + direction or management of such entity, whether by contract or\n\ + otherwise, or (ii) ownership of fifty percent (50%) or more of the\n\ + outstanding shares, or (iii) beneficial ownership of such entity.\n\ +\n\ + "You" (or "Your") shall mean an individual or Legal Entity\n\ + exercising permissions granted by this License.\n\ +\n\ + "Source" form shall mean the preferred form for making modifications,\n\ + including but not limited to software source code, documentation\n\ + source, and configuration files.\n\ +\n\ + "Object" form shall mean any form resulting from mechanical\n\ + transformation or translation of a Source form, including but\n\ + not limited to compiled object code, generated documentation,\n\ + and conversions to other media types.\n\ +\n\ + "Work" shall mean the work of authorship, whether in Source or\n\ + Object form, made available under the License, as indicated by a\n\ + copyright notice that is included in or attached to the work\n\ + (an example is provided in the Appendix below).\n\ +\n\ + "Derivative Works" shall mean any work, whether in Source or Object\n\ + form, that is based on (or derived from) the Work and for which the\n\ + editorial revisions, annotations, elaborations, or other modifications\n\ + represent, as a whole, an original work of authorship. For the purposes\n\ + of this License, Derivative Works shall not include works that remain\n\ + separable from, or merely link (or bind by name) to the interfaces of,\n\ + the Work and Derivative Works thereof.\n\ +\n\ + "Contribution" shall mean any work of authorship, including\n\ + the original version of the Work and any modifications or additions\n\ + to that Work or Derivative Works thereof, that is intentionally\n\ + submitted to Licensor for inclusion in the Work by the copyright owner\n\ + or by an individual or Legal Entity authorized to submit on behalf of\n\ + the copyright owner. For the purposes of this definition, "submitted"\n\ + means any form of electronic, verbal, or written communication sent\n\ + to the Licensor or its representatives, including but not limited to\n\ + communication on electronic mailing lists, source code control systems,\n\ + and issue tracking systems that are managed by, or on behalf of, the\n\ + Licensor for the purpose of discussing and improving the Work, but\n\ + excluding communication that is conspicuously marked or otherwise\n\ + designated in writing by the copyright owner as "Not a Contribution."\n\ +\n\ + "Contributor" shall mean Licensor and any individual or Legal Entity\n\ + on behalf of whom a Contribution has been received by Licensor and\n\ + subsequently incorporated within the Work.\n\ +\n\ + 2. Grant of Copyright License. Subject to the terms and conditions of\n\ + this License, each Contributor hereby grants to You a perpetual,\n\ + worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n\ + copyright license to reproduce, prepare Derivative Works of,\n\ + publicly display, publicly perform, sublicense, and distribute the\n\ + Work and such Derivative Works in Source or Object form.\n\ +\n\ + 3. Grant of Patent License. Subject to the terms and conditions of\n\ + this License, each Contributor hereby grants to You a perpetual,\n\ + worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n\ + (except as stated in this section) patent license to make, have made,\n\ + use, offer to sell, sell, import, and otherwise transfer the Work,\n\ + where such license applies only to those patent claims licensable\n\ + by such Contributor that are necessarily infringed by their\n\ + Contribution(s) alone or by combination of their Contribution(s)\n\ + with the Work to which such Contribution(s) was submitted. If You\n\ + institute patent litigation against any entity (including a\n\ + cross-claim or counterclaim in a lawsuit) alleging that the Work\n\ + or a Contribution incorporated within the Work constitutes direct\n\ + or contributory patent infringement, then any patent licenses\n\ + granted to You under this License for that Work shall terminate\n\ + as of the date such litigation is filed.\n\ +\n\ + 4. Redistribution. You may reproduce and distribute copies of the\n\ + Work or Derivative Works thereof in any medium, with or without\n\ + modifications, and in Source or Object form, provided that You\n\ + meet the following conditions:\n\ +\n\ + (a) You must give any other recipients of the Work or\n\ + Derivative Works a copy of this License; and\n\ +\n\ + (b) You must cause any modified files to carry prominent notices\n\ + stating that You changed the files; and\n\ +\n\ + (c) You must retain, in the Source form of any Derivative Works\n\ + that You distribute, all copyright, patent, trademark, and\n\ + attribution notices from the Source form of the Work,\n\ + excluding those notices that do not pertain to any part of\n\ + the Derivative Works; and\n\ +\n\ + (d) If the Work includes a "NOTICE" text file as part of its\n\ + distribution, then any Derivative Works that You distribute must\n\ + include a readable copy of the attribution notices contained\n\ + within such NOTICE file, excluding those notices that do not\n\ + pertain to any part of the Derivative Works, in at least one\n\ + of the following places: within a NOTICE text file distributed\n\ + as part of the Derivative Works; within the Source form or\n\ + documentation, if provided along with the Derivative Works; or,\n\ + within a display generated by the Derivative Works, if and\n\ + wherever such third-party notices normally appear. The contents\n\ + of the NOTICE file are for informational purposes only and\n\ + do not modify the License. You may add Your own attribution\n\ + notices within Derivative Works that You distribute, alongside\n\ + or as an addendum to the NOTICE text from the Work, provided\n\ + that such additional attribution notices cannot be construed\n\ + as modifying the License.\n\ +\n\ + You may add Your own copyright statement to Your modifications and\n\ + may provide additional or different license terms and conditions\n\ + for use, reproduction, or distribution of Your modifications, or\n\ + for any such Derivative Works as a whole, provided Your use,\n\ + reproduction, and distribution of the Work otherwise complies with\n\ + the conditions stated in this License.\n\ +\n\ + 5. Submission of Contributions. Unless You explicitly state otherwise,\n\ + any Contribution intentionally submitted for inclusion in the Work\n\ + by You to the Licensor shall be under the terms and conditions of\n\ + this License, without any additional terms or conditions.\n\ + Notwithstanding the above, nothing herein shall supersede or modify\n\ + the terms of any separate license agreement you may have executed\n\ + with Licensor regarding such Contributions.\n\ +\n\ + 6. Trademarks. This License does not grant permission to use the trade\n\ + names, trademarks, service marks, or product names of the Licensor,\n\ + except as required for reasonable and customary use in describing the\n\ + origin of the Work and reproducing the content of the NOTICE file.\n\ +\n\ + 7. Disclaimer of Warranty. Unless required by applicable law or\n\ + agreed to in writing, Licensor provides the Work (and each\n\ + Contributor provides its Contributions) on an "AS IS" BASIS,\n\ + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\ + implied, including, without limitation, any warranties or conditions\n\ + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n\ + PARTICULAR PURPOSE. You are solely responsible for determining the\n\ + appropriateness of using or redistributing the Work and assume any\n\ + risks associated with Your exercise of permissions under this License.\n\ +\n\ + 8. Limitation of Liability. In no event and under no legal theory,\n\ + whether in tort (including negligence), contract, or otherwise,\n\ + unless required by applicable law (such as deliberate and grossly\n\ + negligent acts) or agreed to in writing, shall any Contributor be\n\ + liable to You for damages, including any direct, indirect, special,\n\ + incidental, or consequential damages of any character arising as a\n\ + result of this License or out of the use or inability to use the\n\ + Work (including but not limited to damages for loss of goodwill,\n\ + work stoppage, computer failure or malfunction, or any and all\n\ + other commercial damages or losses), even if such Contributor\n\ + has been advised of the possibility of such damages.\n\ +\n\ + 9. Accepting Warranty or Additional Liability. While redistributing\n\ + the Work or Derivative Works thereof, You may choose to offer,\n\ + and charge a fee for, acceptance of support, warranty, indemnity,\n\ + or other liability obligations and/or rights consistent with this\n\ + License. However, in accepting such obligations, You may act only\n\ + on Your own behalf and on Your sole responsibility, not on behalf\n\ + of any other Contributor, and only if You agree to indemnify,\n\ + defend, and hold each Contributor harmless for any liability\n\ + incurred by, or claims asserted against, such Contributor by reason\n\ + of your accepting any such warranty or additional liability.\n\ +\n\ + END OF TERMS AND CONDITIONS\n\ +\n\ + APPENDIX: How to apply the Apache License to your work.\n\ +\n\ + To apply the Apache License to your work, attach the following\n\ + boilerplate notice, with the fields enclosed by brackets "[]"\n\ + replaced with your own identifying information. (Don't include\n\ + the brackets!) The text should be enclosed in the appropriate\n\ + comment syntax for the file format. We also recommend that a\n\ + file or class name and description of purpose be included on the\n\ + same "printed page" as the copyright notice for easier\n\ + identification within third-party archives.\n\ +\n\ + Copyright [yyyy] [name of copyright owner]\n\ +\n\ + Licensed under the Apache License, Version 2.0 (the "License");\n\ + you may not use this file except in compliance with the License.\n\ + You may obtain a copy of the License at\n\ +\n\ + http://www.apache.org/licenses/LICENSE-2.0\n\ +\n\ + Unless required by applicable law or agreed to in writing, software\n\ + distributed under the License is distributed on an "AS IS" BASIS,\n\ + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\ + See the License for the specific language governing permissions and\n\ + limitations under the License.\n + +######################### copyright properties ################################# +copyrightURL=TODO + +copyright=\ +Copyright (c) WSO2 Inc. (http://wso2.com)\n\ +\n\ +Licensed under the Apache License, Version 2.0 (the "License");\n\ +you may not use this file except in compliance with the License.\n\ +You may obtain a copy of the License at\n\ +\n\ +http://www.apache.org/licenses/LICENSE-2.0\n\ +\n\ +Unless required by applicable law or agreed to in writing, software\n\ +distributed under the License is distributed on an "AS IS" BASIS,\n\ +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\ +See the License for the specific language governing permissions and\n\ +limitations under the License.\n + diff --git a/modules/features/product/org.wso2.am.styles.feature/pom.xml b/modules/features/product/org.wso2.am.styles.feature/pom.xml new file mode 100644 index 0000000000..b8a083bd50 --- /dev/null +++ b/modules/features/product/org.wso2.am.styles.feature/pom.xml @@ -0,0 +1,78 @@ + + + + + + + org.wso2.am + am-features + 1.7.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.am.styles.feature + pom + WSO2 API Manager - Styles Features + http://www.wso2.org + + + + org.wso2.am + org.wso2.am.styles + + + + + + + org.wso2.maven + carbon-p2-plugin + ${carbon.p2.plugin.version} + + + 4-p2-feature-generation + package + + p2-feature-gen + + + org.wso2.am.styles + ../etc/feature.properties + + + org.wso2.carbon.p2.category.type:console + + + + org.wso2.am:org.wso2.am.styles + + + org.wso2.carbon.core.ui:${carbon.platform.version} + + + + + + + + + diff --git a/modules/features/product/pom.xml b/modules/features/product/pom.xml new file mode 100644 index 0000000000..599e0e92dd --- /dev/null +++ b/modules/features/product/pom.xml @@ -0,0 +1,51 @@ + + + + + + + org.wso2.am + am-features-parent + 1.7.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + am-features + pom + WSO2 API Manager - Features Aggregator Module + Features specific to the WSO2 API Manager + + + + + org.wso2.am + org.wso2.am.styles + 1.7.0-SNAPSHOT + + + + + + org.wso2.am.styles.feature + + + diff --git a/modules/features/service/etc/feature.properties b/modules/features/service/etc/feature.properties new file mode 100644 index 0000000000..ad7a55338c --- /dev/null +++ b/modules/features/service/etc/feature.properties @@ -0,0 +1,242 @@ +################################################################################ +# Copyright 2009 WSO2, Inc. (http://wso2.com) +# +# 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. +################################################################################ + +providerName=WSO2 Inc. + +########################## license properties ################################## +licenseURL=http://www.apache.org/licenses/LICENSE-2.0 + +license=\ + Apache License\n\ + Version 2.0, January 2004\n\ + http://www.apache.org/licenses/\n\ +\n\ + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\ +\n\ + 1. Definitions.\n\ +\n\ + "License" shall mean the terms and conditions for use, reproduction,\n\ + and distribution as defined by Sections 1 through 9 of this document.\n\ +\n\ + "Licensor" shall mean the copyright owner or entity authorized by\n\ + the copyright owner that is granting the License.\n\ +\n\ + "Legal Entity" shall mean the union of the acting entity and all\n\ + other entities that control, are controlled by, or are under common\n\ + control with that entity. For the purposes of this definition,\n\ + "control" means (i) the power, direct or indirect, to cause the\n\ + direction or management of such entity, whether by contract or\n\ + otherwise, or (ii) ownership of fifty percent (50%) or more of the\n\ + outstanding shares, or (iii) beneficial ownership of such entity.\n\ +\n\ + "You" (or "Your") shall mean an individual or Legal Entity\n\ + exercising permissions granted by this License.\n\ +\n\ + "Source" form shall mean the preferred form for making modifications,\n\ + including but not limited to software source code, documentation\n\ + source, and configuration files.\n\ +\n\ + "Object" form shall mean any form resulting from mechanical\n\ + transformation or translation of a Source form, including but\n\ + not limited to compiled object code, generated documentation,\n\ + and conversions to other media types.\n\ +\n\ + "Work" shall mean the work of authorship, whether in Source or\n\ + Object form, made available under the License, as indicated by a\n\ + copyright notice that is included in or attached to the work\n\ + (an example is provided in the Appendix below).\n\ +\n\ + "Derivative Works" shall mean any work, whether in Source or Object\n\ + form, that is based on (or derived from) the Work and for which the\n\ + editorial revisions, annotations, elaborations, or other modifications\n\ + represent, as a whole, an original work of authorship. For the purposes\n\ + of this License, Derivative Works shall not include works that remain\n\ + separable from, or merely link (or bind by name) to the interfaces of,\n\ + the Work and Derivative Works thereof.\n\ +\n\ + "Contribution" shall mean any work of authorship, including\n\ + the original version of the Work and any modifications or additions\n\ + to that Work or Derivative Works thereof, that is intentionally\n\ + submitted to Licensor for inclusion in the Work by the copyright owner\n\ + or by an individual or Legal Entity authorized to submit on behalf of\n\ + the copyright owner. For the purposes of this definition, "submitted"\n\ + means any form of electronic, verbal, or written communication sent\n\ + to the Licensor or its representatives, including but not limited to\n\ + communication on electronic mailing lists, source code control systems,\n\ + and issue tracking systems that are managed by, or on behalf of, the\n\ + Licensor for the purpose of discussing and improving the Work, but\n\ + excluding communication that is conspicuously marked or otherwise\n\ + designated in writing by the copyright owner as "Not a Contribution."\n\ +\n\ + "Contributor" shall mean Licensor and any individual or Legal Entity\n\ + on behalf of whom a Contribution has been received by Licensor and\n\ + subsequently incorporated within the Work.\n\ +\n\ + 2. Grant of Copyright License. Subject to the terms and conditions of\n\ + this License, each Contributor hereby grants to You a perpetual,\n\ + worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n\ + copyright license to reproduce, prepare Derivative Works of,\n\ + publicly display, publicly perform, sublicense, and distribute the\n\ + Work and such Derivative Works in Source or Object form.\n\ +\n\ + 3. Grant of Patent License. Subject to the terms and conditions of\n\ + this License, each Contributor hereby grants to You a perpetual,\n\ + worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n\ + (except as stated in this section) patent license to make, have made,\n\ + use, offer to sell, sell, import, and otherwise transfer the Work,\n\ + where such license applies only to those patent claims licensable\n\ + by such Contributor that are necessarily infringed by their\n\ + Contribution(s) alone or by combination of their Contribution(s)\n\ + with the Work to which such Contribution(s) was submitted. If You\n\ + institute patent litigation against any entity (including a\n\ + cross-claim or counterclaim in a lawsuit) alleging that the Work\n\ + or a Contribution incorporated within the Work constitutes direct\n\ + or contributory patent infringement, then any patent licenses\n\ + granted to You under this License for that Work shall terminate\n\ + as of the date such litigation is filed.\n\ +\n\ + 4. Redistribution. You may reproduce and distribute copies of the\n\ + Work or Derivative Works thereof in any medium, with or without\n\ + modifications, and in Source or Object form, provided that You\n\ + meet the following conditions:\n\ +\n\ + (a) You must give any other recipients of the Work or\n\ + Derivative Works a copy of this License; and\n\ +\n\ + (b) You must cause any modified files to carry prominent notices\n\ + stating that You changed the files; and\n\ +\n\ + (c) You must retain, in the Source form of any Derivative Works\n\ + that You distribute, all copyright, patent, trademark, and\n\ + attribution notices from the Source form of the Work,\n\ + excluding those notices that do not pertain to any part of\n\ + the Derivative Works; and\n\ +\n\ + (d) If the Work includes a "NOTICE" text file as part of its\n\ + distribution, then any Derivative Works that You distribute must\n\ + include a readable copy of the attribution notices contained\n\ + within such NOTICE file, excluding those notices that do not\n\ + pertain to any part of the Derivative Works, in at least one\n\ + of the following places: within a NOTICE text file distributed\n\ + as part of the Derivative Works; within the Source form or\n\ + documentation, if provided along with the Derivative Works; or,\n\ + within a display generated by the Derivative Works, if and\n\ + wherever such third-party notices normally appear. The contents\n\ + of the NOTICE file are for informational purposes only and\n\ + do not modify the License. You may add Your own attribution\n\ + notices within Derivative Works that You distribute, alongside\n\ + or as an addendum to the NOTICE text from the Work, provided\n\ + that such additional attribution notices cannot be construed\n\ + as modifying the License.\n\ +\n\ + You may add Your own copyright statement to Your modifications and\n\ + may provide additional or different license terms and conditions\n\ + for use, reproduction, or distribution of Your modifications, or\n\ + for any such Derivative Works as a whole, provided Your use,\n\ + reproduction, and distribution of the Work otherwise complies with\n\ + the conditions stated in this License.\n\ +\n\ + 5. Submission of Contributions. Unless You explicitly state otherwise,\n\ + any Contribution intentionally submitted for inclusion in the Work\n\ + by You to the Licensor shall be under the terms and conditions of\n\ + this License, without any additional terms or conditions.\n\ + Notwithstanding the above, nothing herein shall supersede or modify\n\ + the terms of any separate license agreement you may have executed\n\ + with Licensor regarding such Contributions.\n\ +\n\ + 6. Trademarks. This License does not grant permission to use the trade\n\ + names, trademarks, service marks, or product names of the Licensor,\n\ + except as required for reasonable and customary use in describing the\n\ + origin of the Work and reproducing the content of the NOTICE file.\n\ +\n\ + 7. Disclaimer of Warranty. Unless required by applicable law or\n\ + agreed to in writing, Licensor provides the Work (and each\n\ + Contributor provides its Contributions) on an "AS IS" BASIS,\n\ + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\ + implied, including, without limitation, any warranties or conditions\n\ + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n\ + PARTICULAR PURPOSE. You are solely responsible for determining the\n\ + appropriateness of using or redistributing the Work and assume any\n\ + risks associated with Your exercise of permissions under this License.\n\ +\n\ + 8. Limitation of Liability. In no event and under no legal theory,\n\ + whether in tort (including negligence), contract, or otherwise,\n\ + unless required by applicable law (such as deliberate and grossly\n\ + negligent acts) or agreed to in writing, shall any Contributor be\n\ + liable to You for damages, including any direct, indirect, special,\n\ + incidental, or consequential damages of any character arising as a\n\ + result of this License or out of the use or inability to use the\n\ + Work (including but not limited to damages for loss of goodwill,\n\ + work stoppage, computer failure or malfunction, or any and all\n\ + other commercial damages or losses), even if such Contributor\n\ + has been advised of the possibility of such damages.\n\ +\n\ + 9. Accepting Warranty or Additional Liability. While redistributing\n\ + the Work or Derivative Works thereof, You may choose to offer,\n\ + and charge a fee for, acceptance of support, warranty, indemnity,\n\ + or other liability obligations and/or rights consistent with this\n\ + License. However, in accepting such obligations, You may act only\n\ + on Your own behalf and on Your sole responsibility, not on behalf\n\ + of any other Contributor, and only if You agree to indemnify,\n\ + defend, and hold each Contributor harmless for any liability\n\ + incurred by, or claims asserted against, such Contributor by reason\n\ + of your accepting any such warranty or additional liability.\n\ +\n\ + END OF TERMS AND CONDITIONS\n\ +\n\ + APPENDIX: How to apply the Apache License to your work.\n\ +\n\ + To apply the Apache License to your work, attach the following\n\ + boilerplate notice, with the fields enclosed by brackets "[]"\n\ + replaced with your own identifying information. (Don't include\n\ + the brackets!) The text should be enclosed in the appropriate\n\ + comment syntax for the file format. We also recommend that a\n\ + file or class name and description of purpose be included on the\n\ + same "printed page" as the copyright notice for easier\n\ + identification within third-party archives.\n\ +\n\ + Copyright [yyyy] [name of copyright owner]\n\ +\n\ + Licensed under the Apache License, Version 2.0 (the "License");\n\ + you may not use this file except in compliance with the License.\n\ + You may obtain a copy of the License at\n\ +\n\ + http://www.apache.org/licenses/LICENSE-2.0\n\ +\n\ + Unless required by applicable law or agreed to in writing, software\n\ + distributed under the License is distributed on an "AS IS" BASIS,\n\ + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\ + See the License for the specific language governing permissions and\n\ + limitations under the License.\n + +######################### copyright properties ################################# +copyrightURL=TODO + +copyright=\ +Copyright (c) WSO2 Inc. (http://wso2.com)\n\ +\n\ +Licensed under the Apache License, Version 2.0 (the "License");\n\ +you may not use this file except in compliance with the License.\n\ +You may obtain a copy of the License at\n\ +\n\ +http://www.apache.org/licenses/LICENSE-2.0\n\ +\n\ +Unless required by applicable law or agreed to in writing, software\n\ +distributed under the License is distributed on an "AS IS" BASIS,\n\ +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\ +See the License for the specific language governing permissions and\n\ +limitations under the License.\n + diff --git a/modules/features/service/org.wso2.stratos.apimgt.dashboard.ui.feature/pom.xml b/modules/features/service/org.wso2.stratos.apimgt.dashboard.ui.feature/pom.xml new file mode 100644 index 0000000000..d431788629 --- /dev/null +++ b/modules/features/service/org.wso2.stratos.apimgt.dashboard.ui.feature/pom.xml @@ -0,0 +1,82 @@ + + + + + org.wso2.am + wso2stratos-am-features + ${stratos.version} + + + 4.0.0 + org.wso2.stratos.apimgt.dashboard.ui.feature + pom + WSO2 Stratos API Manager - Dashboard UI Features + http://wso2.org + + + + org.wso2.am + org.wso2.stratos.apimgt.dashboard.ui + ${stratos.version} + + + org.wso2.carbon + org.wso2.carbon.ui.menu.stratos + ${stratos.version} + + + + + + + org.wso2.maven + carbon-p2-plugin + ${carbon.p2.plugin.version} + + + p2-feature-generation + package + + p2-feature-gen + + + org.wso2.stratos.apimgt.dashboard.ui + ../etc/feature.properties + + + org.wso2.carbon.p2.category.type:console + + + + org.wso2.am:org.wso2.stratos.apimgt.dashboard.ui + org.wso2.carbon:org.wso2.carbon.ui.menu.stratos + + + org.wso2.carbon.core.ui:${carbon.platform.version} + + + + + + + + + diff --git a/modules/features/service/org.wso2.stratos.apimgt.login.ui.feature/pom.xml b/modules/features/service/org.wso2.stratos.apimgt.login.ui.feature/pom.xml new file mode 100644 index 0000000000..883e64fba4 --- /dev/null +++ b/modules/features/service/org.wso2.stratos.apimgt.login.ui.feature/pom.xml @@ -0,0 +1,73 @@ + + + + + org.wso2.am + wso2stratos-am-features + ${stratos.version} + + + 4.0.0 + org.wso2.stratos.apimgt.login.ui.feature + pom + WSO2 Stratos API Manager - Deployment Features + http://wso2.org + + + + org.wso2.am + org.wso2.stratos.apimgt.login.ui + ${stratos.version} + + + + + + + org.wso2.maven + carbon-p2-plugin + ${carbon.p2.plugin.version} + + + p2-feature-generation + package + + p2-feature-gen + + + org.wso2.stratos.apimgt.login.ui + ../etc/feature.properties + + + org.wso2.carbon.p2.category.type:console + + + + org.wso2.am:org.wso2.stratos.apimgt.login.ui + + + + + + + + + diff --git a/modules/features/service/org.wso2.stratos.apimgt.styles.feature/pom.xml b/modules/features/service/org.wso2.stratos.apimgt.styles.feature/pom.xml new file mode 100644 index 0000000000..ddf542802a --- /dev/null +++ b/modules/features/service/org.wso2.stratos.apimgt.styles.feature/pom.xml @@ -0,0 +1,76 @@ + + + + + org.wso2.am + wso2stratos-am-features + ${stratos.version} + + + 4.0.0 + org.wso2.stratos.apimgt.styles.feature + pom + WSO2 Stratos API Manager - Style Features + http://wso2.org + + + + org.wso2.am + org.wso2.stratos.apimgt.styles + ${project.version} + + + + + + + org.wso2.maven + carbon-p2-plugin + ${carbon.p2.plugin.version} + + + p2-feature-generation + package + + p2-feature-gen + + + org.wso2.stratos.apimgt.styles + ../etc/feature.properties + + + org.wso2.carbon.p2.category.type:console + + + + org.wso2.am:org.wso2.stratos.apimgt.styles + + + org.wso2.carbon.core.ui:${carbon.platform.version} + + + + + + + + + diff --git a/modules/features/service/org.wso2.stratos.apimgt.utils.feature/pom.xml b/modules/features/service/org.wso2.stratos.apimgt.utils.feature/pom.xml new file mode 100644 index 0000000000..167be61c5d --- /dev/null +++ b/modules/features/service/org.wso2.stratos.apimgt.utils.feature/pom.xml @@ -0,0 +1,116 @@ + + + + + org.wso2.am + wso2stratos-am-features + ${stratos.version} + + + 4.0.0 + org.wso2.stratos.apimgt.utils.feature + pom + WSO2 Stratos API Manager - Utils Features + http://wso2.org + + + + org.apache.derby.wso2 + derby + + + org.hibernate.wso2 + hibernate + + + org.apache.bcel.wso2 + bcel + + + asm.wso2 + asm + + + cglib.wso2 + cglib + + + org.apache.axis2.wso2 + axis2-jibx + + + org.jibx.wso2 + jibx + + + org.apache.axis2.wso2 + axis2-jaxbri + + + com.sun.xml.bind.wso2 + jaxb + + + + + + + org.wso2.maven + carbon-p2-plugin + ${carbon.p2.plugin.version} + + + p2-feature-generation + package + + p2-feature-gen + + + org.wso2.stratos.apimgt.utils + ../etc/feature.properties + + + org.wso2.carbon.p2.category.type:server + + + + org.apache.derby.wso2:derby + org.hibernate.wso2:hibernate + org.apache.bcel.wso2:bcel + asm.wso2:asm + cglib.wso2:cglib + cglib.wso2:cglib + org.apache.axis2.wso2:axis2-jibx + org.jibx.wso2:jibx + org.apache.axis2.wso2:axis2-jaxbri + com.sun.xml.bind.wso2:jaxb + + + org.wso2.carbon.core.server:${carbon.platform.version} + + + + + + + + + diff --git a/modules/features/service/pom.xml b/modules/features/service/pom.xml new file mode 100644 index 0000000000..211a0bc1e9 --- /dev/null +++ b/modules/features/service/pom.xml @@ -0,0 +1,99 @@ + + + + + + + org.wso2.am + am-features-parent + 1.7.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + wso2stratos-am-features + ${stratos.version} + pom + WSO2 Stratos API Manager - Features Aggregator Module + http://wso2.org + + + org.wso2.stratos.apimgt.styles.feature + org.wso2.stratos.apimgt.utils.feature + org.wso2.stratos.apimgt.dashboard.ui.feature + org.wso2.stratos.apimgt.login.ui.feature + + + + + + org.wso2.am + org.wso2.stratos.apimgt.styles + ${project.version} + + + org.apache.derby.wso2 + derby + ${apache.derby.version} + + + org.hibernate.wso2 + hibernate + ${hibernate.version} + + + org.apache.bcel.wso2 + bcel + ${bcel.version} + + + asm.wso2 + asm + ${asm.version} + + + cglib.wso2 + cglib + ${cglib.version} + + + org.apache.axis2.wso2 + axis2-jibx + ${axis2.jibx.version} + + + org.jibx.wso2 + jibx + ${jibx.version} + + + org.apache.axis2.wso2 + axis2-jaxbri + ${axis2.jaxb.version} + + + com.sun.xml.bind.wso2 + jaxb + ${jaxb.version} + + + + + + diff --git a/modules/integration/backend-service/pom.xml b/modules/integration/backend-service/pom.xml new file mode 100644 index 0000000000..1caa80a750 --- /dev/null +++ b/modules/integration/backend-service/pom.xml @@ -0,0 +1,183 @@ + + + + org.wso2.am + integration + 1.7.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + WSO2 API Manager - RestFul Backend + org.wso2.am.backend.service + jar + + + 2.7.2 + 3.2.0.RELEASE + 7.0.34 + 1.9.12 + + + + maven2-repository.dev.java.net + http://download.java.net/maven/2/ + + + + wso2-nexus + WSO2 internal Repository + http://maven.wso2.org/nexus/content/groups/wso2-public/ + + true + daily + ignore + + + + wso2-maven2-repository + WSO2 Maven2 Repository + http://dist.wso2.org/maven2 + + false + + + true + never + fail + + + + + maven2-repository-jococo + Maven2 Repository + http://repo1.maven.org/maven2/ + + + saucelabs-repository + https://repository-saucelabs.forge.cloudbees.com/release + + true + + + true + + + + + + + + com.google.code.gson + gson + 2.2 + + + + javax.inject + javax.inject + 1 + + + + org.codehaus.jackson + jackson-mapper-asl + ${org.codehaus.jackson.version} + + + + org.codehaus.jackson + jackson-jaxrs + ${org.codehaus.jackson.version} + + + + cglib + cglib-nodep + 2.2 + + + + org.springframework + spring-core + ${org.springframework.version} + + + + org.springframework + spring-context + ${org.springframework.version} + + + + org.springframework + spring-web + ${org.springframework.version} + + + + org.apache.tomcat.embed + tomcat-embed-core + ${org.apache.tomcat} + + + + org.apache.tomcat.embed + tomcat-embed-logging-juli + ${org.apache.tomcat} + + + + org.springframework.ws.wso2 + spring.framework + 3.1.0.wso2v1 + + + + org.springframework.ws.wso2 + spring.framework + 3.1.0.wso2v1 + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${org.apache.cxf.version} + + + org.apache.ws.xmlschema + xmlschema-core + + + + + + org.codehaus.jackson + jackson-core-lgpl + ${org.codehaus.jackson.version} + + + + org.codehaus.jackson + jackson-mapper-lgpl + ${org.codehaus.jackson.version} + + + + org.apache.cxf + cxf-rt-rs-security-cors + ${org.apache.cxf.version} + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/CoffeeConfig.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/CoffeeConfig.java new file mode 100644 index 0000000000..a11e2900c9 --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/CoffeeConfig.java @@ -0,0 +1,66 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.coffeesample; + +import org.apache.cxf.bus.spring.SpringBus; +import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; +import org.codehaus.jackson.jaxrs.JacksonJsonProvider; +import org.springframework.context.annotation.Bean; + +import javax.ws.rs.ext.RuntimeDelegate; +import java.util.Arrays; +import java.util.List; +import java.util.ArrayList; + +public class CoffeeConfig { + @Bean( destroyMethod = "shutdown" ) + public SpringBus cxf() { + return new SpringBus(); + } + + @Bean + public org.apache.cxf.endpoint.Server jaxRsServer() { + JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class ); + factory.setServiceBeans( Arrays.< Object >asList(starbucksOutletService()) ); + factory.setAddress( "/" + factory.getAddress() ); + List providers = new ArrayList(); + providers.add(jsonProvider()); + providers.add(new OrderReader()); + factory.setProviders(providers); + //factory.setProviders( Arrays.< Object >asList( jsonProvider() ) ); + return factory.create(); + } + + @Bean + public JaxRsApiApplication jaxRsApiApplication() { + return new JaxRsApiApplication(); + } + + @Bean + public StarbucksOutletService starbucksOutletService() { + return new StarbucksOutletServiceImpl(); + } + + + + @Bean + public JacksonJsonProvider jsonProvider() { + return new JacksonJsonProvider(); + } +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/JaxRsApiApplication.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/JaxRsApiApplication.java new file mode 100644 index 0000000000..8bd3542f9f --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/JaxRsApiApplication.java @@ -0,0 +1,26 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.coffeesample; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath( "api" ) +public class JaxRsApiApplication extends Application { +} \ No newline at end of file diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/OrderReader.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/OrderReader.java new file mode 100644 index 0000000000..1280fdc148 --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/OrderReader.java @@ -0,0 +1,62 @@ +package org.wso2.am.integration.services.jaxrs.coffeesample; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.wso2.am.integration.services.jaxrs.coffeesample.bean.Order; + +import javax.ws.rs.Consumes; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyReader; +import javax.ws.rs.ext.Provider; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +@Provider +@Consumes(MediaType.APPLICATION_JSON) +public class OrderReader implements MessageBodyReader { + + @Override + public Order readFrom(Class type, + Type type1, + Annotation[] antns, + MediaType mt, MultivaluedMap mm, + InputStream in) throws IOException, WebApplicationException { + + Order order = new Order(); + InputStreamReader reader = new InputStreamReader(in); + + JsonElement json = new JsonParser().parse(reader); + JsonObject jsonObject = json.getAsJsonObject(); + if(jsonObject.get("additions") != null) { + order.setAdditions(jsonObject.get("additions").getAsString()); + } else { + order.setAdditions(""); + } + if(jsonObject.get("drinkName") != null) { + order.setDrinkName(jsonObject.get("drinkName").getAsString()); + } else { + order.setDrinkName(""); + } + if(jsonObject.get("cost") != null) { + order.setCost(jsonObject.get("cost").getAsDouble()); + } + if(jsonObject.get("orderId") != null) { + order.setOrderId(jsonObject.get("orderId").getAsString()); + } + order.setLocked(false); + + return order; + } + + @Override + public boolean isReadable(Class type, Type type1, Annotation[] antns, MediaType mt) { + return Order.class.isAssignableFrom(type); + } + +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/StarbucksOutletService.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/StarbucksOutletService.java new file mode 100644 index 0000000000..bfa1490e04 --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/StarbucksOutletService.java @@ -0,0 +1,64 @@ +package org.wso2.am.integration.services.jaxrs.coffeesample; + + + +import org.wso2.am.integration.services.jaxrs.coffeesample.bean.Order; +import org.wso2.am.integration.services.jaxrs.coffeesample.bean.Payment; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +@Path("/") +public interface StarbucksOutletService { + + @POST + @Path("/orders/") +// @Produces(MediaType.TEXT_PLAIN) + @Produces(MediaType.APPLICATION_JSON) // produces application/json + @Consumes({MediaType.TEXT_XML, MediaType.APPLICATION_XML}) // consumes text/xml + public Response addOrder(Order orderBean); + + /** + * Read the following article on ATOM data binding in CXF + * http://goo.gl/UKJdM + * @param id order id + * @return the order + */ + @GET + @Path("/orders/{orderId}") + @Produces( { "application/json", "application/xml" } ) // produces atom and json as relevant + public Order getOrder(@PathParam("orderId") String id); + + @PUT + @Path("/orders/") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public Response updateOrder(Order orderBean); + + @GET + @Path("/orders/pending/") + @Produces( { "application/json", "application/atom+xml;type=feed", "application/xml" } ) // application/atom+xml and json + public Response getPendingOrders(); //todo add a atom feader + + @PUT + @Path("/orders/lock/{orderId}/") + @Produces({MediaType.APPLICATION_XML}) // application/xml + public Response lockOrder(@PathParam("orderId") String id); + + @DELETE + @Path("/orders/{orderId}/") + @Produces({MediaType.TEXT_PLAIN}) + public Response removeOrder(@PathParam("orderId") String id); + + @POST + @Path("/payment/{orderId}/") + @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_HTML} ) + public Response doPayment(@PathParam("orderId") String id, Payment payment); + + @GET + @Path("/payment/{orderId}/") + @Produces(MediaType.APPLICATION_JSON) + public Payment getPayment(@PathParam("orderId") String id); + +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/StarbucksOutletServiceImpl.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/StarbucksOutletServiceImpl.java new file mode 100755 index 0000000000..70579c01ff --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/StarbucksOutletServiceImpl.java @@ -0,0 +1,199 @@ +/* + * Copyright 2011-2012 WSO2, Inc. (http://wso2.com) + * + * 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 org.wso2.am.integration.services.jaxrs.coffeesample; + + +import org.wso2.am.integration.services.jaxrs.coffeesample.bean.Order; +import org.wso2.am.integration.services.jaxrs.coffeesample.bean.Payment; +import org.wso2.am.integration.services.jaxrs.coffeesample.bean.PaymentStatus; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.ConcurrentHashMap; + +/** + * + */ + +public class StarbucksOutletServiceImpl implements StarbucksOutletService{ + private Map ordersList = new ConcurrentHashMap(); + + private Map paymentRegister = new ConcurrentHashMap(); + + private final Map priceList = new ConcurrentHashMap(); + + private static final Random rand = new Random(); + +// long currentId = 123; +// Map customers = new HashMap(); +// Map orders = new HashMap(); + + public StarbucksOutletServiceImpl() { + init(); + } + + public Response addOrder(Order orderBean) { + String drinkName = orderBean.getDrinkName(); + String additions = orderBean.getAdditions(); + orderBean.setCost(calculateCost(drinkName, additions)); + ordersList.put(orderBean.getOrderId(), orderBean); + return Response.ok().entity(orderBean).type(MediaType.APPLICATION_JSON).build(); + } + + public Order getOrder(String id) { + return ordersList.get(id); + } + + public Response updateOrder(Order orderBean) { + String orderId = orderBean.getOrderId(); + String drinkName = orderBean.getDrinkName(); + String additions = orderBean.getAdditions(); + + Order order = ordersList.get(orderId); + if (order != null) { + if (order.isLocked()) { + return Response.notModified().type(MediaType.APPLICATION_JSON_TYPE).build(); + } else { + if (drinkName != null && !"".equals(drinkName)) { + order.setDrinkName(drinkName); + } else { + drinkName = order.getDrinkName(); //used to calculate the cost + } + order.setAdditions(additions); + order.setCost(calculateCost(drinkName, additions)); + return Response.ok(order).type(MediaType.APPLICATION_JSON_TYPE).build(); + } + } + return null; + } + + public Response getPendingOrders() { //todo write the client + List orders = new ArrayList(); + for (Order order : ordersList.values()) { + if (!order.isLocked()) { + orders.add(order); + } + } + return Response.ok(orders).type("application/atom+xml;type=feed").build(); + } + + public Response lockOrder(String id) { //@PathParam("orderId") + Order order = ordersList.get(id); + if (order != null) { + order.setLocked(true); + return Response.ok(order).type(MediaType.APPLICATION_XML).build(); + } + return Response.notModified().entity(id).type(MediaType.APPLICATION_XML).build(); + } + + public Response removeOrder(String id) { // @PathParam("orderId") + Boolean removed = ordersList.remove(id) != null; + paymentRegister.remove(id); + String status = removed.toString(); + return removed ? Response.ok(status).build() : Response.notModified().build(); + } + + public Response doPayment(String id, Payment payment) { // @PathParam("orderId") + String name = payment.getName(); + Double amount = payment.getAmount(); + String cardNumber = payment.getCardNumber(); + String expiryDate = payment.getExpiryDate(); + + PaymentStatus paymentStatus; + Payment registeredPayment = paymentRegister.get( id ); + if (registeredPayment != null) { + paymentStatus = new PaymentStatus("Duplicate Payment", registeredPayment); + return Response.notModified().entity(paymentStatus).type(MediaType.APPLICATION_JSON).build(); + } + + Order order = ordersList.get(id); + if (order == null) { + paymentStatus = new PaymentStatus("Invalid Order ID", null); + return Response.notModified().entity(paymentStatus).type(MediaType.APPLICATION_JSON).build(); + } + + if (!order.isAmountAcceptable(amount)) { + paymentStatus = new PaymentStatus("Insufficient Funds", null); + return Response.notModified().entity(paymentStatus).type(MediaType.APPLICATION_JSON).build(); + } + + registeredPayment = new Payment(id); + registeredPayment.setAmount(amount); + registeredPayment.setCardNumber(cardNumber); + registeredPayment.setExpiryDate(expiryDate); + registeredPayment.setName(name); + paymentRegister.put(id, registeredPayment); + paymentStatus = new PaymentStatus("Payment Accepted", registeredPayment); + return Response.ok().entity(paymentStatus).type(MediaType.APPLICATION_JSON).build(); + + } + + public Payment getPayment(String id) { // @PathParam("orderId") + return paymentRegister.get(id); + } + + private double calculateCost(String drinkName, String additions) { + double cost = getPrice(drinkName, false); + if (additions != null && !"".equals(additions)) { + String[] additionalItems = additions.split(" "); + for (String item : additionalItems) { + cost += getPrice(item, true); + } + } + return Double.parseDouble(Order.currencyFormat.format(cost)); + } + + private double getPrice(String item, boolean addition) { + synchronized (priceList) { + Double price = priceList.get(item); + if (price == null) { + if (addition) { + price = rand.nextDouble() * 5; + } else { + price = rand.nextInt(8) + 2 - 0.01; + } + priceList.put(item, price); + } + return price; + } + } + + private void init () { + String drinkName = "Vanilla Flavored Coffee"; + String additions = "Milk"; + Order order = new Order(); + order.setOrderId("123"); + order.setDrinkName(drinkName); + order.setAdditions(additions); + order.setCost( calculateCost(drinkName, additions) ); + + ordersList.put(order.getOrderId(), order); + + //following order is used by the Client class to show the HTTP DELETE + drinkName = "Chocolate Flavored Coffee"; + order = new Order(); + order.setOrderId("444"); + order.setDrinkName(drinkName); + order.setCost( calculateCost(drinkName, null) ); //no additions + + ordersList.put(order.getOrderId(), order); + } +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Customer.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Customer.java new file mode 100755 index 0000000000..891b8ac6df --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Customer.java @@ -0,0 +1,41 @@ +/* + * Copyright 2011-2012 WSO2, Inc. (http://wso2.com) + * + * 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 org.wso2.am.integration.services.jaxrs.coffeesample.bean; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "Customer") +public class Customer { + private long id; + private String name; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Order.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Order.java new file mode 100755 index 0000000000..1f566a0cdd --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Order.java @@ -0,0 +1,104 @@ +/* + * Copyright 2011-2012 WSO2, Inc. (http://wso2.com) + * + * 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 org.wso2.am.integration.services.jaxrs.coffeesample.bean; + +import javax.xml.bind.annotation.XmlRootElement; +import java.text.DateFormat; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +@XmlRootElement(name = "Order") +public class Order { + + private String orderId; + + private String drinkName; + + private String additions; + + private double cost; + + private boolean locked; //false by default + + private long timestamp; + + public static final NumberFormat currencyFormat = new DecimalFormat("#.##"); + private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'"); + + public Order() { + this.orderId = UUID.randomUUID().toString(); + this.timestamp = System.currentTimeMillis(); + } + + public String getOrderId() { + return orderId; + } + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public String getDrinkName() { + return drinkName; + } + + public void setDrinkName(String drinkName) { + this.drinkName = drinkName; +// this.setCost(calculateCost()); + this.timestamp = System.currentTimeMillis(); + } + + public String getAdditions() { + return additions; + } + + public void setAdditions(String additions) { + this.additions = additions; +// this.setCost(calculateCost()); + this.timestamp = System.currentTimeMillis(); + } + + public String getCost() { + return currencyFormat.format(cost); + } + + public void setCost(double cost) { + this.cost = cost; + } + + public boolean isLocked() { + return locked; + } + + public void setLocked(boolean locked) { + this.locked = locked; + } + + public String getTimestamp() { + return dateFormat.format(new Date(timestamp)); + } + + public void setTimestamp(Long timestamp) { + this.timestamp = timestamp; + } + + public boolean isAmountAcceptable(double amount) { + return amount >= cost; + } +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Payment.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Payment.java new file mode 100644 index 0000000000..646b09f1f6 --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Payment.java @@ -0,0 +1,62 @@ +package org.wso2.am.integration.services.jaxrs.coffeesample.bean; + +import javax.xml.bind.annotation.XmlRootElement; +import java.text.DecimalFormat; +import java.text.NumberFormat; + +@XmlRootElement (name = "Payment") +public class Payment { + + private static final NumberFormat currencyFormat = new DecimalFormat("#.##"); + + private String orderId; + private String name; + private String cardNumber; + private String expiryDate; + private Double amount; + + public Payment(String orderId) { + this.orderId = orderId; + } + + public Payment() { + + } + + public String getOrderId() { + return orderId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCardNumber() { + return cardNumber; + } + + public void setCardNumber(String cardNumber) { + this.cardNumber = cardNumber; + } + + public String getExpiryDate() { + return expiryDate; + } + + public void setExpiryDate(String expiryDate) { + this.expiryDate = expiryDate; + } + + public Double getAmount() { + return Double.valueOf(currencyFormat.format(amount)); + } + + public void setAmount(Double amount) { + this.amount = amount; + } + +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/PaymentStatus.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/PaymentStatus.java new file mode 100644 index 0000000000..349237b79f --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/PaymentStatus.java @@ -0,0 +1,63 @@ +package org.wso2.am.integration.services.jaxrs.coffeesample.bean; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "PaymentStatus") +public class PaymentStatus { + + /** + * If XmlElement wasn't there, the generated element name will be simple letters, 'status' + * Here, we modified it to 'Status' + * + * name is of type String, and required is of type boolean + * + * Since the required attribute is set to true, no get method for this variable + */ + @XmlElement(name = "Status", required = true) + private String status; + + /** + * Since Payment class is also a bean, the JSON content generated by this bean + * will be wrapped in to PaymentStatus bean + * ex. + * { + * "PaymentStatus": + * { + * "Payment":{"amount":50,"cardNumber":"1234 2345 3456 4567","expiryDate":"01-01-2015","name":"Kasun Gajasinghe"}, + * "Status":"Payment Accepted" + * } + * } + * + */ + @XmlElement(name = "Payment", required = true) + private Payment payment; + + public PaymentStatus(String status, Payment payment) { + this.setStatus(status); + this.setPayment(payment); + } + + /** + * A no-arg default constructor is needed for proper operation of JAX-RS + */ + public PaymentStatus() { + + } + +// public String getStatus() { +// return status; +// } +// +// public Payment getPayment() { +// return payment; +// } + + public void setStatus(String status) { + this.status = status; + } + + public void setPayment(Payment payment) { + this.payment = payment; + } +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/CustomerConfig.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/CustomerConfig.java new file mode 100644 index 0000000000..7e0e0f6db1 --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/CustomerConfig.java @@ -0,0 +1,59 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.customersample; + +import org.apache.cxf.bus.spring.SpringBus; +import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; +import org.codehaus.jackson.jaxrs.JacksonJsonProvider; +import org.springframework.context.annotation.Bean; + + +import javax.ws.rs.ext.RuntimeDelegate; +import java.util.Arrays; + +public class CustomerConfig { + @Bean( destroyMethod = "shutdown" ) + public SpringBus cxf() { + return new SpringBus(); + } + + @Bean + public org.apache.cxf.endpoint.Server jaxRsServer() { + JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class ); + factory.setServiceBeans( Arrays.< Object >asList(customerService()) ); + factory.setAddress( "/" + factory.getAddress() ); + factory.setProviders( Arrays.< Object >asList( jsonProvider() ) ); + return factory.create(); + } + + @Bean + public JaxRsApiApplication jaxRsApiApplication() { + return new JaxRsApiApplication(); + } + + @Bean + public CustomerService customerService() { + return new CustomerService(); + } + + @Bean + public JacksonJsonProvider jsonProvider() { + return new JacksonJsonProvider(); + } +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/CustomerService.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/CustomerService.java new file mode 100755 index 0000000000..846f2f967d --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/CustomerService.java @@ -0,0 +1,122 @@ +/* + * Copyright 2011-2012 WSO2, Inc. (http://wso2.com) + * + * 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 org.wso2.am.integration.services.jaxrs.customersample; + +import org.wso2.am.integration.services.jaxrs.customersample.bean.Customer; +import org.wso2.am.integration.services.jaxrs.customersample.bean.Order; + +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import java.util.HashMap; +import java.util.Map; + +@Path("/customerservice/") +public class CustomerService { + long currentId = 123; + Map customers = new HashMap(); + Map orders = new HashMap(); + + public CustomerService() { + init(); + } + + @GET + @Path("/customers/{id}/") + public Customer getCustomer(@PathParam("id") String id) { + System.out.println("----invoking getCustomer, Customer id is: " + id); + long idNumber = Long.parseLong(id); + Customer c = customers.get(idNumber); + return c; + } + + @PUT + @Path("/customers/") + public Response updateCustomer(Customer customer) { + System.out.println("----invoking updateCustomer, Customer name is: " + customer.getName()); + Customer c = customers.get(customer.getId()); + Response r; + if (c != null) { + customers.put(customer.getId(), customer); + r = Response.ok().build(); + } else { + r = Response.notModified().build(); + } + + return r; + } + + @POST + @Path("/customers/") + public Response addCustomer(Customer customer) { + System.out.println("----invoking addCustomer, Customer name is: " + customer.getName()); + customer.setId(++currentId); + + customers.put(customer.getId(), customer); + + return Response.ok(customer).build(); + } + + // Adding a new method to demonstrate Consuming and Producing text/plain + + @POST + @Path("/customers/name/") + @Consumes("text/plain") + @Produces("text/plain") + public String getCustomerName(String id) { + System.out.println("----invoking getCustomerName, Customer id is: " + id); + return "Isuru Suriarachchi"; + } + + @DELETE + @Path("/customers/{id}/") + public Response deleteCustomer(@PathParam("id") String id) { + System.out.println("----invoking deleteCustomer, Customer id is: " + id); + long idNumber = Long.parseLong(id); + Customer c = customers.get(idNumber); + + Response r; + if (c != null) { + r = Response.ok().build(); + customers.remove(idNumber); + } else { + r = Response.notModified().build(); + } + + return r; + } + + @Path("/orders/{orderId}/") + public Order getOrder(@PathParam("orderId") String orderId) { + System.out.println("----invoking getOrder, Order id is: " + orderId); + long idNumber = Long.parseLong(orderId); + Order c = orders.get(idNumber); + return c; + } + + final void init() { + Customer c = new Customer(); + c.setName("John"); + c.setId(123); + customers.put(c.getId(), c); + + Order o = new Order(); + o.setDescription("order 223"); + o.setId(223); + orders.put(o.getId(), o); + } + +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/JaxRsApiApplication.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/JaxRsApiApplication.java new file mode 100644 index 0000000000..59630752f9 --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/JaxRsApiApplication.java @@ -0,0 +1,26 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.customersample; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath( "api" ) +public class JaxRsApiApplication extends Application { +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Customer.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Customer.java new file mode 100755 index 0000000000..d9f88eadf6 --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Customer.java @@ -0,0 +1,41 @@ +/* + * Copyright 2011-2012 WSO2, Inc. (http://wso2.com) + * + * 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 org.wso2.am.integration.services.jaxrs.customersample.bean; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "Customer") +public class Customer { + private long id; + private String name; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Order.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Order.java new file mode 100755 index 0000000000..a6fe93985a --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Order.java @@ -0,0 +1,66 @@ +/* + * Copyright 2011-2012 WSO2, Inc. (http://wso2.com) + * + * 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 org.wso2.am.integration.services.jaxrs.customersample.bean; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.HashMap; +import java.util.Map; + +@XmlRootElement(name = "Order") +public class Order { + private long id; + private String description; + private Map products = new HashMap(); + + public Order() { + init(); + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String d) { + this.description = d; + } + + @GET + @Path("products/{productId}/") + public Product getProduct(@PathParam("productId")int productId) { + System.out.println("----invoking getProduct with id: " + productId); + Product p = products.get(new Long(productId)); + return p; + } + + final void init() { + Product p = new Product(); + p.setId(323); + p.setDescription("product 323"); + products.put(p.getId(), p); + } +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Product.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Product.java new file mode 100755 index 0000000000..ab48cab26b --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Product.java @@ -0,0 +1,41 @@ +/* + * Copyright 2011-2012 WSO2, Inc. (http://wso2.com) + * + * 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 org.wso2.am.integration.services.jaxrs.customersample.bean; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "Product") +public class Product { + private long id; + private String description; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String d) { + this.description = d; + } +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/AppConfig.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/AppConfig.java new file mode 100644 index 0000000000..6e53fe1672 --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/AppConfig.java @@ -0,0 +1,66 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.peoplesample; + +import org.apache.cxf.bus.spring.SpringBus; +import org.apache.cxf.endpoint.Server; +import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; +import org.codehaus.jackson.jaxrs.JacksonJsonProvider; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.ws.rs.ext.RuntimeDelegate; +import java.util.Arrays; + +@Configuration +public class AppConfig { + @Bean( destroyMethod = "shutdown" ) + public SpringBus cxf() { + return new SpringBus(); + } + + @Bean + public Server jaxRsServer() { + JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class ); + factory.setServiceBeans( Arrays.< Object >asList( peopleRestService() ) ); + factory.setAddress( "/" + factory.getAddress() ); + factory.setProviders( Arrays.< Object >asList( jsonProvider() ) ); + return factory.create(); + } + + @Bean + public JaxRsApiApplication jaxRsApiApplication() { + return new JaxRsApiApplication(); + } + + @Bean + public PeopleRestService peopleRestService() { + return new PeopleRestService(); + } + + @Bean + public PeopleService peopleService() { + return new PeopleService(); + } + + @Bean + public JacksonJsonProvider jsonProvider() { + return new JacksonJsonProvider(); + } +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/JaxRsApiApplication.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/JaxRsApiApplication.java new file mode 100644 index 0000000000..84dabe5495 --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/JaxRsApiApplication.java @@ -0,0 +1,26 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.peoplesample; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath( "api" ) +public class JaxRsApiApplication extends Application { +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/PeopleRestService.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/PeopleRestService.java new file mode 100644 index 0000000000..56c905d3b2 --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/PeopleRestService.java @@ -0,0 +1,149 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.peoplesample; + + +import org.wso2.am.integration.services.jaxrs.peoplesample.bean.Person; +import org.apache.cxf.rs.security.cors.CorsHeaderConstants; + +import javax.inject.Inject; +import javax.ws.rs.*; +import javax.ws.rs.core.*; +import java.util.Collection; + +@Path("/people") +public class PeopleRestService { + @Inject + private PeopleService peopleService; + + public void PeopleRestService() { + peopleService.setInitPeople(); + } + + @Produces({MediaType.APPLICATION_JSON}) + @GET + public Collection getPeople(@QueryParam("page") @DefaultValue("1") final int page) { + return peopleService.getPeople(page, 5); + } + + @Produces({MediaType.APPLICATION_JSON}) + @PUT + public Person addPerson(@FormParam("email") final String email) { + return peopleService.addPerson(email); + } + + @Produces({MediaType.APPLICATION_JSON}) + @Path("/{email}") + @GET + public Person getPeople(@PathParam("email") final String email) { + return peopleService.getByEmail(email); + } + +/* + @Produces( { MediaType.APPLICATION_FORM_URLENCODED } ) + @POST + public Response addPerson( @Context final UriInfo uriInfo, + @FormParam( "email" ) final String email, + @FormParam( "firstName" ) final String firstName, + @FormParam( "lastName" ) final String lastName ) { + peopleService.addPerson( email, firstName, lastName ); + return Response.created( uriInfo.getRequestUriBuilder().path( email ).build() ).build(); + } + +*/ + + @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_FORM_URLENCODED}) + @POST + public Response addPersonQueryParam(@Context final UriInfo uriInfo, + @QueryParam("email") final String email, + @QueryParam("firstName") final String firstName, + @QueryParam("lastName") final String lastName) { + peopleService.addPerson(email, firstName, lastName); + return Response.created(uriInfo.getRequestUriBuilder().path(email).build()).build(); + } + + /* @Produces({MediaType.APPLICATION_JSON}) + @Path("/{email}") + @PUT + public Person updatePerson(@PathParam("email") final String email, + @FormParam("firstName") final String firstName, + @FormParam("lastName") final String lastName) { + + final Person person = peopleService.getByEmail(email); + if (firstName != null) { + person.setFirstName(firstName); + } + + if (lastName != null) { + person.setLastName(lastName); + } + + return person; + } +*/ + @Produces({MediaType.APPLICATION_JSON}) + @Path("/{email}") + @HEAD + public Response checkPerson(@PathParam("email") final String email) { + if (peopleService.checkPersonByEmail(email)) { + return Response.ok().build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + + } + + @Produces({MediaType.APPLICATION_JSON}) + @Path("/{email}") + @PUT + public Person updatePersonQueryParam(@PathParam("email") final String email, + @QueryParam("firstName") final String firstName, + @QueryParam("lastName") final String lastName) { + + final Person person = peopleService.getByEmail(email); + if (firstName != null) { + person.setFirstName(firstName); + } + + if (lastName != null) { + person.setLastName(lastName); + } + + return person; + } + + @Path("/{email}") + @DELETE + public Response deletePerson(@PathParam("email") final String email) { + peopleService.removePerson(email); + return Response.ok().build(); + } + + @Produces({MediaType.APPLICATION_JSON}) + @Path("/options") + @OPTIONS + public Response getOptions(@Context HttpHeaders headers, + @Context Request request) { + return Response.ok() + .header(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS, "GET POST DELETE PUT OPTIONS") + .header(CorsHeaderConstants.HEADER_AC_ALLOW_CREDENTIALS, "false") + .header(CorsHeaderConstants.HEADER_AC_REQUEST_HEADERS, MediaType.APPLICATION_JSON) + .build(); + } +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/PeopleService.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/PeopleService.java new file mode 100644 index 0000000000..4d75c2af81 --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/PeopleService.java @@ -0,0 +1,99 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.peoplesample; + +import org.springframework.stereotype.Service; +import org.wso2.am.integration.services.jaxrs.peoplesample.bean.Person; +import org.wso2.am.integration.services.jaxrs.peoplesample.exceptions.PersonAlreadyExistsException; +import org.wso2.am.integration.services.jaxrs.peoplesample.exceptions.PersonNotFoundException; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +@Service +public class PeopleService { + private ConcurrentMap< String, Person> persons = new ConcurrentHashMap< String, Person >(); + public void setInitPeople() + { + + for(int count =1;count <=10; count ++) + { + Person newPerson= new Person(); + newPerson.setEmail(String.format("test-%d@wso2.com",count)); + newPerson.setFirstName(String.format("testUser%d",count)); + newPerson.setLastName(String.format("testLasrName%d",count)); + persons.putIfAbsent(String.format("test-%d@wso2.com",count),newPerson) ; + } + } + public Collection< Person > getPeople( int page, int pageSize ) { + Collection< Person > person = new ArrayList< Person >( pageSize ); + + for( int index = 0; index < pageSize; ++index ) { + person.add( new Person( String.format( "person+%d@at.com", ( pageSize * ( page - 1 ) + index + 1 ) ) ) ); + } + setInitPeople(); + return person; + } + + public Person addPerson( String email ) { + + return new Person( email ); + } + + public Person getByEmail( final String email ) { + final Person person = persons.get( email ); + if( person == null ) { + throw new PersonNotFoundException( email ); + } + + return person; + } + + public boolean checkPersonByEmail(final String email) + { + boolean personExists= true; + final Person person = persons.get( email ); + if( person == null ) { + personExists=false; + } + return personExists; + } + + public Person addPerson( final String email, final String firstName, final String lastName ) { + final Person person = new Person( email ); + person.setFirstName( firstName ); + person.setLastName( lastName ); + + if( persons.putIfAbsent( email, person ) != null ) { + throw new PersonAlreadyExistsException( email ); + } + + return person; + } + + public void removePerson( final String email ) { + if( persons.remove( email ) == null ) { + throw new PersonNotFoundException( email ); + } + } + + +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/Starter.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/Starter.java new file mode 100644 index 0000000000..01c2d03c95 --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/Starter.java @@ -0,0 +1,70 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.peoplesample; + +import java.io.File; +import java.io.IOException; + +import org.apache.catalina.Context; +import org.apache.catalina.loader.WebappLoader; +import org.apache.catalina.startup.Tomcat; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.cxf.transport.servlet.CXFServlet; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; + +public class Starter { + private final static Log log = LogFactory.getLog(Starter.class); + + public void startPeopleService() throws Exception { + final File base = createBaseDirectory(); + log.info("Using base folder: " + base.getAbsolutePath()); + + final Tomcat tomcat = new Tomcat(); + tomcat.setPort(8080); + tomcat.setBaseDir(base.getAbsolutePath()); + + Context context = tomcat.addContext("/", base.getAbsolutePath()); + Tomcat.addServlet(context, "CXFServlet", new CXFServlet()); + + context.addServletMapping("/rest/*", "CXFServlet"); + context.addApplicationListener(ContextLoaderListener.class.getName()); + context.setLoader(new WebappLoader(Thread.currentThread().getContextClassLoader())); + + context.addParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName()); + context.addParameter("contextConfigLocation", AppConfig.class.getName()); + + tomcat.start(); + tomcat.getServer().await(); + } + + private static File createBaseDirectory() throws IOException { + final File base = File.createTempFile("tmp-", "", new File("/home/dharshana/reaserch/jetty/jetty2/src/main/resources")); + + if (!base.delete()) { + throw new IOException("Cannot (re)create base folder: " + base.getAbsolutePath()); + } + + if (!base.mkdir()) { + throw new IOException("Cannot create base folder: " + base.getAbsolutePath()); + } + return base; + } +} \ No newline at end of file diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/bean/Person.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/bean/Person.java new file mode 100644 index 0000000000..04874c2e79 --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/bean/Person.java @@ -0,0 +1,56 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.peoplesample.bean; + +public class Person { + private String email; + private String firstName; + private String lastName; + + public Person() { + } + + public Person( final String email ) { + this.email = email; + } + + public String getEmail() { + return email; + } + + public void setEmail( final String email ) { + this.email = email; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public void setFirstName( final String firstName ) { + this.firstName = firstName; + } + + public void setLastName( final String lastName ) { + this.lastName = lastName; + } +} \ No newline at end of file diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/exceptions/PersonAlreadyExistsException.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/exceptions/PersonAlreadyExistsException.java new file mode 100644 index 0000000000..b50fad8030 --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/exceptions/PersonAlreadyExistsException.java @@ -0,0 +1,36 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.peoplesample.exceptions; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +public class PersonAlreadyExistsException extends WebApplicationException { + private static final long serialVersionUID = 6817489620338221395L; + + public PersonAlreadyExistsException( final String email ) { + super( + Response + .status( Status.CONFLICT ) + .entity( "Person already exists: " + email ) + .build() + ); + } +} diff --git a/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/exceptions/PersonNotFoundException.java b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/exceptions/PersonNotFoundException.java new file mode 100644 index 0000000000..9631eee325 --- /dev/null +++ b/modules/integration/backend-service/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/exceptions/PersonNotFoundException.java @@ -0,0 +1,36 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.peoplesample.exceptions; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +public class PersonNotFoundException extends WebApplicationException { + private static final long serialVersionUID = -2894269137259898072L; + + public PersonNotFoundException( final String email ) { + super( + Response + .status( Status.NOT_FOUND ) + .entity( "Person not found: " + email ) + .build() + ); + } +} diff --git a/modules/integration/pom.xml b/modules/integration/pom.xml new file mode 100644 index 0000000000..ca1982e1c2 --- /dev/null +++ b/modules/integration/pom.xml @@ -0,0 +1,58 @@ + + + + + org.wso2.am + am-parent + 1.7.0-SNAPSHOT + ../../pom.xml + + + 4.0.0 + integration + WSO2 API Manager - Integration Tests + + + org.wso2.carbon.automation + org.wso2.carbon.automation.extensions + 4.3.1 + + + org.testng + testng + 6.8.5 + + + pom + + + tests-common + tests-integration/tests-scenario + + + + + + + + + + + maven-clean-plugin + 2.4.1 + + + auto-clean + initialize + + clean + + + + + + + + diff --git a/modules/integration/tests-common/admin-clients/pom.xml b/modules/integration/tests-common/admin-clients/pom.xml new file mode 100644 index 0000000000..bdf3dc8a16 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/pom.xml @@ -0,0 +1,19 @@ + + + + + org.wso2.am + integration-test-common + 1.7.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + admin-clients + 1.7.0-SNAPSHOT + jar + WSO2 API Manager - Integration - Tests Common - Admin Clients + + diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/aar/services/AARServiceUploaderClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/aar/services/AARServiceUploaderClient.java new file mode 100644 index 0000000000..0a46325cc0 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/aar/services/AARServiceUploaderClient.java @@ -0,0 +1,88 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.aar.services; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.aarservices.stub.ExceptionException; +import org.wso2.carbon.aarservices.stub.ServiceUploaderStub; +import org.wso2.carbon.aarservices.stub.types.carbon.AARServiceData; + +import javax.activation.DataHandler; +import java.net.MalformedURLException; +import java.net.URL; +import java.rmi.RemoteException; + +public class AARServiceUploaderClient { + private static final Log log = LogFactory.getLog(AARServiceUploaderClient.class); + + private ServiceUploaderStub serviceUploaderStub; + private final String serviceName = "ServiceUploader"; + + public AARServiceUploaderClient(String backEndUrl, String sessionCookie) throws AxisFault { + + String endPoint = backEndUrl + serviceName; + try { + serviceUploaderStub = new ServiceUploaderStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, serviceUploaderStub); + } catch (AxisFault axisFault) { + log.error("ServiceUploaderStub Initialization fail " + axisFault.getMessage()); + throw new AxisFault( + "ServiceUploaderStub Initialization fail " + axisFault.getMessage()); + } + } + + public AARServiceUploaderClient(String backEndUrl, String userName, String password) + throws AxisFault { + String endPoint = backEndUrl + serviceName; + try { + serviceUploaderStub = new ServiceUploaderStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, serviceUploaderStub); + } catch (AxisFault axisFault) { + log.error("ServiceUploaderStub Initialization fail " + axisFault.getMessage()); + throw new AxisFault( + "ServiceUploaderStub Initialization fail " + axisFault.getMessage()); + } + } + + public void uploadAARFile(String fileName, String filePath, + String serviceHierarchy) + throws ExceptionException, RemoteException, MalformedURLException { + AARServiceData aarServiceData; + + aarServiceData = new AARServiceData(); + aarServiceData.setFileName(fileName); + aarServiceData.setDataHandler(createDataHandler(filePath)); + aarServiceData.setServiceHierarchy(serviceHierarchy); + serviceUploaderStub.uploadService(new AARServiceData[] { aarServiceData }); + } + + private DataHandler createDataHandler(String filePath) throws MalformedURLException { + URL url = null; + try { + url = new URL("file://" + filePath); + } catch (MalformedURLException e) { + log.error("File path URL is invalid" + e); + throw new MalformedURLException("File path URL is invalid" + e); + } + DataHandler dh = new DataHandler(url); + return dh; + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/client/utils/AuthenticateStub.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/client/utils/AuthenticateStub.java new file mode 100644 index 0000000000..4d5c9241bd --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/client/utils/AuthenticateStub.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2010, 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 org.wso2.am.admin.clients.client.utils; + +import org.apache.axis2.addressing.EndpointReference; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; +import org.apache.axis2.client.Stub; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.utils.CarbonUtils; + +/** + * This class authenticate stubs with valid session cookie + */ +public class AuthenticateStub { + private static final Log log = LogFactory.getLog(AuthenticateStub.class); + + /** + * Stub authentication method + * + * @param stub valid stub + * @param sessionCookie session cookie + */ + public static void authenticateStub(String sessionCookie, Stub stub) { + long soTimeout = 5 * 60 * 1000; // Three minutes + + ServiceClient client = stub._getServiceClient(); + Options option = client.getOptions(); + option.setManageSession(true); + option.setTimeOutInMilliSeconds(soTimeout); + option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, + sessionCookie); + if (log.isDebugEnabled()) { + log.debug("AuthenticateStub : Stub created with session " + sessionCookie); + } + } + + public static Stub authenticateStub(Stub stub, String sessionCookie, String backendURL) { + long soTimeout = 5 * 60 * 1000; // Three minutes + + ServiceClient client = stub._getServiceClient(); + Options option = client.getOptions(); + option.setManageSession(true); + option.setTimeOutInMilliSeconds(soTimeout); + System.out.println("XXXXXXXXXXXXXXXXXXX" + + backendURL + client.getServiceContext().getAxisService().getName() + .replaceAll("[^a-zA-Z]", "")); + option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, + sessionCookie); + option.setTo(new EndpointReference(backendURL + + client.getServiceContext().getAxisService().getName() + .replaceAll("[^a-zA-Z]", ""))); + if (log.isDebugEnabled()) { + log.debug("AuthenticateStub : Stub created with session " + sessionCookie); + } + + return stub; + } + + /** + * Authenticate the given web service stub against the Product user manager. This + * will make it possible to use the stub for invoking Product admin services. + * + * @param stub Axis2 service stub which needs to be authenticated + */ + public static void authenticateStub(String userName, String password, Stub stub) { + CarbonUtils.setBasicAccessSecurityHeaders(userName, password, stub._getServiceClient()); + } +} \ No newline at end of file diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/endpoint/EndPointAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/endpoint/EndPointAdminClient.java new file mode 100755 index 0000000000..1429cbbe5c --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/endpoint/EndPointAdminClient.java @@ -0,0 +1,136 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.endpoint; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.endpoint.stub.types.EndpointAdminEndpointAdminException; +import org.wso2.carbon.endpoint.stub.types.EndpointAdminStub; +import org.wso2.carbon.endpoint.stub.types.service.EndpointMetaData; + +import javax.activation.DataHandler; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.rmi.RemoteException; + +public class EndPointAdminClient { + private static final Log log = LogFactory.getLog(EndPointAdminClient.class); + + private final String serviceName = "EndpointAdmin"; + private EndpointAdminStub endpointAdminStub; + + public EndPointAdminClient(String backEndUrl, String sessionCookie) throws AxisFault { + String endPoint = backEndUrl + serviceName; + endpointAdminStub = new EndpointAdminStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, endpointAdminStub); + } + + public EndPointAdminClient(String backEndURL, String userName, String password) + throws AxisFault { + String endPoint = backEndURL + serviceName; + endpointAdminStub = new EndpointAdminStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, endpointAdminStub); + } + + public boolean addEndPoint(DataHandler dh) + throws EndpointAdminEndpointAdminException, IOException, XMLStreamException { + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + //create the builder + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement endPointElem = builder.getDocumentElement(); + return endpointAdminStub.addEndpoint(endPointElem.toString()); + } + + public boolean addEndPoint(OMElement endPointElem) + throws EndpointAdminEndpointAdminException, IOException, XMLStreamException { + return endpointAdminStub.addEndpoint(endPointElem.toString()); + } + + public boolean addDynamicEndPoint(String key, DataHandler dh) + throws EndpointAdminEndpointAdminException, IOException, XMLStreamException { + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + //create the builder + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement endPointElem = builder.getDocumentElement(); + return endpointAdminStub.addDynamicEndpoint(key, endPointElem.toString()); + } + + public boolean addDynamicEndPoint(String key, OMElement endPointElem) + throws EndpointAdminEndpointAdminException, IOException, XMLStreamException { + return endpointAdminStub.addDynamicEndpoint(key, endPointElem.toString()); + } + + public int getEndpointCount() throws EndpointAdminEndpointAdminException, RemoteException { + return endpointAdminStub.getEndpointCount(); + } + + public String[] getEndpointNames() throws EndpointAdminEndpointAdminException, RemoteException { + return endpointAdminStub.getEndPointsNames(); + } + + public int getDynamicEndpointCount() + throws EndpointAdminEndpointAdminException, RemoteException { + return endpointAdminStub.getDynamicEndpointCount(); + } + + public String getDynamicEndpoint(String key) + throws EndpointAdminEndpointAdminException, RemoteException { + return endpointAdminStub.getDynamicEndpoint(key); + } + + public String[] getDynamicEndpoints() + throws EndpointAdminEndpointAdminException, RemoteException { + return endpointAdminStub.getDynamicEndpoints(); + } + + public void enableEndpointStatistics(String endpointName) + throws RemoteException, EndpointAdminEndpointAdminException { + endpointAdminStub.enableStatistics(endpointName); + String endpoint = endpointAdminStub.getEndpointConfiguration(endpointName); + assert (endpoint.contains("statistics=\"enable")); + } + + public boolean deleteEndpoint(String endpointName) + throws RemoteException, EndpointAdminEndpointAdminException { + return endpointAdminStub.deleteEndpoint(endpointName); + } + + public boolean deleteDynamicEndpoint(String key) + throws RemoteException, EndpointAdminEndpointAdminException { + return endpointAdminStub.deleteDynamicEndpoint(key); + } + + public String getEndpointConfiguration(String endpointName) + throws RemoteException, EndpointAdminEndpointAdminException { + return endpointAdminStub.getEndpointConfiguration(endpointName); + } + + public EndpointMetaData[] getEndpointsData() + throws EndpointAdminEndpointAdminException, IOException, XMLStreamException { + return endpointAdminStub.getEndpointsData(); + } + +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/executor/PriorityMediationAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/executor/PriorityMediationAdminClient.java new file mode 100644 index 0000000000..d41734e29b --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/executor/PriorityMediationAdminClient.java @@ -0,0 +1,79 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.executor; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.priority.executors.stub.PriorityMediationAdminStub; + +import javax.activation.DataHandler; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.rmi.RemoteException; + +public class PriorityMediationAdminClient { + String backendUrl = null; + String SessionCookie = null; + PriorityMediationAdminStub priorityMediationAdmin; + private static final Log log = LogFactory.getLog(PriorityMediationAdminClient.class); + + public PriorityMediationAdminClient(String backendUrl, String sessionCookie) { + this.backendUrl = backendUrl; + this.SessionCookie = sessionCookie; + } + + private PriorityMediationAdminStub setPriorityExecutorStub() throws AxisFault { + final String priorityAdminServiceUrl = backendUrl + "PriorityMediationAdmin"; + PriorityMediationAdminStub priorityMediator = null; + priorityMediator = new PriorityMediationAdminStub(priorityAdminServiceUrl); + AuthenticateStub.authenticateStub(SessionCookie, priorityMediator); + return priorityMediator; + } + + public void addPriorityMediator(String name, DataHandler dh) + throws IOException, XMLStreamException { + priorityMediationAdmin = this.setPriorityExecutorStub(); + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement messageProcessorElem = builder.getDocumentElement(); + priorityMediationAdmin.add(name, messageProcessorElem); + } + + public void addPriorityMediator(String name, OMElement priorityExecutor) + throws RemoteException { + priorityMediationAdmin = this.setPriorityExecutorStub(); + priorityMediationAdmin.add(name, priorityExecutor); + } + + public String[] getExecutorList() throws RemoteException { + return priorityMediationAdmin.getExecutorList(); + } + + public void remove(String executorName) throws RemoteException { + priorityMediationAdmin.remove(executorName); + } + +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/localentry/AdminServiceLocalEntryAdminService.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/localentry/AdminServiceLocalEntryAdminService.java new file mode 100755 index 0000000000..b69bad02ee --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/localentry/AdminServiceLocalEntryAdminService.java @@ -0,0 +1,73 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.localentry; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.localentry.stub.types.LocalEntryAdminException; +import org.wso2.carbon.localentry.stub.types.LocalEntryAdminServiceStub; + +import javax.activation.DataHandler; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.rmi.RemoteException; + +public class AdminServiceLocalEntryAdminService { + private static final Log log = LogFactory.getLog(AdminServiceLocalEntryAdminService.class); + + private final String serviceName = "LocalEntryAdmin"; + private LocalEntryAdminServiceStub localEntryAdminServiceStub; + private String endPoint; + + public AdminServiceLocalEntryAdminService(String backEndUrl) throws AxisFault { + this.endPoint = backEndUrl + serviceName; + localEntryAdminServiceStub = new LocalEntryAdminServiceStub(endPoint); + } + + public void addLocalEntry(String sessionCookie, DataHandler dh) + throws LocalEntryAdminException, IOException, XMLStreamException { + AuthenticateStub.authenticateStub(sessionCookie, localEntryAdminServiceStub); + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + //create the builder + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement localEntryElem = builder.getDocumentElement(); + localEntryAdminServiceStub.addEntry(localEntryElem.toString()); + + } + + public void deleteLocalEntry(String sessionCookie, String localEntryKey) + throws LocalEntryAdminException, RemoteException { + AuthenticateStub.authenticateStub(sessionCookie, localEntryAdminServiceStub); + localEntryAdminServiceStub.deleteEntry(localEntryKey); + + } + + public OMElement getLocalEntry(String sessionCookie, String localEntryKey) + throws LocalEntryAdminException, RemoteException { + AuthenticateStub.authenticateStub(sessionCookie, localEntryAdminServiceStub); + return (OMElement) localEntryAdminServiceStub.getEntry(localEntryKey); + + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/localentry/LocalEntriesAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/localentry/LocalEntriesAdminClient.java new file mode 100644 index 0000000000..316ee8ed0c --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/localentry/LocalEntriesAdminClient.java @@ -0,0 +1,145 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.localentry; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.localentry.stub.types.LocalEntryAdminException; +import org.wso2.carbon.localentry.stub.types.LocalEntryAdminServiceStub; + +import javax.activation.DataHandler; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.rmi.RemoteException; + +public class LocalEntriesAdminClient { + + private static final Log log = LogFactory.getLog(LocalEntriesAdminClient.class); + + private LocalEntryAdminServiceStub localEntryAdminServiceStub; + private final String serviceName = "LocalEntryAdmin"; + + /** + * creation of LocalEntriesAdminClient using sessionCokkie + * + * @param backendUrl + * @param sessionCookie + * @throws AxisFault + */ + public LocalEntriesAdminClient(String backendUrl, String sessionCookie) throws AxisFault { + String endPoint = backendUrl + serviceName; + localEntryAdminServiceStub = new LocalEntryAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, localEntryAdminServiceStub); + } + + /** + * Creation of LocalEntriesAdminClient using userName and password + * + * @param backendUrl + * @param userName + * @param password + * @throws AxisFault + */ + + public LocalEntriesAdminClient(String backendUrl, String userName, String password) + throws AxisFault { + String endPoint = backendUrl + serviceName; + localEntryAdminServiceStub = new LocalEntryAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, localEntryAdminServiceStub); + } + + /** + * Add Local entry by DataHandler + * + * @param dh + * @return + * @throws java.io.IOException + * @throws LocalEntryAdminException + * @throws javax.xml.stream.XMLStreamException + */ + public boolean addLocalEntery(DataHandler dh) + throws IOException, LocalEntryAdminException, XMLStreamException { + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement localEntryElem = builder.getDocumentElement(); + return (localEntryAdminServiceStub.addEntry(localEntryElem.toString())); + } + + /** + * Add local entry by OMElement + * + * @param localEntry + * @return + * @throws LocalEntryAdminException + * @throws java.rmi.RemoteException + */ + public boolean addLocalEntry(OMElement localEntry) + throws LocalEntryAdminException, RemoteException { + return (localEntryAdminServiceStub.addEntry(localEntry.toString())); + } + + /** + * Delete local entry + * + * @param localEntryKey + * @return + * @throws LocalEntryAdminException + * @throws java.rmi.RemoteException + */ + public boolean deleteLocalEntry(String localEntryKey) + throws LocalEntryAdminException, RemoteException { + return (localEntryAdminServiceStub.deleteEntry(localEntryKey)); + } + + /** + * @return + * @throws LocalEntryAdminException + * @throws java.rmi.RemoteException + */ + public String getEntryNamesString() + throws LocalEntryAdminException, RemoteException { + return localEntryAdminServiceStub.getEntryNamesString(); + } + + /** + * @return + * @throws LocalEntryAdminException + * @throws java.rmi.RemoteException + */ + public int getEntryDataCount() + throws LocalEntryAdminException, RemoteException { + return localEntryAdminServiceStub.getEntryDataCount(); + } + + /** + * @return + * @throws LocalEntryAdminException + * @throws java.rmi.RemoteException + */ + public String[] getEntryNames() throws LocalEntryAdminException, RemoteException { + return localEntryAdminServiceStub.getEntryNames(); + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/localentry/LocalEntryAdminService.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/localentry/LocalEntryAdminService.java new file mode 100755 index 0000000000..90c536eb34 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/localentry/LocalEntryAdminService.java @@ -0,0 +1,73 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.localentry; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.localentry.stub.types.LocalEntryAdminException; +import org.wso2.carbon.localentry.stub.types.LocalEntryAdminServiceStub; + +import javax.activation.DataHandler; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.rmi.RemoteException; + +public class LocalEntryAdminService { + private static final Log log = LogFactory.getLog(LocalEntryAdminService.class); + + private final String serviceName = "LocalEntryAdmin"; + private LocalEntryAdminServiceStub localEntryAdminServiceStub; + private String endPoint; + + public LocalEntryAdminService(String backEndUrl) throws AxisFault { + this.endPoint = backEndUrl + serviceName; + localEntryAdminServiceStub = new LocalEntryAdminServiceStub(endPoint); + } + + public void addLocalEntry(String sessionCookie, DataHandler dh) + throws LocalEntryAdminException, IOException, XMLStreamException { + AuthenticateStub.authenticateStub(sessionCookie, localEntryAdminServiceStub); + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + //create the builder + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement localEntryElem = builder.getDocumentElement(); + localEntryAdminServiceStub.addEntry(localEntryElem.toString()); + + } + + public void deleteLocalEntry(String sessionCookie, String localEntryKey) + throws LocalEntryAdminException, RemoteException { + AuthenticateStub.authenticateStub(sessionCookie, localEntryAdminServiceStub); + localEntryAdminServiceStub.deleteEntry(localEntryKey); + + } + + public OMElement getLocalEntry(String sessionCookie, String localEntryKey) + throws LocalEntryAdminException, RemoteException { + AuthenticateStub.authenticateStub(sessionCookie, localEntryAdminServiceStub); + return (OMElement) localEntryAdminServiceStub.getEntry(localEntryKey); + + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/logging/LoggingAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/logging/LoggingAdminClient.java new file mode 100644 index 0000000000..ed9a22a4a7 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/logging/LoggingAdminClient.java @@ -0,0 +1,55 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.logging; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.logging.admin.stub.LoggingAdminStub; + +public class LoggingAdminClient { + private static final Log log = LogFactory.getLog(LoggingAdminClient.class); + private final String serviceName = "LoggingAdmin"; + private String endpoint = null; + private LoggingAdminStub loggingAdminStub; + + public static enum logLevel {OFF, TRACE, DEBUG, INFO, WARN, ERROR, FATAL} + + public LoggingAdminClient(String backEndUrl, String sessionCookie) throws AxisFault { + this.endpoint = backEndUrl + serviceName; + loggingAdminStub = new LoggingAdminStub(this.endpoint); + AuthenticateStub.authenticateStub(sessionCookie, loggingAdminStub); + } + + public LoggingAdminClient(String backEndURL, String userName, String password) + throws AxisFault { + this.endpoint = backEndURL + serviceName; + loggingAdminStub = new LoggingAdminStub(this.endpoint); + AuthenticateStub.authenticateStub(userName, password, loggingAdminStub); + } + + public boolean updateLoggerData(String loggerName, String logLevel, + boolean additivity, boolean persist) throws Exception { + + loggingAdminStub.updateLoggerData(loggerName, logLevel, additivity, persist); + return true; + } + +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/ConfigServiceAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/ConfigServiceAdminClient.java new file mode 100644 index 0000000000..4225e2f31e --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/ConfigServiceAdminClient.java @@ -0,0 +1,76 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.mediation; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.localentry.stub.types.LocalEntryAdminException; +import org.wso2.carbon.mediation.configadmin.stub.ConfigServiceAdminStub; + +import javax.activation.DataHandler; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.rmi.RemoteException; + +public class ConfigServiceAdminClient { + + private static final Log log = LogFactory.getLog(ConfigServiceAdminClient.class); + private final String serviceName = "MessageStoreAdminService"; + private ConfigServiceAdminStub configServiceAdminStub; + + public ConfigServiceAdminClient(String backEndUrl, String sessionCookie) throws AxisFault { + String endPoint = backEndUrl + serviceName; + configServiceAdminStub = new ConfigServiceAdminStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, configServiceAdminStub); + } + + public ConfigServiceAdminClient(String backEndUrl, String userName, String password) + throws AxisFault { + String endPoint = backEndUrl + serviceName; + configServiceAdminStub = new ConfigServiceAdminStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, configServiceAdminStub); + } + + public void addExistingConfiguration(DataHandler dh) + throws IOException, LocalEntryAdminException, XMLStreamException { + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement configSourceElem = builder.getDocumentElement(); + configServiceAdminStub.addExistingConfiguration(configSourceElem.toString()); + + } + + public void addExistingConfiguration(OMElement configSourceElem) throws RemoteException { + configServiceAdminStub.addExistingConfiguration(configSourceElem.toString()); + + } + + public void updateConfiguration(OMElement omElement) + throws IOException, LocalEntryAdminException, XMLStreamException { + configServiceAdminStub.updateConfiguration(omElement); + + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/EventBrokerAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/EventBrokerAdminClient.java new file mode 100644 index 0000000000..e3aceafceb --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/EventBrokerAdminClient.java @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2005-2010, 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.am.admin.clients.mediation; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axis2.AxisFault; +import org.apache.axis2.addressing.EndpointReference; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; +import org.apache.axis2.context.ConfigurationContext; +import org.apache.axis2.databinding.types.URI; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.event.client.stub.generated.*; +import org.wso2.carbon.event.client.stub.generated.addressing.AttributedURI; +import org.wso2.carbon.event.client.stub.generated.addressing.EndpointReferenceType; +import org.wso2.carbon.event.client.stub.generated.addressing.ReferenceParametersType; + +import javax.xml.namespace.QName; +import java.rmi.RemoteException; + +public class EventBrokerAdminClient { + + private static final Log log = LogFactory.getLog(EventBrokerAdminClient.class); + + String backendUrl = null; + String SessionCookie = null; + ConfigurationContext configurationContext = null; + private static final String TOPIC_HEADER_NAME = "topic"; + + private static final String TOPIC_HEADER_NS = "http://wso2.org/ns/2009/09/eventing/notify"; + + public static final String WSE_EVENTING_NS = "http://schemas.xmlsoap.org/ws/2004/08/eventing"; + public static final String WSE_EN_IDENTIFIER = "Identifier"; + + private static OMFactory omFactory = OMAbstractFactory.getOMFactory(); + + public EventBrokerAdminClient(String backendUrl, String sessionCookie, + ConfigurationContext configurationContext) { + + this.backendUrl = backendUrl + "EventBrokerService"; + this.SessionCookie = sessionCookie; + this.configurationContext = configurationContext; + + } + + public String subscribe(String topic, String eventSinkUrl) throws RemoteException { + log.debug("Subscribed to " + topic + " in " + eventSinkUrl); + + try { + // append the topic name at the end of the broker URL + // so that it seems there is a seperate uri each event source + if (!topic.startsWith("/")) { + topic = "/" + topic; + } + EventBrokerServiceStub stub = new EventBrokerServiceStub(configurationContext, + backendUrl + topic); + + ServiceClient client = stub._getServiceClient(); + configureCookie(client); + + EndpointReferenceType epr = new EndpointReferenceType(); + epr.setAddress(createURI(eventSinkUrl)); + + DeliveryType deliveryType = new DeliveryType(); + EndpointReferenceType eventSink = new EndpointReferenceType(); + eventSink.setAddress(createURI(eventSinkUrl)); + deliveryType.setNotifyTo(eventSink); + + ExpirationType expirationType = null; + + FilterType filterType = new FilterType(); + filterType.setDialect(new URI("urn:someurl")); + filterType.setString(topic); + + SubscribeResponse subscribeResponse = stub.subscribe(epr, deliveryType, expirationType, + filterType, null); + ReferenceParametersType referenceParameters = + subscribeResponse.getSubscriptionManager().getReferenceParameters(); + OMElement[] properties = referenceParameters.getExtraElement(); + + String id = null; + for (OMElement property : properties) { + if (property.getLocalName().equals("Identifier")) { + id = property.getText(); + } + } + return id; + } catch (AxisFault e) { + e.printStackTrace(); + } catch (URI.MalformedURIException e) { + e.printStackTrace(); + } catch (RemoteException e) { + e.printStackTrace(); + } + + return null; + } + + public void publish(String topic, OMElement element) throws AxisFault { + log.debug("published element to " + topic); + EventBrokerServiceStub service = new EventBrokerServiceStub(configurationContext, backendUrl + + + "/publish/" + + topic); + configureCookie(service._getServiceClient()); + ServiceClient serviceClient = service._getServiceClient(); + + OMElement header = omFactory.createOMElement(new QName(TOPIC_HEADER_NS, TOPIC_HEADER_NAME)); + header.setText(topic); + serviceClient.addHeader(header); + serviceClient.getOptions().setTo(new EndpointReference(backendUrl + "/publish")); + //serviceClient.getOptions().setTo(new EndpointReference(brokerUrl)); + serviceClient.getOptions().setAction("urn:publish"); + serviceClient.sendRobust(element); + } + + public void unsubscribe(String subscriptionID) throws RemoteException { + log.debug("Unsubscribed to " + subscriptionID); + EventBrokerServiceStub service = + new EventBrokerServiceStub(configurationContext, backendUrl); + configureCookie(service._getServiceClient()); + ServiceClient serviceClient = service._getServiceClient(); + OMElement header = omFactory.createOMElement(new QName(WSE_EVENTING_NS, WSE_EN_IDENTIFIER)); + header.setText(subscriptionID); + serviceClient.addHeader(header); + service.unsubscribe(new OMElement[] { }); + } + + public GetSubscriptionsResponse getAllSubscriptions(int maxRequestCount, String resultFilter, + int firstIndex) throws RemoteException { + EventBrokerServiceStub service = + new EventBrokerServiceStub(configurationContext, backendUrl); + configureCookie(service._getServiceClient()); + return service.getSubscriptions(maxRequestCount, resultFilter, firstIndex); + } + + private void configureCookie(ServiceClient client) throws AxisFault { + if (SessionCookie != null) { + Options option = client.getOptions(); + option.setManageSession(true); + option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, + SessionCookie); + } + } + + private static AttributedURI createURI(String uriAddress) throws URI.MalformedURIException { + AttributedURI address = new AttributedURI(); + address.setAnyURI(new URI(uriAddress)); + return address; + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/EventingAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/EventingAdminClient.java new file mode 100644 index 0000000000..dcf834f194 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/EventingAdminClient.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2005-2010, 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.am.admin.clients.mediation; + +import org.apache.axis2.AxisFault; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; +import org.apache.axis2.context.ConfigurationContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.event.stub.service.EventingAdminServiceStub; +import org.wso2.carbon.event.stub.service.dto.SubscriptionDTO; + +public class EventingAdminClient { + + private static final Log log = LogFactory.getLog(EventingAdminClient.class); + + private org.wso2.carbon.event.stub.service.EventingAdminServiceStub stub; + + /** + * @param cookie + * @param backendServerURL + * @param configCtx + * @throws AxisFault + */ + public EventingAdminClient(String cookie, String backendServerURL, + ConfigurationContext configCtx) throws AxisFault { + String serviceURL = backendServerURL + "EventingAdminService"; + stub = new EventingAdminServiceStub(configCtx, serviceURL); + ServiceClient client = stub._getServiceClient(); + Options option = client.getOptions(); + option.setManageSession(true); + option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); + } + + /** + * @param serviceName + * @return + * @throws AxisFault + */ + public String[] getValidSubscriptions(String serviceName) throws AxisFault { + try { + if (serviceName == null) { + return null; + } + return stub.getValidSubscriptions(serviceName); + } catch (Exception e) { + String msg = "Cannot get valid subscriptions for " + serviceName; + handleException(msg, e); + } + + return null; + } + + /** + * @param serviceName + * @return + * @throws AxisFault + */ + public String[] getExpiredSubscriptions(String serviceName) throws AxisFault { + try { + if (serviceName == null) { + return null; + } + return stub.getExpiredSubscriptions(serviceName); + } catch (Exception e) { + String msg = "Cannot get expired subscriptions for " + serviceName; + handleException(msg, e); + } + + return null; + } + + /** + * @param serviceName + * @param subscriptionId + * @return + * @throws AxisFault + */ + public SubscriptionDTO getSubscriptionDetails(String serviceName, String subscriptionId) + throws AxisFault { + try { + if (serviceName == null || subscriptionId == null) { + return null; + } + return stub.getSubscriptionDetails(serviceName, subscriptionId); + } catch (Exception e) { + String msg = "Cannot get subscriptions for details for " + serviceName; + handleException(msg, e); + } + + return null; + } + + private void handleException(String msg, Exception e) throws AxisFault { + log.error(msg, e); + throw new AxisFault(msg, e); + } +} \ No newline at end of file diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/MassageStoreAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/MassageStoreAdminClient.java new file mode 100644 index 0000000000..5edec25a43 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/MassageStoreAdminClient.java @@ -0,0 +1,83 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.mediation; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.localentry.stub.types.LocalEntryAdminException; +import org.wso2.carbon.message.store.stub.MessageInfo; +import org.wso2.carbon.message.store.stub.MessageStoreAdminServiceStub; + +import javax.activation.DataHandler; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.rmi.RemoteException; + +public class MassageStoreAdminClient { + + String backendUrl = null; + String SessionCookie = null; + MessageStoreAdminServiceStub messageStoreAdminServiceStub; + private static final Log log = LogFactory.getLog(MassageStoreAdminClient.class); + + public MassageStoreAdminClient(String backendUrl, String sessionCookie) { + this.backendUrl = backendUrl; + this.SessionCookie = sessionCookie; + } + + private MessageStoreAdminServiceStub setMessageStoreStubStub() throws AxisFault { + final String messageStoreServiceUrl = backendUrl + "MessageStoreAdminService"; + MessageStoreAdminServiceStub messageStoreAdminService = null; + messageStoreAdminService = new MessageStoreAdminServiceStub(messageStoreServiceUrl); + AuthenticateStub.authenticateStub(SessionCookie, messageStoreAdminService); + return messageStoreAdminService; + } + + public void addMessageStore(DataHandler dh) + throws IOException, LocalEntryAdminException, XMLStreamException, + Exception { + messageStoreAdminServiceStub = this.setMessageStoreStubStub(); + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement localEntryElem = builder.getDocumentElement(); + messageStoreAdminServiceStub.addMessageStore(localEntryElem.toString()); + } + + public String[] getMessageStores() throws RemoteException { + messageStoreAdminServiceStub = this.setMessageStoreStubStub(); + return messageStoreAdminServiceStub.getMessageStoreNames(); + } + + public int getMessageCount(String storeName) throws RemoteException { + messageStoreAdminServiceStub = this.setMessageStoreStubStub(); + return messageStoreAdminServiceStub.getSize(storeName); + } + + public MessageInfo[] getAllMessages(String storeName) throws RemoteException { + messageStoreAdminServiceStub = this.setMessageStoreStubStub(); + return messageStoreAdminServiceStub.getAllMessages(storeName); + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/MessageProcessorClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/MessageProcessorClient.java new file mode 100644 index 0000000000..e59d4ae8f2 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/MessageProcessorClient.java @@ -0,0 +1,75 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.mediation; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.message.processor.stub.MessageProcessorAdminServiceStub; + +import javax.activation.DataHandler; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.rmi.RemoteException; + +public class MessageProcessorClient { + + private static final Log log = LogFactory.getLog(MessageProcessorClient.class); + + private MessageProcessorAdminServiceStub messageProcessorAdminServiceStub; + private final String serviceName = "MessageProcessorAdminService"; + + public MessageProcessorClient(String backEndUrl, String sessionCookie) throws AxisFault { + String endPoint = backEndUrl + serviceName; + messageProcessorAdminServiceStub = new MessageProcessorAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, messageProcessorAdminServiceStub); + } + + public MessageProcessorClient(String backEndUrl, String userName, String password) + throws AxisFault { + String endPoint = backEndUrl + serviceName; + messageProcessorAdminServiceStub = new MessageProcessorAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, messageProcessorAdminServiceStub); + } + + public void addMessageProcessor(DataHandler dh) throws IOException, XMLStreamException { + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement messageProcessorElem = builder.getDocumentElement(); + messageProcessorAdminServiceStub.addMessageProcessor(messageProcessorElem.toString()); + } + + public void addMessageProcessor(OMElement messageProcessor) throws RemoteException { + messageProcessorAdminServiceStub.addMessageProcessor(messageProcessor.toString()); + } + + public void deleteMessageProcessor(String messageProcessorName) throws RemoteException { + messageProcessorAdminServiceStub.deleteMessageProcessor(messageProcessorName); + } + + public String[] getMessageProcessorNames() throws RemoteException { + return messageProcessorAdminServiceStub.getMessageProcessorNames(); + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/MessageStoreAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/MessageStoreAdminClient.java new file mode 100644 index 0000000000..11132913bb --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/MessageStoreAdminClient.java @@ -0,0 +1,101 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.mediation; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.message.store.stub.Exception; +import org.wso2.carbon.message.store.stub.MessageInfo; +import org.wso2.carbon.message.store.stub.MessageStoreAdminServiceStub; + +import javax.activation.DataHandler; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.rmi.RemoteException; + +public class MessageStoreAdminClient { + + private static final Log log = LogFactory.getLog(MessageStoreAdminClient.class); + private MessageStoreAdminServiceStub messageStoreAdminServiceStub; + private final String serviceName = "MessageStoreAdminService"; + + public MessageStoreAdminClient(String backEndUrl, String sessionCookie) throws AxisFault { + String endPoint = backEndUrl + serviceName; + messageStoreAdminServiceStub = new MessageStoreAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, messageStoreAdminServiceStub); + } + + public MessageStoreAdminClient(String backEndUrl, String userName, String password) + throws AxisFault { + String endPoint = backEndUrl + serviceName; + messageStoreAdminServiceStub = new MessageStoreAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, messageStoreAdminServiceStub); + } + + public void addMessageStore(DataHandler dh) + throws IOException, XMLStreamException, org.wso2.carbon.message.store.stub.Exception { + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement messageStore = builder.getDocumentElement(); + messageStoreAdminServiceStub.addMessageStore(messageStore.toString()); + } + + public void addMessageStore(OMElement messageStore) throws RemoteException, Exception { + messageStoreAdminServiceStub.addMessageStore(messageStore.toString()); + } + + public void updateMessageStore(OMElement messageStore) throws RemoteException { + messageStoreAdminServiceStub.modifyMessageStore(messageStore.toString()); + } + + public void deleteMessageStore(String messageStoreName) throws RemoteException { + messageStoreAdminServiceStub.deleteMessageStore(messageStoreName); + } + + public void deleteMessage(String storeName, String messageId) throws RemoteException { + messageStoreAdminServiceStub.deleteMessage(storeName, messageId); + } + + public String[] getMessageStores() throws RemoteException { + return messageStoreAdminServiceStub.getMessageStoreNames(); + } + + public int getMessageCount(String storeName) throws RemoteException { + return messageStoreAdminServiceStub.getSize(storeName); + } + + public MessageInfo[] getAllMessages(String storeName) throws RemoteException { + return messageStoreAdminServiceStub.getAllMessages(storeName); + } + + public MessageInfo[] getPaginatedMessages(String storeName, int pageNo) throws RemoteException { + return messageStoreAdminServiceStub.getPaginatedMessages(storeName, pageNo); + } + + public String getEnvelope(String storeName, String messageId) throws RemoteException { + return messageStoreAdminServiceStub.getEnvelope(storeName, messageId); + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/NDataSourceAdminServiceClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/NDataSourceAdminServiceClient.java new file mode 100644 index 0000000000..c6e91b2f93 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/NDataSourceAdminServiceClient.java @@ -0,0 +1,211 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.mediation; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.integration.common.admin.client.utils.AuthenticateStubUtil; +import org.wso2.carbon.ndatasource.ui.stub.NDataSourceAdminDataSourceException; +import org.wso2.carbon.ndatasource.ui.stub.NDataSourceAdminStub; +import org.wso2.carbon.ndatasource.ui.stub.core.services.xsd.WSDataSourceInfo; +import org.wso2.carbon.ndatasource.ui.stub.core.services.xsd.WSDataSourceMetaInfo; + +public class NDataSourceAdminServiceClient { + private static final Log log = LogFactory + .getLog(org.wso2.carbon.integration.common.admin.client.NDataSourceAdminServiceClient.class); + private final String serviceName = "NDataSourceAdmin"; + private NDataSourceAdminStub nDataSourceAdminStub; + private String endPoint; + + public NDataSourceAdminServiceClient(String backEndUrl, String sessionCookie) throws AxisFault { + this.endPoint = backEndUrl + serviceName; + try { + nDataSourceAdminStub = new NDataSourceAdminStub(endPoint); + } catch (AxisFault axisFault) { + log.error("nDataSourceAdminStub Initialization fail " + axisFault.getMessage()); + throw new AxisFault("nDataSourceAdminStub Initialization fail ", axisFault); + } + AuthenticateStubUtil.authenticateStub(sessionCookie, nDataSourceAdminStub); + } + + public NDataSourceAdminServiceClient(String backEndUrl, String userName, String password) + throws AxisFault { + this.endPoint = backEndUrl + serviceName; + try { + nDataSourceAdminStub = new NDataSourceAdminStub(endPoint); + } catch (AxisFault axisFault) { + log.error("nDataSourceAdminStub Initialization fail " + axisFault.getMessage()); + throw new AxisFault("nDataSourceAdminStub Initialization fail ", axisFault); + } + AuthenticateStubUtil.authenticateStub(userName, password, nDataSourceAdminStub); + } + + public void addDataSource(WSDataSourceMetaInfo dataSourceMetaInfo) throws Exception { + validateDataSourceMetaInformation(dataSourceMetaInfo); + if (log.isDebugEnabled()) { + log.debug("Going to add Datasource :" + dataSourceMetaInfo.getName()); + } + try { + nDataSourceAdminStub.addDataSource(dataSourceMetaInfo); + } catch (NDataSourceAdminDataSourceException e) { + if (e.getFaultMessage().getDataSourceException().isErrorMessageSpecified()) { + handleException(e.getFaultMessage().getDataSourceException().getErrorMessage(), e); + } + handleException(e.getMessage(), e); + } + } + + public boolean testDataSourceConnection(WSDataSourceMetaInfo dataSourceMetaInfo) + throws Exception { + validateDataSourceMetaInformation(dataSourceMetaInfo); + if (log.isDebugEnabled()) { + log.debug("Going test connection of Datasource :" + dataSourceMetaInfo.getName()); + } + try { + return nDataSourceAdminStub.testDataSourceConnection(dataSourceMetaInfo); + } catch (NDataSourceAdminDataSourceException e) { + if (e.getFaultMessage().getDataSourceException().isErrorMessageSpecified()) { + handleException(e.getFaultMessage().getDataSourceException().getErrorMessage(), e); + } + handleException(e.getMessage(), e); + } + return false; + } + + public void deleteDataSource(String dsName) throws Exception { + validateName(dsName); + if (log.isDebugEnabled()) { + log.debug("Going to delete a Data-source with name : " + dsName); + } + try { + nDataSourceAdminStub.deleteDataSource(dsName); + } catch (NDataSourceAdminDataSourceException e) { + if (e.getFaultMessage().getDataSourceException().isErrorMessageSpecified()) { + handleException(e.getFaultMessage().getDataSourceException().getErrorMessage(), e); + } + handleException(e.getMessage(), e); + } + } + + public WSDataSourceInfo[] getAllDataSources() throws Exception { + WSDataSourceInfo[] allDataSources = null; + try { + allDataSources = nDataSourceAdminStub.getAllDataSources(); + } catch (NDataSourceAdminDataSourceException e) { + if (e.getFaultMessage().getDataSourceException().isErrorMessageSpecified()) { + handleException(e.getFaultMessage().getDataSourceException().getErrorMessage(), e); + } + handleException(e.getMessage(), e); + } + return allDataSources; + } + + public WSDataSourceInfo getDataSource(String dsName) throws Exception { + validateName(dsName); + WSDataSourceInfo wsDataSourceInfo = null; + try { + wsDataSourceInfo = nDataSourceAdminStub.getDataSource(dsName); + } catch (NDataSourceAdminDataSourceException e) { + if (e.getFaultMessage().getDataSourceException().isErrorMessageSpecified()) { + handleException(e.getFaultMessage().getDataSourceException().getErrorMessage(), e); + } + handleException(e.getMessage(), e); + } + return wsDataSourceInfo; + } + + public WSDataSourceInfo[] getAllDataSourcesForType(String dsType) throws Exception { + validateType(dsType); + WSDataSourceInfo[] allDataSources = null; + try { + allDataSources = nDataSourceAdminStub.getAllDataSourcesForType(dsType); + } catch (NDataSourceAdminDataSourceException e) { + if (e.getFaultMessage().getDataSourceException().isErrorMessageSpecified()) { + handleException(e.getFaultMessage().getDataSourceException().getErrorMessage(), e); + } + handleException(e.getMessage(), e); + } + return allDataSources; + } + + public String[] getDataSourceTypes() throws Exception { + String[] dataSourceTypes = null; + try { + dataSourceTypes = nDataSourceAdminStub.getDataSourceTypes(); + } catch (NDataSourceAdminDataSourceException e) { + if (e.getFaultMessage().getDataSourceException().isErrorMessageSpecified()) { + handleException(e.getFaultMessage().getDataSourceException().getErrorMessage(), e); + } + handleException(e.getMessage(), e); + } + return dataSourceTypes; + } + + public boolean reloadAllDataSources() throws Exception { + try { + return nDataSourceAdminStub.reloadAllDataSources(); + } catch (NDataSourceAdminDataSourceException e) { + if (e.getFaultMessage().getDataSourceException().isErrorMessageSpecified()) { + handleException(e.getFaultMessage().getDataSourceException().getErrorMessage(), e); + } + handleException(e.getMessage(), e); + } + return false; + } + + public boolean reloadDataSource(String dsName) throws Exception { + validateName(dsName); + try { + return nDataSourceAdminStub.reloadDataSource(dsName); + } catch (NDataSourceAdminDataSourceException e) { + if (e.getFaultMessage().getDataSourceException().isErrorMessageSpecified()) { + handleException(e.getFaultMessage().getDataSourceException().getErrorMessage(), e); + } + handleException(e.getMessage(), e); + } + return false; + } + + private static void validateDataSourceMetaInformation(WSDataSourceMetaInfo dataSourceMetaInfo) { + if (dataSourceMetaInfo == null) { + handleException("WSDataSourceMetaInfo can not be found."); + } + } + + private static void validateName(String name) { + if (name == null || "".equals(name)) { + handleException("Name is null or empty"); + } + } + + private static void validateType(String type) { + if (type == null || "".equals(type)) { + handleException("Type is null or empty"); + } + } + + private static void handleException(String msg) { + log.error(msg); + throw new IllegalArgumentException(msg); + } + + private static void handleException(String msg, Exception e) throws Exception { + throw new Exception(msg, e); + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/PriorityMediationAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/PriorityMediationAdminClient.java new file mode 100644 index 0000000000..93884d5c22 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/PriorityMediationAdminClient.java @@ -0,0 +1,75 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.mediation; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.priority.executors.stub.PriorityMediationAdminStub; + +import javax.activation.DataHandler; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.rmi.RemoteException; + +public class PriorityMediationAdminClient { + + private static final Log log = LogFactory.getLog(PriorityMediationAdminClient.class); + private PriorityMediationAdminStub priorityMediationAdmin; + private final String serviceName = "PriorityMediationAdmin"; + + public PriorityMediationAdminClient(String backEndUrl, String sessionCookie) throws AxisFault { + String endPoint = backEndUrl + serviceName; + priorityMediationAdmin = new PriorityMediationAdminStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, priorityMediationAdmin); + } + + public PriorityMediationAdminClient(String backEndUrl, String userName, String password) + throws AxisFault { + String endPoint = backEndUrl + serviceName; + priorityMediationAdmin = new PriorityMediationAdminStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, priorityMediationAdmin); + } + + public void addPriorityMediator(String name, DataHandler dh) + throws IOException, XMLStreamException { + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement messageProcessorElem = builder.getDocumentElement(); + priorityMediationAdmin.add(name, messageProcessorElem); + } + + public void addPriorityMediator(String name, OMElement priorityElement) throws RemoteException { + priorityMediationAdmin.add(name, priorityElement); + } + + public void remove(String name) throws RemoteException { + priorityMediationAdmin.remove(name); + } + + public String[] getExecutorList() throws RemoteException { + return priorityMediationAdmin.getExecutorList(); + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/SynapseArtifactUploaderClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/SynapseArtifactUploaderClient.java new file mode 100644 index 0000000000..85b6e169a0 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/SynapseArtifactUploaderClient.java @@ -0,0 +1,62 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.mediation; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.mediation.artifactuploader.stub.SynapseArtifactUploaderAdminStub; + +import javax.activation.DataHandler; +import java.rmi.RemoteException; + +public class SynapseArtifactUploaderClient { + private static final Log log = LogFactory.getLog(SynapseArtifactUploaderClient.class); + + private final String serviceName = "SynapseArtifactUploaderAdmin"; + private SynapseArtifactUploaderAdminStub synapseArtifactUploaderAdminStub; + + public SynapseArtifactUploaderClient(String backEndUrl, String sessionCookie) throws AxisFault { + String endPoint = backEndUrl + serviceName; + synapseArtifactUploaderAdminStub = new SynapseArtifactUploaderAdminStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, synapseArtifactUploaderAdminStub); + } + + public SynapseArtifactUploaderClient(String backEndUrl, String userName, String password) + throws AxisFault { + String endPoint = backEndUrl + serviceName; + synapseArtifactUploaderAdminStub = new SynapseArtifactUploaderAdminStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, synapseArtifactUploaderAdminStub); + } + + public void uploadFile(String fileName, DataHandler dh) throws RemoteException { + + synapseArtifactUploaderAdminStub.uploadArtifact(fileName, dh); + log.info("Artifact uploaded"); + + } + + public void deleteFile(String fileName) throws RemoteException { + + synapseArtifactUploaderAdminStub.removeArtifact(fileName); + log.info("Artifact Deleted"); + + } + +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/SynapseConfigAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/SynapseConfigAdminClient.java new file mode 100644 index 0000000000..7c2fb1b7fb --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/SynapseConfigAdminClient.java @@ -0,0 +1,222 @@ +/** + * Copyright (c) 2009, 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. + */ + +/* +*ConfigServiceAdmin methods will be called using its returned stub +*/ + +package org.wso2.am.admin.clients.mediation; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.mediation.configadmin.stub.ConfigServiceAdminStub; +import org.wso2.carbon.mediation.configadmin.stub.types.carbon.ConfigurationInformation; +import org.wso2.carbon.mediation.configadmin.stub.types.carbon.ValidationError; +import org.xml.sax.SAXException; + +import javax.servlet.ServletException; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.File; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.rmi.RemoteException; + +/** + * This class exposing ConfigServiceAdmin operations to the test cases. + */ +public class SynapseConfigAdminClient { + + private static final Log log = LogFactory.getLog(SynapseConfigAdminClient.class); + + private ConfigServiceAdminStub configServiceAdminStub; + private final String serviceName = "ConfigServiceAdmin"; + + public SynapseConfigAdminClient(String backEndUrl, String sessionCookie) throws AxisFault { + + String endPoint = backEndUrl + serviceName; + configServiceAdminStub = new ConfigServiceAdminStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, configServiceAdminStub); + } + + public SynapseConfigAdminClient(String backEndUrl, String userName, String password) + throws AxisFault { + + String endPoint = backEndUrl + serviceName; + configServiceAdminStub = new ConfigServiceAdminStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, configServiceAdminStub); + } + + /** + * Activating service + * + * @param serviceName service name need to be activated + * @throws java.rmi.RemoteException throwable exception + */ + public void activateService(String serviceName) throws RemoteException { + configServiceAdminStub.activate(serviceName); + } + + /** + * Adding more configuration to the existing service + * + * @param serviceName service name + * @throws java.rmi.RemoteException throwable exception + */ + public void addExistingConfiguration(String serviceName) throws RemoteException { + configServiceAdminStub.addExistingConfiguration(serviceName); + } + + /** + * @param serviceName service name + * @param description service description + * @throws java.rmi.RemoteException throwable exception + */ + public void create(String serviceName, String description) throws RemoteException { + configServiceAdminStub.create(serviceName, description); + } + + /** + * Deleting synapse configuration + * + * @param serviceName service name + * @throws java.rmi.RemoteException throwable exception + */ + public void deleteConfiguration(String serviceName) throws RemoteException { + configServiceAdminStub.deleteConfiguration(serviceName); + } + + /** + * Get current synapse configuration + * + * @return synapse configuration + * @throws java.rmi.RemoteException throwable exception + */ + public String getConfiguration() throws RemoteException { + return configServiceAdminStub.getConfiguration(); + } + + /** + * @return configuration list + * @throws java.rmi.RemoteException throwable exception + */ + public ConfigurationInformation[] getConfigurationList() throws RemoteException { + return configServiceAdminStub.getConfigurationList(); + } + + /** + * save synapse configuration + * + * @throws java.rmi.RemoteException throwable exception + */ + public void saveConfigurationToDisk() throws RemoteException { + configServiceAdminStub.saveConfigurationToDisk(); + } + + /** + * update synapse configuration + * + * @param configuration synapse configuration + * @return configuration update status + * @throws java.rmi.RemoteException throwable exception + * @throws javax.servlet.ServletException throwable exception + * @throws javax.xml.stream.XMLStreamException throwable exception + */ + public boolean updateConfiguration(String configuration) + throws XMLStreamException, ServletException, RemoteException { + return configServiceAdminStub.updateConfiguration(createOMElement(configuration)); + } + + /** + * Uploads synapse config bu using a file + * + * @param file + * @return + */ + public boolean updateConfiguration(File file) + throws IOException, SAXException, ParserConfigurationException, TransformerException, + XMLStreamException, ServletException { + boolean success = false; + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + if (file.exists()) { + Document doc = docBuilder.parse(file); + String fileContent = getStringFromDocument(doc); + success = configServiceAdminStub.updateConfiguration(createOMElement(fileContent)); + } + return success; + } + + /** + * update synapse configuration + * + * @param configuration synapse configuration + * @return configuration update status + * @throws java.rmi.RemoteException throwable exception + * @throws javax.servlet.ServletException throwable exception + * @throws javax.xml.stream.XMLStreamException throwable exception + */ + public boolean updateConfiguration(OMElement configuration) + throws XMLStreamException, ServletException, RemoteException { + return configServiceAdminStub.updateConfiguration(configuration); + } + + /** + * Validate configuration + * + * @param configuration ynapse configuration + * @return validation error array + * @throws java.rmi.RemoteException throwable exception + */ + public ValidationError[] validateConfiguration(OMElement configuration) throws RemoteException { + return configServiceAdminStub.validateConfiguration(configuration); + } + + private static OMElement createOMElement(String xml) + throws ServletException, XMLStreamException { + XMLStreamReader reader = + XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(xml)); + StAXOMBuilder builder = new StAXOMBuilder(reader); + return builder.getDocumentElement(); + + } + + private String getStringFromDocument(Document doc) throws TransformerException { + DOMSource domSource = new DOMSource(doc); + StringWriter writer = new StringWriter(); + StreamResult result = new StreamResult(writer); + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer transformer = tf.newTransformer(); + transformer.transform(domSource, result); + return writer.toString(); + } + +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/TopicAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/TopicAdminClient.java new file mode 100644 index 0000000000..7bcd2399c4 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/mediation/TopicAdminClient.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2005-2010, 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.esb.integration.common.clients.mediation; + +import org.apache.axis2.AxisFault; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; +import org.apache.axis2.context.ConfigurationContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.event.stub.internal.TopicManagerAdminServiceStub; +import org.wso2.carbon.event.stub.internal.xsd.TopicNode; + +public class TopicAdminClient { + + private static final Log log = LogFactory.getLog(TopicAdminClient.class); + + String backendUrl = null; + String SessionCookie = null; + ConfigurationContext configurationContext = null; + + public TopicAdminClient(String backendUrl, String sessionCookie, + ConfigurationContext configurationContext) { + + this.backendUrl = backendUrl + + "TopicManagerAdminService.TopicManagerAdminServiceHttpsSoap12Endpoint"; + this.SessionCookie = sessionCookie; + this.configurationContext = configurationContext; + + } + + public void addTopic(String topic) throws Exception { + + TopicManagerAdminServiceStub stub = new TopicManagerAdminServiceStub(configurationContext, + backendUrl); + configureCookie(stub._getServiceClient()); + stub.addTopic(topic); + } + + public TopicNode getAllTopics() throws Exception { + TopicManagerAdminServiceStub stub = new TopicManagerAdminServiceStub(configurationContext, + backendUrl); + configureCookie(stub._getServiceClient()); + return stub.getAllTopics(); + } + + public void removeTopic(String topic) throws Exception { + + TopicManagerAdminServiceStub stub = new TopicManagerAdminServiceStub(configurationContext, + backendUrl); + configureCookie(stub._getServiceClient()); + stub.removeTopic(topic); + } + + private void configureCookie(ServiceClient client) throws AxisFault { + if (SessionCookie != null) { + Options option = client.getOptions(); + option.setManageSession(true); + option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, + SessionCookie); + } + } + +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/prioroty/executor/PriorityMediationAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/prioroty/executor/PriorityMediationAdminClient.java new file mode 100644 index 0000000000..73b3598de9 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/prioroty/executor/PriorityMediationAdminClient.java @@ -0,0 +1,77 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.prioroty.executor; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.priority.executors.stub.PriorityMediationAdminStub; + +import javax.activation.DataHandler; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.rmi.RemoteException; + +public class PriorityMediationAdminClient { + String backendUrl = null; + String SessionCookie = null; + PriorityMediationAdminStub priorityMediationAdmin; + private static final Log log = LogFactory.getLog(PriorityMediationAdminClient.class); + + public PriorityMediationAdminClient(String backendUrl, String sessionCookie) { + this.backendUrl = backendUrl; + this.SessionCookie = sessionCookie; + } + + private PriorityMediationAdminStub setPriorityExecutorStub() throws AxisFault { + final String priorityAdminServiceUrl = backendUrl + "PriorityMediationAdmin"; + PriorityMediationAdminStub priorityMediator = null; + priorityMediator = new PriorityMediationAdminStub(priorityAdminServiceUrl); + AuthenticateStub.authenticateStub(SessionCookie, priorityMediator); + return priorityMediator; + } + + public void addPriorityMediator(String name, DataHandler dh) + throws IOException, XMLStreamException { + priorityMediationAdmin = this.setPriorityExecutorStub(); + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement messageProcessorElem = builder.getDocumentElement(); + priorityMediationAdmin.add(name, messageProcessorElem); + } + + public void addPriorityMediator(String name, OMElement messageProcessorElement) + throws RemoteException { + priorityMediationAdmin.add(name, messageProcessorElement); + } + + public String[] getExecutorList() throws RemoteException { + return priorityMediationAdmin.getExecutorList(); + } + + public void remove(String name) throws RemoteException { + priorityMediationAdmin.remove(name); + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/proxy/admin/ProxyServiceAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/proxy/admin/ProxyServiceAdminClient.java new file mode 100644 index 0000000000..2869e68bd9 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/proxy/admin/ProxyServiceAdminClient.java @@ -0,0 +1,501 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.proxy.admin; + +import junit.framework.Assert; +import org.apache.axiom.om.OMAttribute; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMNamespace; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.axis2.description.WSDL2Constants; +import org.apache.axis2.wsdl.WSDLConstants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.synapse.config.xml.XMLConfigConstants; +import org.apache.synapse.core.axis2.ProxyService; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.proxyadmin.stub.ProxyServiceAdminProxyAdminException; +import org.wso2.carbon.proxyadmin.stub.ProxyServiceAdminStub; +import org.wso2.carbon.proxyadmin.stub.types.carbon.Entry; +import org.wso2.carbon.proxyadmin.stub.types.carbon.ProxyData; +import org.wso2.carbon.proxyadmin.stub.types.carbon.ProxyServicePolicyInfo; + +import javax.activation.DataHandler; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Locale; +import java.util.ResourceBundle; + +/** + * This class exposing internal command methods to invoke ProxyAdmin admin service + */ + +public class ProxyServiceAdminClient { + private static final Log log = LogFactory.getLog(ProxyServiceAdminClient.class); + + private ProxyServiceAdminStub proxyServiceAdminStub; + private final String serviceName = "ProxyServiceAdmin"; + + /** + * Authenticate stub + * + * @param backEndUrl server backend URL + * @throws org.apache.axis2.AxisFault + */ + public ProxyServiceAdminClient(String backEndUrl, String sessionCookie) throws AxisFault { + + String endPoint = backEndUrl + serviceName; + proxyServiceAdminStub = new ProxyServiceAdminStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, proxyServiceAdminStub); + } + + public ProxyServiceAdminClient(String backEndUrl, String userName, String password) + throws AxisFault { + + String endPoint = backEndUrl + serviceName; + proxyServiceAdminStub = new ProxyServiceAdminStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, proxyServiceAdminStub); + } + + /** + * Adding proxy service + * + * @param proxyName Name of the proxy service + * @param wsdlURI WSDL URI + * @param serviceEndPoint Service endpoint location + * @throws ProxyServiceAdminProxyAdminException proxyAdmin Service exception + * @throws java.rmi.RemoteException Remote Exception + */ + public void addProxyService(String proxyName, String wsdlURI, + String serviceEndPoint) + throws Exception { + + String[] transport = { "http", "https" }; + ProxyData data = new ProxyData(); + data.setName(proxyName); + data.setWsdlURI(wsdlURI); + data.setTransports(transport); + data.setStartOnLoad(true); + //data.setEndpointKey("http://localhost:9000/services/SimpleStockQuoteService"); + data.setEndpointXML("
    "); + data.setEnableSecurity(true); + try { + proxyServiceAdminStub.addProxy(data); + } catch (Exception e) { + throw new Exception("Error while adding proxy ", e); + } + log.info("Proxy Added"); + } + + /** + * Adding proxy service + * + * @param dh Data Handler + * @throws ProxyServiceAdminProxyAdminException Proxy service admin exception + * @throws java.rmi.RemoteException Remote exception + * @throws javax.xml.stream.XMLStreamException Exception + */ + public void addProxyService(DataHandler dh) + throws ProxyServiceAdminProxyAdminException, IOException, XMLStreamException { + + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + //create the builder + StAXOMBuilder builder = new StAXOMBuilder(parser); + //get the root element (in this case the envelope) + OMElement documentElement = builder.getDocumentElement(); + + ProxyData proxyData = getProxyData(documentElement.toString()); + + log.info("Proxy Added"); + } + + /** + * @param data + * @throws ProxyServiceAdminProxyAdminException + * @throws java.io.IOException + * @throws javax.xml.stream.XMLStreamException + */ + public void addProxyService(OMElement data) + throws Exception { + + ProxyData proxyData = getProxyData(data.toString()); + try { + proxyServiceAdminStub.addProxy(proxyData); + } catch (Exception e) { + throw new Exception("Error while adding proxy ", e); + } + log.info("Proxy Added"); + } + + /** + * Delete proxy service + * + * @param proxyName Name of the proxy service to be deleted + * @throws ProxyServiceAdminProxyAdminException proxy admin exception + * @throws java.rmi.RemoteException remote exception + */ + public void deleteProxy(String proxyName) + throws ProxyServiceAdminProxyAdminException, RemoteException { + AuthenticateStub auth = new AuthenticateStub(); + + proxyServiceAdminStub.deleteProxyService(proxyName); + log.info("Proxy Deleted"); + } + + /** + * Stop proxy service + * + * @param proxyName name of the proxy + * @throws ProxyServiceAdminProxyAdminException proxy admin exception + * @throws java.rmi.RemoteException remote exception + */ + public void stopProxyService(String proxyName) + throws ProxyServiceAdminProxyAdminException, RemoteException { + + proxyServiceAdminStub.stopProxyService(proxyName); + log.info("Proxy Deactivated"); + } + + /** + * Redeploy proxy service + * + * @param proxyName name of the proxy + * @throws ProxyServiceAdminProxyAdminException proxy admin exception + * @throws java.rmi.RemoteException Remote Exception + */ + public void reloadProxyService(String proxyName) + throws ProxyServiceAdminProxyAdminException, RemoteException { + proxyServiceAdminStub.redeployProxyService(proxyName); + log.info("Proxy Redeployed"); + } + + /** + * Get proxy service details + * + * @param proxyName proxy service name + * @return proxy data + * @throws ProxyServiceAdminProxyAdminException Admin stub exception + * @throws java.rmi.RemoteException Remote Exception + */ + public ProxyData getProxyDetails(String proxyName) + throws ProxyServiceAdminProxyAdminException, RemoteException { + return proxyServiceAdminStub.getProxy(proxyName); + } + + /** + * Method used to create proxy data + * + * @param proxyString proxy configuration + * @return proxy data + */ + //this function from org.wso2.carbon.org.wso2.carbon.org.wso2.carbon.proxyadmin.service in proxy-admin modules + public ProxyData getProxyData(String proxyString) { + final String BUNDLE = "org.wso2.carbon.proxyadmin.Resources"; + ProxyData pd = new ProxyData(); + ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE, Locale.US); + try { + byte[] bytes = null; + try { + bytes = proxyString.getBytes("UTF8"); + } catch (UnsupportedEncodingException e) { + log.error("Unable to extract bytes in UTF-8 encoding. " + + "Extracting bytes in the system default encoding" + e.getMessage()); + bytes = proxyString.getBytes(); + } + OMElement elem = new StAXOMBuilder( + new ByteArrayInputStream(bytes)).getDocumentElement(); + + // check whether synapse namespace is present in the configuration. + Iterator itr = elem.getAllDeclaredNamespaces(); + OMNamespace ns; + boolean synapseNSPresent = false; + while (itr.hasNext()) { + ns = (OMNamespace) itr.next(); + if (XMLConfigConstants.SYNAPSE_NAMESPACE.equals(ns.getNamespaceURI())) { + synapseNSPresent = true; + break; + } + } + + OMAttribute name = elem.getAttribute(new QName("name")); + if (name != null) { + pd.setName(name.getAttributeValue()); + } + + OMAttribute statistics = + elem.getAttribute(new QName(XMLConfigConstants.STATISTICS_ATTRIB_NAME)); + if (statistics != null) { + String statisticsValue = statistics.getAttributeValue(); + if (statisticsValue != null) { + if (XMLConfigConstants.STATISTICS_ENABLE.equals(statisticsValue)) { + pd.setEnableStatistics(true); + } else if (XMLConfigConstants.STATISTICS_DISABLE.equals(statisticsValue)) { + pd.setEnableStatistics(false); + } + } + } + + OMAttribute trans = elem.getAttribute(new QName("transports")); + if (trans != null) { + String transports = trans.getAttributeValue(); + if (transports == null || "".equals(transports) || + ProxyService.ALL_TRANSPORTS.equals(transports)) { + // default to all transports using service name as destination + } else { + String[] arr = transports.split(","); + if (arr != null && arr.length != 0) { + pd.setTransports(arr); + } + } + } + + OMAttribute pinnedServers = elem.getAttribute(new QName("pinnedServers")); + if (pinnedServers != null) { + String pinnedServersValue = pinnedServers.getAttributeValue(); + if (pinnedServersValue == null || "".equals(pinnedServersValue)) { + // default to all servers + } else { + String[] arr = pinnedServersValue.split(","); + if (arr != null && arr.length != 0) { + pd.setPinnedServers(arr); + } + } + } + + OMAttribute trace = elem.getAttribute(new QName(XMLConfigConstants.TRACE_ATTRIB_NAME)); + if (trace != null) { + String traceValue = trace.getAttributeValue(); + if (traceValue != null) { + if (traceValue.equals(XMLConfigConstants.TRACE_ENABLE)) { + pd.setEnableTracing(true); + } else if (traceValue.equals(XMLConfigConstants.TRACE_DISABLE)) { + pd.setEnableTracing(false); + } + } + } + + OMAttribute startOnLoad = elem.getAttribute(new QName("startOnLoad")); + String val; + if (startOnLoad != null && (val = startOnLoad.getAttributeValue()) != null && + !"".equals(val)) { + pd.setStartOnLoad(Boolean.valueOf(val)); + } else { + pd.setStartOnLoad(true); + } + + // read definition of the target of this proxy service. The target could be an 'endpoint' + // or a named sequence. If none of these are specified, the messages would be mediated + // by the Synapse main mediator + OMElement target = elem.getFirstChildWithName( + new QName(XMLConfigConstants.SYNAPSE_NAMESPACE, "target")); + if (target != null) { + OMAttribute inSequence = target.getAttribute(new QName("inSequence")); + if (inSequence != null) { + pd.setInSeqKey(inSequence.getAttributeValue()); + } else { + OMElement inSequenceElement = target.getFirstChildWithName( + new QName(XMLConfigConstants.SYNAPSE_NAMESPACE, "inSequence")); + if (inSequenceElement != null) { + pd.setInSeqXML(inSequenceElement.toString()); + } + } + OMAttribute outSequence = target.getAttribute(new QName("outSequence")); + if (outSequence != null) { + pd.setOutSeqKey(outSequence.getAttributeValue()); + } else { + OMElement outSequenceElement = target.getFirstChildWithName( + new QName(XMLConfigConstants.SYNAPSE_NAMESPACE, "outSequence")); + if (outSequenceElement != null) { + pd.setOutSeqXML(outSequenceElement.toString()); + } + } + OMAttribute faultSequence = target.getAttribute(new QName("faultSequence")); + if (faultSequence != null) { + pd.setFaultSeqKey(faultSequence.getAttributeValue()); + } else { + OMElement faultSequenceElement = target.getFirstChildWithName( + new QName(XMLConfigConstants.SYNAPSE_NAMESPACE, "faultSequence")); + if (faultSequenceElement != null) { + pd.setFaultSeqXML(faultSequenceElement.toString()); + } + } + OMAttribute tgtEndpt = target.getAttribute(new QName("endpoint")); + if (tgtEndpt != null) { + pd.setEndpointKey(tgtEndpt.getAttributeValue()); + } else { + OMElement endpointElement = target.getFirstChildWithName( + new QName(XMLConfigConstants.SYNAPSE_NAMESPACE, "endpoint")); + if (endpointElement != null) { + pd.setEndpointXML(endpointElement.toString()); + } + } + } + + Iterator props = elem.getChildrenWithName( + new QName(XMLConfigConstants.SYNAPSE_NAMESPACE, "parameter")); + ArrayList params = new ArrayList(); + Entry entry = null; + while (props.hasNext()) { + Object o = props.next(); + if (o instanceof OMElement) { + OMElement prop = (OMElement) o; + OMAttribute pname = prop.getAttribute(new QName("name")); + OMElement propertyValue = prop.getFirstElement(); + if (pname != null) { + if (propertyValue != null) { + entry = new Entry(); + entry.setKey(pname.getAttributeValue()); + entry.setValue(propertyValue.toString()); + params.add(entry); + } else { + entry = new Entry(); + entry.setKey(pname.getAttributeValue()); + entry.setValue(prop.getText().trim()); + params.add(entry); + } + } + } + } + pd.setServiceParams(params.toArray(new Entry[params.size()])); + + OMElement wsdl = elem.getFirstChildWithName( + new QName(XMLConfigConstants.SYNAPSE_NAMESPACE, "publishWSDL")); + if (wsdl != null) { + OMAttribute wsdlkey = wsdl.getAttribute( + new QName(XMLConfigConstants.NULL_NAMESPACE, "key")); + OMAttribute wsdlEP = wsdl.getAttribute( + new QName(XMLConfigConstants.NULL_NAMESPACE, "endpoint")); + if (wsdlEP != null) { + //Commenting out this line because of the possible API change in stub + // pd.setPublishWSDLEndpoint(wsdlEP.getAttributeValue()); + } else if (wsdlkey != null) { + pd.setWsdlKey(wsdlkey.getAttributeValue()); + } else { + OMAttribute wsdlURI = wsdl.getAttribute( + new QName(XMLConfigConstants.NULL_NAMESPACE, "uri")); + if (wsdlURI != null) { + pd.setWsdlURI(wsdlURI.getAttributeValue()); + } else { + OMElement wsdl11 = wsdl.getFirstChildWithName( + new QName(WSDLConstants.WSDL1_1_NAMESPACE, "definitions")); + String wsdlDef; + if (wsdl11 != null) { + wsdlDef = wsdl11.toString().replaceAll("\n|\\r|\\f|\\t", ""); + wsdlDef = wsdlDef.replaceAll("> +<", "><"); + pd.setWsdlDef(wsdlDef); + } else { + OMElement wsdl20 = wsdl.getFirstChildWithName( + new QName(WSDL2Constants.WSDL_NAMESPACE, "description")); + if (wsdl20 != null) { + wsdlDef = wsdl20.toString().replaceAll("\n|\\r|\\f|\\t", ""); + wsdlDef = wsdlDef.replaceAll("> +<", "><"); + pd.setWsdlDef(wsdlDef); + } + } + } + } + + Iterator it = wsdl.getChildrenWithName( + new QName(XMLConfigConstants.SYNAPSE_NAMESPACE, "resource")); + ArrayList resources = new ArrayList(); + Entry resource = null; + while (it.hasNext()) { + OMElement resourceElem = (OMElement) it.next(); + OMAttribute location = resourceElem.getAttribute + (new QName(XMLConfigConstants.NULL_NAMESPACE, "location")); + if (location == null) { + throw new XMLStreamException("location element not found in xml file"); + } + OMAttribute key = resourceElem.getAttribute( + new QName(XMLConfigConstants.NULL_NAMESPACE, "key")); + if (key == null) { + throw new XMLStreamException("key element not found in xml file"); + } + resource = new Entry(); + resource.setKey(location.getAttributeValue()); + resource.setValue(key.getAttributeValue()); + resources.add(resource); + } + pd.setWsdlResources(resources.toArray(new Entry[resources.size()])); + } + + OMElement enableSec = + elem.getFirstChildWithName(new QName(XMLConfigConstants.SYNAPSE_NAMESPACE, + "enableSec")); + if (enableSec != null) { + pd.setEnableSecurity(true); + } + + OMElement description = elem.getFirstChildWithName( + new QName(XMLConfigConstants.SYNAPSE_NAMESPACE, "description")); + if (description != null) { + pd.setDescription(description.getText()); + } + + Iterator policies = elem.getChildrenWithName( + new QName(XMLConfigConstants.SYNAPSE_NAMESPACE, "policy")); + while (policies.hasNext()) { + OMElement policyElement = (OMElement) policies.next(); + String policyKey = policyElement.getAttributeValue(new QName("key")); + ProxyServicePolicyInfo policyInfo = new ProxyServicePolicyInfo(); + policyInfo.setKey(policyKey); + pd.addPolicies(policyInfo); + } + + } catch (XMLStreamException e) { + log.error(bundle.getString("unable.to.build.the.design.view.from.the.given.xml"), e); + Assert.fail(bundle.getString("unable.to.build.the.design.view.from.the.given.xml")); + } + return pd; + + } + + /** + * @param data - Proxy Configuration element + * @throws ProxyServiceAdminProxyAdminException + * @throws java.rmi.RemoteException + */ + public void updateProxy(OMElement data) + throws ProxyServiceAdminProxyAdminException, RemoteException { + ProxyData proxyData = getProxyData(data.toString()); + proxyServiceAdminStub.modifyProxy(proxyData); + log.info("Proxy Updated"); + } + + /** + * @param proxyData + * @throws ProxyServiceAdminProxyAdminException + * @throws java.rmi.RemoteException + */ + public void updateProxy(ProxyData proxyData) + throws ProxyServiceAdminProxyAdminException, RemoteException { + proxyServiceAdminStub.modifyProxy(proxyData); + log.info("Proxy Updated"); + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/ActivityAdminServiceClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/ActivityAdminServiceClient.java new file mode 100644 index 0000000000..2ccd452dde --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/ActivityAdminServiceClient.java @@ -0,0 +1,87 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.registry; + +import org.apache.axis2.AxisFault; +import org.apache.axis2.context.ConfigurationContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.registry.activities.stub.ActivityAdminServiceStub; +import org.wso2.carbon.registry.activities.stub.RegistryExceptionException; +import org.wso2.carbon.registry.activities.stub.beans.xsd.ActivityBean; + +import java.rmi.RemoteException; + +public class ActivityAdminServiceClient { + private static final Log log = LogFactory.getLog(ActivityAdminServiceClient.class); + + private final String serviceName = "ActivityAdminService"; + private ActivityAdminServiceStub activityAdminServiceStub; + private String endPoint; + + public final static String FILTER_ALL = "All"; + public final static String FILTER_ASSOCIATE_ASPECT = "Associate Aspect"; + public final static String FILTER_RESOURCE_ADDED = "Resource Add"; + public final static String FILTER_RESOURCE_UPDATE = "Resource Update"; + + public ActivityAdminServiceClient(String backEndUrl, String sessionCookie) throws AxisFault { + this.endPoint = backEndUrl + serviceName; + try { + activityAdminServiceStub = new ActivityAdminServiceStub(endPoint); + } catch (AxisFault axisFault) { + log.error("activityAdminServiceStub Initialization fail " + axisFault.getMessage()); + throw new AxisFault("activityAdminServiceStub Initialization fail ", axisFault); + } + AuthenticateStub.authenticateStub(sessionCookie, activityAdminServiceStub); + } + + public ActivityAdminServiceClient(String backEndUrl, String userName, String password) + throws AxisFault { + this.endPoint = backEndUrl + serviceName; + try { + activityAdminServiceStub = new ActivityAdminServiceStub(endPoint); + } catch (AxisFault axisFault) { + log.error("activityAdminServiceStub Initialization fail " + axisFault.getMessage()); + throw new AxisFault("activityAdminServiceStub Initialization fail ", axisFault); + } + AuthenticateStub.authenticateStub(userName, password, activityAdminServiceStub); + } + + public ActivityBean getActivities(String sessionCookie, String userName, String resourcePath + , String fromDate, String toDate, String filter, int page) + throws RemoteException, RegistryExceptionException { + try { + return activityAdminServiceStub.getActivities(userName, resourcePath, fromDate, toDate + , filter, page + "", sessionCookie); + } catch (RemoteException e) { + String msg = "Fails to get activities"; + log.error(msg + " " + e.getMessage()); + throw new RemoteException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Fails to get activities"; + log.error(msg + " " + e.getMessage()); + throw new RegistryExceptionException(msg, e); + } + } + + public ConfigurationContext getConfigurationContext() { + return activityAdminServiceStub._getServiceClient().getServiceContext() + .getConfigurationContext(); + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/ContentSearchAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/ContentSearchAdminClient.java new file mode 100644 index 0000000000..5137604d76 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/ContentSearchAdminClient.java @@ -0,0 +1,65 @@ +/* +* Copyright 2004,2005 The Apache Software Foundation. +* +* 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 org.wso2.am.admin.clients.registry; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.registry.indexing.stub.generated.ContentSearchAdminServiceStub; +import org.wso2.carbon.registry.indexing.stub.generated.xsd.SearchResultsBean; + +import java.rmi.RemoteException; + +public class ContentSearchAdminClient { + + private static final Log log = LogFactory.getLog(SearchAdminServiceClient.class); + + private ContentSearchAdminServiceStub contentSearchAdminServiceStub; + + public ContentSearchAdminClient(String backEndUrl, String username, String password) + throws AxisFault { + String serviceName = "ContentSearchAdminService"; + String endPoint = backEndUrl + serviceName; + contentSearchAdminServiceStub = new ContentSearchAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(username, password, contentSearchAdminServiceStub); + + } + + public ContentSearchAdminClient(String sessionCookie, String backEndUrl) + throws AxisFault { + String serviceName = "ContentSearchAdminService"; + String endPoint = backEndUrl + serviceName; + contentSearchAdminServiceStub = new ContentSearchAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, contentSearchAdminServiceStub); + + } + + public SearchResultsBean getContentSearchResults(String searchQuery) throws RemoteException { + + SearchResultsBean bean; + try { + bean = contentSearchAdminServiceStub.getContentSearchResults(searchQuery); + } catch (RemoteException e) { + String msg = "Unable o search the contents"; + log.error(msg + e); + throw new RemoteException(msg, e); + } + + return bean; + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/HandlerManagementServiceClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/HandlerManagementServiceClient.java new file mode 100644 index 0000000000..5c232daa2f --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/HandlerManagementServiceClient.java @@ -0,0 +1,170 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.registry; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.registry.handler.stub.ExceptionException; +import org.wso2.carbon.registry.handler.stub.HandlerManagementServiceStub; + +import java.rmi.RemoteException; + +public class HandlerManagementServiceClient { + private static final Log log = LogFactory.getLog(HandlerManagementServiceClient.class); + private final String serviceName = "HandlerManagementService"; + private HandlerManagementServiceStub handlerManagementServiceStub; + private String endPoint; + + public HandlerManagementServiceClient(String backEndUrl, String sessionCookie) + throws AxisFault { + this.endPoint = backEndUrl + serviceName; + try { + handlerManagementServiceStub = new HandlerManagementServiceStub(endPoint); + } catch (AxisFault axisFault) { + log.error("handlerManagementServiceStub Initialization fail " + axisFault.getMessage()); + throw new AxisFault("handlerManagementServiceStub Initialization fail ", axisFault); + } + AuthenticateStub.authenticateStub(sessionCookie, handlerManagementServiceStub); + } + + public HandlerManagementServiceClient(String backEndUrl, String userName, String password) + throws AxisFault { + this.endPoint = backEndUrl + serviceName; + try { + handlerManagementServiceStub = new HandlerManagementServiceStub(endPoint); + } catch (AxisFault axisFault) { + log.error("handlerManagementServiceStub Initialization fail " + axisFault.getMessage()); + throw new AxisFault("handlerManagementServiceStub Initialization fail ", axisFault); + } + AuthenticateStub.authenticateStub(userName, password, handlerManagementServiceStub); + } + + public String[] getHandlerList() throws RemoteException, ExceptionException { + + try { + return handlerManagementServiceStub.getHandlerList(); + + } catch (RemoteException e) { + String msg = "Fails to get Handler List"; + log.error(msg + " " + e.getMessage()); + throw new RemoteException(msg, e); + } catch (ExceptionException e) { + String msg = "Fails to get Handler List"; + log.error(msg + " " + e.getMessage()); + throw new ExceptionException(msg, e); + } + + } + + public boolean createHandler(String payload) throws RemoteException, ExceptionException { + + try { + return handlerManagementServiceStub.createHandler(payload); + } catch (RemoteException e) { + String msg = "Fails to create Handler"; + log.error(msg + " " + e.getMessage()); + throw new RemoteException(msg, e); + } catch (ExceptionException e) { + String msg = "Fails to create Handler"; + log.error(msg + " " + e.getMessage()); + throw new ExceptionException(msg, e); + } + } + + public boolean updateHandler(String oldName, String payload) + throws RemoteException, ExceptionException { + + try { + return handlerManagementServiceStub.updateHandler(oldName, payload); + } catch (RemoteException e) { + String msg = "Fails to update Handler"; + log.error(msg + " " + e.getMessage()); + throw new RemoteException(msg, e); + } catch (ExceptionException e) { + String msg = "Fails to update Handler"; + log.error(msg + " " + e.getMessage()); + throw new ExceptionException(msg, e); + } + } + + public boolean deleteHandler(String name) throws RemoteException, ExceptionException { + + try { + return handlerManagementServiceStub.deleteHandler(name); + } catch (RemoteException e) { + String msg = "Fails to delete Handler"; + log.error(msg + " " + e.getMessage()); + throw new RemoteException(msg, e); + } catch (ExceptionException e) { + String msg = "Fails to delete Handler"; + log.error(msg + " " + e.getMessage()); + throw new ExceptionException(msg, e); + } + } + + public String getHandlerConfiguration(String name) throws RemoteException, ExceptionException { + + try { + return handlerManagementServiceStub.getHandlerConfiguration(name); + } catch (RemoteException e) { + String msg = "Fails to get Handler Configuration"; + log.error(msg + " " + e.getMessage()); + throw new RemoteException(msg, e); + } catch (ExceptionException e) { + String msg = "Fails to get Handler Configuration"; + log.error(msg + " " + e.getMessage()); + throw new ExceptionException(msg, e); + } + } + + public String getHandlerCollectionLocation() throws RemoteException, ExceptionException { + + try { + return handlerManagementServiceStub.getHandlerCollectionLocation(); + } catch (RemoteException e) { + String msg = "Fails to get Handler Collection Location"; + log.error(msg + " " + e.getMessage()); + throw new RemoteException(msg, e); + } catch (ExceptionException e) { + String msg = "Fails to get Handler Collection Location"; + log.error(msg + " " + e.getMessage()); + throw new ExceptionException(msg, e); + } + + } + + public void setHandlerCollectionLocation(String location) + throws RemoteException, ExceptionException { + + try { + handlerManagementServiceStub.setHandlerCollectionLocation(location); + } catch (RemoteException e) { + String msg = "Fails to get Handler Collection Location"; + log.error(msg + " " + e.getMessage()); + throw new RemoteException(msg, e); + } catch (ExceptionException e) { + String msg = "Fails to get Handler Collection Location"; + log.error(msg + " " + e.getMessage()); + throw new ExceptionException(msg, e); + } + + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/InfoServiceAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/InfoServiceAdminClient.java new file mode 100644 index 0000000000..54120de806 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/InfoServiceAdminClient.java @@ -0,0 +1,342 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.registry; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import org.wso2.carbon.registry.info.stub.InfoAdminServiceStub; +import org.wso2.carbon.registry.info.stub.RegistryExceptionException; +import org.wso2.carbon.registry.info.stub.beans.xsd.*; + +import java.rmi.RemoteException; + +public class InfoServiceAdminClient { + + private static final Log log = LogFactory.getLog(InfoServiceAdminClient.class); + + private InfoAdminServiceStub infoAdminServiceStub; + + public InfoServiceAdminClient(String backEndUrl, String sessionCookie) + throws RegistryException, AxisFault { + String serviceName = "InfoAdminService"; + String endPoint = backEndUrl + serviceName; + try { + infoAdminServiceStub = new InfoAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, infoAdminServiceStub); + } catch (AxisFault axisFault) { + log.error("infoAdminServiceStub Initialization fail " + axisFault.getMessage()); + throw new AxisFault( + "infoAdminServiceStub Initialization fail " + axisFault.getMessage()); + } + + } + + public InfoServiceAdminClient(String backEndUrl, String userName, String password) + throws RegistryException, AxisFault { + String serviceName = "InfoAdminService"; + String endPoint = backEndUrl + serviceName; + try { + infoAdminServiceStub = new InfoAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, infoAdminServiceStub); + } catch (AxisFault axisFault) { + log.error("infoAdminServiceStub Initialization fail " + axisFault.getMessage()); + throw new AxisFault( + "infoAdminServiceStub Initialization fail " + axisFault.getMessage()); + } + + } + + public SubscriptionBean subscribe(String path, String endpoint, String eventName, + String sessionId) throws RemoteException { + SubscriptionBean bean = null; + try { + bean = infoAdminServiceStub.subscribe(path, endpoint, eventName, sessionId); + } catch (RemoteException remoteException) { + log.error("infoAdminServiceStub subscription fail " + remoteException.getMessage()); + throw new RemoteException( + "infoAdminServiceStub subscription fail " + remoteException.getMessage()); + + } catch (RegistryExceptionException registryException) { + log.error("infoAdminServiceStub subscription fail " + registryException.getMessage()); + throw new AxisFault( + "infoAdminServiceStub subscription fail " + registryException.getMessage()); + + } + return bean; + } + + public void addComment(String comment, String path, String sessionId) + throws RegistryException, AxisFault { + try { + infoAdminServiceStub.addComment(comment, path, sessionId); + } catch (RemoteException e) { + String msg = "Unable to add comment to resource path - " + path; + log.error(msg, e); + throw new RegistryException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to add comment to resource path - " + path; + log.error(msg, e); + throw new RegistryException(msg, e); + } + } + + public void addTag(String tag, String path, String sessionId) + throws RegistryException, AxisFault { + try { + infoAdminServiceStub.addTag(tag, path, sessionId); + } catch (RemoteException e) { + String msg = "Unable to add tag to resource path - " + path; + log.error(msg, e); + throw new RegistryException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to add tag to resource path - " + path; + log.error(msg, e); + throw new RegistryException(msg, e); + } + } + + public void rateResource(String rating, String path, String sessionId) + throws RegistryException, RegistryExceptionException { + try { + infoAdminServiceStub.rateResource(rating, path, sessionId); + + } catch (RemoteException e) { + String msg = "Unable to rate resource path - " + path; + log.error(msg, e); + throw new RegistryException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to rate resource path - " + path; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public CommentBean getComments(String path, String sessionId) + throws RegistryException, RegistryExceptionException { + try { + return infoAdminServiceStub.getComments(path, sessionId); + } catch (RemoteException e) { + String msg = "Unable to get comments of path - " + path; + log.error(msg, e); + throw new RegistryException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to rate comments of path - " + path; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public RatingBean getRatings(String path, String sessionId) + throws RegistryException, RegistryExceptionException { + try { + return infoAdminServiceStub.getRatings(path, sessionId); + } catch (RemoteException e) { + String msg = "Unable to get ratings of resource path - " + path; + log.error(msg, e); + throw new RegistryException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to get ratings of resource path - " + path; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public TagBean getTags(String path, String sessionId) + throws RegistryException, RegistryExceptionException { + try { + return infoAdminServiceStub.getTags(path, sessionId); + } catch (RemoteException e) { + String msg = "Unable to get tags of resource path - " + path; + log.error(msg, e); + throw new RegistryException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to get tags of resource path - " + path; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public EventTypeBean getEventTypes(String path, String sessionId) + throws RegistryException, RegistryExceptionException { + try { + return infoAdminServiceStub.getEventTypes(path, sessionId); + } catch (RemoteException e) { + String msg = "Unable to get events types of resource path - " + path; + log.error(msg, e); + throw new RegistryException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to get event types of resource path - " + path; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public String getRemoteURL(String path, String sessionId) + throws RegistryException, RegistryExceptionException { + try { + return infoAdminServiceStub.getRemoteURL(path, sessionId); + } catch (RemoteException e) { + String msg = "Unable to get remote URL of resource path - " + path; + log.error(msg, e); + throw new RegistryException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to get remote URL of resource path - " + path; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public SubscriptionBean getSubscriptions(String path, String sessionId) + throws RegistryException, RegistryExceptionException { + try { + return infoAdminServiceStub.getSubscriptions(path, sessionId); + } catch (RemoteException e) { + String msg = "Unable to get subscriptions of resource path - " + path; + log.error(msg, e); + throw new RegistryException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to get subscriptions of resource path - " + path; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public boolean isProfileExisting(String userName, String sessionId) + throws RegistryException, RegistryExceptionException { + try { + return infoAdminServiceStub.isProfileExisting(userName, sessionId); + } catch (RemoteException e) { + String msg = "Unable to check profiles of - " + userName; + log.error(msg, e); + throw new RegistryException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to check profiles of - " + userName; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public boolean isResource(String path, String sessionId) + throws RegistryException, RegistryExceptionException { + try { + return infoAdminServiceStub.isResource(path, sessionId); + } catch (RemoteException e) { + String msg = "Unable to check resource - " + path; + log.error(msg, e); + throw new RegistryException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to check resource - " + path; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public boolean isRoleProfileExisting(String role, String sessionId) + throws RegistryException, RegistryExceptionException { + try { + return infoAdminServiceStub.isRoleProfileExisting(role, sessionId); + } catch (RemoteException e) { + String msg = "Unable to check role profile of - " + role; + log.error(msg, e); + throw new RegistryException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to check role profile of - " + role; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public boolean isRoleValid(String role, String sessionId) + throws RegistryException, RegistryExceptionException { + try { + return infoAdminServiceStub.isRoleValid(role, sessionId); + } catch (RemoteException e) { + String msg = "Unable to check validity of role - " + role; + log.error(msg, e); + throw new RegistryException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to check validity of role - " + role; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public boolean isUserValid(String userName, String sessionId) + throws RegistryException, RegistryExceptionException { + try { + return infoAdminServiceStub.isUserValid(userName, sessionId); + } catch (RemoteException e) { + String msg = "Unable to check validity of user - " + userName; + log.error(msg, e); + throw new RegistryException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to check validity of user - " + userName; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public void removeComment(String commentPath, String sessionId) + throws RegistryException, RegistryExceptionException { + try { + infoAdminServiceStub.removeComment(commentPath, sessionId); + } catch (RemoteException e) { + String msg = "Unable to remove comment"; + log.error(msg, e); + throw new RegistryException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to remove comment "; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public void removeTag(String tag, String path, String sessionId) + throws RegistryException, RegistryExceptionException { + try { + infoAdminServiceStub.removeTag(tag, path, sessionId); + } catch (RemoteException e) { + String msg = "Unable to remove tag"; + log.error(msg, e); + throw new RegistryException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to remove tag "; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public void unsubscribe(String path, String subscriptionId, String sessionID) + throws RemoteException, RegistryExceptionException { + try { + infoAdminServiceStub.unsubscribe(path, subscriptionId, sessionID); + } catch (RemoteException e) { + String msg = "Unable to unsubscribe"; + log.error(msg, e); + throw new RemoteException(msg, e); + } catch (RegistryExceptionException e) { + String msg = "Unable to unsubscribe"; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } +} \ No newline at end of file diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/ProfilesAdminServiceClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/ProfilesAdminServiceClient.java new file mode 100644 index 0000000000..9d17f1f78a --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/ProfilesAdminServiceClient.java @@ -0,0 +1,82 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.registry; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.registry.profiles.stub.ProfilesAdminServiceStub; +import org.wso2.carbon.registry.profiles.stub.beans.xsd.ProfilesBean; + +import java.rmi.RemoteException; + +public class ProfilesAdminServiceClient { + + private final String serviceName = "ProfilesAdminService"; + private ProfilesAdminServiceStub profilesAdminServiceStub; + private String endPoint; + private static final Log log = LogFactory.getLog(ProfilesAdminServiceClient.class); + + public ProfilesAdminServiceClient(String backEndUrl, String sessionCookie) + throws RemoteException { + this.endPoint = backEndUrl + serviceName; + try { + profilesAdminServiceStub = new ProfilesAdminServiceStub(endPoint); + } catch (AxisFault axisFault) { + log.error("Error on initializing listMetadataServiceStub : " + axisFault.getMessage()); + throw new RemoteException("Error on initializing listMetadataServiceStub : ", + axisFault); + } + AuthenticateStub.authenticateStub(sessionCookie, profilesAdminServiceStub); + } + + public ProfilesAdminServiceClient(String backEndUrl, String userName, String password) + throws RemoteException { + this.endPoint = backEndUrl + serviceName; + try { + profilesAdminServiceStub = new ProfilesAdminServiceStub(endPoint); + } catch (AxisFault axisFault) { + log.error("Error on initializing listMetadataServiceStub : " + axisFault.getMessage()); + throw new RemoteException("Error on initializing listMetadataServiceStub : ", + axisFault); + } + AuthenticateStub.authenticateStub(userName, password, profilesAdminServiceStub); + } + + public ProfilesBean getUserProfile(String path) throws Exception { + try { + return profilesAdminServiceStub.getUserProfile(path); + } catch (Exception e) { + String msg = "Unable to get user profiles "; + log.error(msg + e.getMessage()); + throw new Exception(msg, e); + } + } + + public boolean putUserProfile(String path) throws Exception { + try { + return profilesAdminServiceStub.putUserProfile(path); + } catch (Exception e) { + String msg = "Unable to put user profiles "; + log.error(msg + e.getMessage()); + throw new Exception(msg, e); + } + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/PropertiesAdminServiceClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/PropertiesAdminServiceClient.java new file mode 100644 index 0000000000..beabd6c38f --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/PropertiesAdminServiceClient.java @@ -0,0 +1,165 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.registry; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.registry.properties.stub.PropertiesAdminServiceRegistryExceptionException; +import org.wso2.carbon.registry.properties.stub.PropertiesAdminServiceStub; +import org.wso2.carbon.registry.properties.stub.beans.xsd.PropertiesBean; +import org.wso2.carbon.registry.properties.stub.beans.xsd.RetentionBean; + +import java.rmi.RemoteException; + +public class PropertiesAdminServiceClient { + + private static final Log log = LogFactory.getLog(PropertiesAdminServiceClient.class); + + private PropertiesAdminServiceStub propertiesAdminServiceStub; + private final String serviceName = "PropertiesAdminService"; + + public PropertiesAdminServiceClient(String backendURL, String sessionCookie) throws AxisFault { + + String endPoint = backendURL + serviceName; + propertiesAdminServiceStub = new PropertiesAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, propertiesAdminServiceStub); + } + + public PropertiesAdminServiceClient(String backendURL, String userName, String password) + throws AxisFault { + + String endPoint = backendURL + serviceName; + propertiesAdminServiceStub = new PropertiesAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, propertiesAdminServiceStub); + } + + public void setRetentionProperties(String path, String mode, String fromDate, String toDate) + throws RemoteException, PropertiesAdminServiceRegistryExceptionException { + RetentionBean retentionBean = new RetentionBean(); + retentionBean.setWriteLocked(mode.contains("write")); + retentionBean.setDeleteLocked(mode.contains("delete")); + retentionBean.setFromDate(fromDate); + retentionBean.setToDate(toDate); + + try { + propertiesAdminServiceStub.setRetentionProperties(path, retentionBean); + } catch (RemoteException e) { + log.error("Set retention properties failed ", e); + throw new RemoteException("Set retention properties failed ", e); + } catch (PropertiesAdminServiceRegistryExceptionException e) { + log.error("Set retention lock failed ", e); + throw new PropertiesAdminServiceRegistryExceptionException( + "Set retention properties failed ", e); + } + } + + public RetentionBean getRetentionProperties(String path) + throws RemoteException, PropertiesAdminServiceRegistryExceptionException { + RetentionBean retentionBean = new RetentionBean(); + try { + retentionBean = propertiesAdminServiceStub.getRetentionProperties(path); + } catch (RemoteException e) { + log.error("get retention properties failed ", e); + throw new RemoteException("get retention properties failed ", e); + } catch (PropertiesAdminServiceRegistryExceptionException e) { + log.error("get retention properties failed ", e); + throw new PropertiesAdminServiceRegistryExceptionException( + "get retention properties failed ", e); + } + return retentionBean; + } + + public void setProperty(String path, String name, String value) + throws RemoteException, PropertiesAdminServiceRegistryExceptionException { + try { + propertiesAdminServiceStub.setProperty(path, name, value); + } catch (RemoteException e) { + String errMsg = "Adding property fails"; + log.error(errMsg); + throw new RemoteException(errMsg, e); + } catch (PropertiesAdminServiceRegistryExceptionException e) { + String errMsg = "Adding property fails"; + log.error(errMsg); + throw new PropertiesAdminServiceRegistryExceptionException(errMsg, e); + } + } + + public PropertiesBean getProperty(String path, String viewProps) + throws RemoteException, PropertiesAdminServiceRegistryExceptionException { + try { + return propertiesAdminServiceStub.getProperties(path, viewProps); + } catch (RemoteException e) { + String errMsg = "Getting property fails"; + log.error(errMsg); + throw new RemoteException(errMsg, e); + } catch (PropertiesAdminServiceRegistryExceptionException e) { + String errMsg = "Getting property fails"; + log.error(errMsg); + throw new PropertiesAdminServiceRegistryExceptionException(errMsg, e); + } + } + + public PropertiesBean getProperties(String path, String viewProps) + throws RemoteException, PropertiesAdminServiceRegistryExceptionException { + try { + return propertiesAdminServiceStub.getProperties(path, viewProps); + } catch (RemoteException e) { + String errMsg = "Getting properties fails"; + log.error(errMsg); + throw new RemoteException(errMsg, e); + } catch (PropertiesAdminServiceRegistryExceptionException e) { + String errMsg = "Getting properties fails"; + log.error(errMsg); + throw new PropertiesAdminServiceRegistryExceptionException(errMsg, e); + } + } + + public void updateProperty(String path, String name, String value, String oldName) + throws RemoteException, PropertiesAdminServiceRegistryExceptionException { + try { + propertiesAdminServiceStub.updateProperty(path, name, value, oldName); + } catch (RemoteException e) { + String errMsg = "Update properties fails"; + log.error(errMsg); + throw new RemoteException(errMsg, e); + } catch (PropertiesAdminServiceRegistryExceptionException e) { + String errMsg = "Update properties fails"; + log.error(errMsg); + throw new PropertiesAdminServiceRegistryExceptionException(errMsg, e); + } + } + + public void removeProperty(String path, String viewProps) + throws RemoteException, PropertiesAdminServiceRegistryExceptionException { + try { + propertiesAdminServiceStub.removeProperty(path, viewProps); + } catch (RemoteException e) { + String errMsg = "Removing property fails"; + log.error(errMsg); + throw new RemoteException(errMsg, e); + } catch (PropertiesAdminServiceRegistryExceptionException e) { + String errMsg = "Removing property fails"; + log.error(errMsg); + throw new PropertiesAdminServiceRegistryExceptionException(errMsg, e); + } + } + +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/RelationAdminServiceClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/RelationAdminServiceClient.java new file mode 100644 index 0000000000..08d2b132fb --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/RelationAdminServiceClient.java @@ -0,0 +1,94 @@ +/* +* Copyright 2004,2005 The Apache Software Foundation. +* +* 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 org.wso2.am.admin.clients.registry; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.registry.relations.stub.AddAssociationRegistryExceptionException; +import org.wso2.carbon.registry.relations.stub.GetAssociationTreeRegistryExceptionException; +import org.wso2.carbon.registry.relations.stub.GetDependenciesRegistryExceptionException; +import org.wso2.carbon.registry.relations.stub.RelationAdminServiceStub; +import org.wso2.carbon.registry.relations.stub.beans.xsd.AssociationTreeBean; +import org.wso2.carbon.registry.relations.stub.beans.xsd.DependenciesBean; + +import java.rmi.RemoteException; + +public class RelationAdminServiceClient { + + private static final Log log = LogFactory.getLog(RelationAdminServiceClient.class); + + private RelationAdminServiceStub relationAdminServiceStub; + private final String serviceName = "RelationAdminService"; + + public RelationAdminServiceClient(String backendURL, String sessionCookie) + throws AxisFault { + String endPoint = backendURL + serviceName; + relationAdminServiceStub = new RelationAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, relationAdminServiceStub); + } + + public RelationAdminServiceClient(String backendURL, String userName, String password) + throws AxisFault { + String endPoint = backendURL + serviceName; + relationAdminServiceStub = new RelationAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, relationAdminServiceStub); + } + + public void addAssociation(String path, String type, String associationPath, String toDo) + throws RemoteException, AddAssociationRegistryExceptionException { + try { + relationAdminServiceStub.addAssociation(path, type, associationPath, toDo); + } catch (RemoteException e) { + log.error("Add association error "); + throw new RemoteException("Add association error ", e); + } catch (AddAssociationRegistryExceptionException e) { + log.error("Add association error "); + throw new AddAssociationRegistryExceptionException("Add association error ", e); + } + } + + public DependenciesBean getDependencies(String path) + throws RemoteException, AddAssociationRegistryExceptionException { + DependenciesBean dependenciesBean = null; + try { + dependenciesBean = relationAdminServiceStub.getDependencies(path); + } catch (RemoteException e) { + log.error("Get dependencies error "); + throw new RemoteException("Get dependencies error ", e); + } catch (GetDependenciesRegistryExceptionException e) { + log.error("Get dependencies error"); + throw new AddAssociationRegistryExceptionException("Get dependencies error ", e); + } + + return dependenciesBean; + } + + public AssociationTreeBean getAssociationTree(String path, String type) + throws RemoteException, AddAssociationRegistryExceptionException { + try { + return relationAdminServiceStub.getAssociationTree(path, type); + } catch (RemoteException e) { + log.error("Get association tree error "); + throw new RemoteException("Get association tree error ", e); + } catch (GetAssociationTreeRegistryExceptionException e) { + log.error("Get association tree error "); + throw new AddAssociationRegistryExceptionException("Get association tree error ", e); + } + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/ReportAdminServiceClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/ReportAdminServiceClient.java new file mode 100644 index 0000000000..d2f0e59297 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/ReportAdminServiceClient.java @@ -0,0 +1,164 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.registry; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.registry.reporting.stub.ReportingAdminServiceStub; +import org.wso2.carbon.registry.reporting.stub.beans.xsd.ReportConfigurationBean; + +import javax.activation.DataHandler; + +public class ReportAdminServiceClient { + + private static final Log log = + LogFactory.getLog(ReportAdminServiceClient.class); + + private ReportingAdminServiceStub reportingAdminServiceStub; + private final String serviceName = "ReportingAdminService"; + + public ReportAdminServiceClient(String backendURL, String sessionCookie) throws AxisFault { + String endPoint = backendURL + serviceName; + try { + reportingAdminServiceStub = new ReportingAdminServiceStub(endPoint); + } catch (AxisFault axisFault) { + String err = "Stub initialization fail"; + log.error("Stub initialization fail" + axisFault.getMessage()); + throw new AxisFault(err, axisFault); + } + AuthenticateStub.authenticateStub(sessionCookie, reportingAdminServiceStub); + } + + public ReportAdminServiceClient(String backendURL, String userName, String password) + throws AxisFault { + String endPoint = backendURL + serviceName; + try { + reportingAdminServiceStub = new ReportingAdminServiceStub(endPoint); + } catch (AxisFault axisFault) { + String err = "Stub initialization fail"; + log.error("Stub initialization fail" + axisFault.getMessage()); + throw new AxisFault(err, axisFault); + } + AuthenticateStub.authenticateStub(userName, password, reportingAdminServiceStub); + } + + public void saveReport(ReportConfigurationBean configuration) throws Exception { + + try { + reportingAdminServiceStub.saveReport(configuration); + } catch (Exception e) { + String msg = "Unable to save report"; + log.error(msg); + throw new Exception(msg, e); + } + } + + public ReportConfigurationBean getSavedReport(String reportName) throws Exception { + + try { + return reportingAdminServiceStub.getSavedReport(reportName); + } catch (Exception e) { + String msg = "Unable get saved report"; + log.error(msg); + throw new Exception(msg, e); + } + } + + public DataHandler getReportBytes(ReportConfigurationBean configuration) throws Exception { + try { + return reportingAdminServiceStub.getReportBytes(configuration); + } catch (Exception e) { + String msg = "Unable get Report in bytes"; + log.error(msg); + throw new Exception(msg, e); + } + } + + public void deleteSavedReport(String name) throws Exception { + try { + reportingAdminServiceStub.deleteSavedReport(name); + } catch (Exception e) { + String msg = "Unable to delete saved report"; + log.error(msg); + throw new Exception(msg, e); + } + } + + public ReportConfigurationBean[] getSavedReports() throws Exception { + try { + return reportingAdminServiceStub.getSavedReports(); + } catch (Exception e) { + String msg = "Unable to get saved report"; + log.error(msg); + throw new Exception(msg, e); + } + } + + public String[] getAttributeNames(String className) throws Exception { + try { + return reportingAdminServiceStub.getAttributeNames(className); + } catch (Exception e) { + String msg = "Unable to get attribute names"; + log.error(msg); + throw new Exception(msg, e); + } + } + + public String[] getMandatoryAttributeNames(String className) throws Exception { + try { + return reportingAdminServiceStub.getMandatoryAttributeNames(className); + } catch (Exception e) { + String msg = "Unable to get mandatory attribute names"; + log.error(msg); + throw new Exception(msg, e); + } + } + + public void copySavedReport(String saved, String copy) throws Exception { + try { + reportingAdminServiceStub.copySavedReport(saved, copy); + } catch (Exception e) { + String msg = "Unable to copy the report"; + log.error(msg); + throw new Exception(msg, e); + } + } + + public void scheduleReport(ReportConfigurationBean configuration) throws Exception { + try { + reportingAdminServiceStub.scheduleReport(configuration); + } catch (Exception e) { + String msg = "Unable to schedule the report"; + log.error(msg); + throw new Exception(msg, e); + } + } + + public void stopScheduledReport(String reportName) throws Exception { + try { + reportingAdminServiceStub.stopScheduledReport(reportName); + } catch (Exception e) { + String msg = "Unable to stop the scheduled report"; + log.error(msg); + throw new Exception(msg, e); + } + } +} \ No newline at end of file diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/ResourceAdminServiceClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/ResourceAdminServiceClient.java new file mode 100644 index 0000000000..522932fa99 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/ResourceAdminServiceClient.java @@ -0,0 +1,525 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.registry; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.registry.info.stub.RegistryExceptionException; +import org.wso2.carbon.registry.resource.stub.ResourceAdminServiceExceptionException; +import org.wso2.carbon.registry.resource.stub.ResourceAdminServiceResourceServiceExceptionException; +import org.wso2.carbon.registry.resource.stub.ResourceAdminServiceStub; +import org.wso2.carbon.registry.resource.stub.beans.xsd.*; +import org.wso2.carbon.registry.resource.stub.common.xsd.ResourceData; + +import javax.activation.DataHandler; +import java.rmi.RemoteException; + +public class ResourceAdminServiceClient { + private static final Log log = LogFactory.getLog(ResourceAdminServiceClient.class); + + private final String serviceName = "ResourceAdminService"; + private ResourceAdminServiceStub resourceAdminServiceStub; + + private static final String MEDIA_TYPE_WSDL = "application/wsdl+xml"; + private static final String MEDIA_TYPE_WADL = "application/wadl+xml"; + private static final String MEDIA_TYPE_SCHEMA = "application/x-xsd+xml"; + private static final String MEDIA_TYPE_POLICY = "application/policy+xml"; + private static final String MEDIA_TYPE_GOVERNANCE_ARCHIVE = + "application/vnd.wso2.governance-archive"; + + public ResourceAdminServiceClient(String serviceUrl, String sessionCookie) throws AxisFault { + String endPoint = serviceUrl + serviceName; + resourceAdminServiceStub = new ResourceAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, resourceAdminServiceStub); + } + + public ResourceAdminServiceClient(String backEndUrl, String userName, String password) + throws AxisFault { + String endPoint = backEndUrl + serviceName; + resourceAdminServiceStub = new ResourceAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, resourceAdminServiceStub); + } + + public boolean addResource(String destinationPath, String mediaType, + String description, DataHandler dh) + throws ResourceAdminServiceExceptionException, RemoteException { + + if (log.isDebugEnabled()) { + log.debug("Destination Path :" + destinationPath); + log.debug("Media Type :" + mediaType); + } + return resourceAdminServiceStub + .addResource(destinationPath, mediaType, description, dh, null, null); + } + + public ResourceData[] getResource(String destinationPath) + throws ResourceAdminServiceExceptionException, RemoteException { + ResourceData[] rs; + rs = resourceAdminServiceStub.getResourceData(new String[] { destinationPath }); + return rs; + } + + public CollectionContentBean getCollectionContent(String destinationPath) + throws RemoteException, ResourceAdminServiceExceptionException { + CollectionContentBean collectionContentBean; + + try { + collectionContentBean = resourceAdminServiceStub.getCollectionContent(destinationPath); + } catch (RemoteException e) { + log.error("Resource getting failed due to RemoteException : " + e); + throw new RemoteException("Resource getting failed due to RemoteException :", + e); + } catch (ResourceAdminServiceExceptionException e) { + log.error("Resource getting failed due to ResourceAdminServiceExceptionException : ", + e); + throw new ResourceAdminServiceExceptionException( + "Resource getting failed due to ResourceAdminServiceExceptionException:", + e); + } + + return collectionContentBean; + } + + public boolean deleteResource(String destinationPath) + throws ResourceAdminServiceExceptionException, RemoteException { + + return resourceAdminServiceStub.delete(destinationPath); + } + + public void addWSDL(String description, DataHandler dh) + throws ResourceAdminServiceExceptionException, RemoteException { + + String fileName; + fileName = dh.getName().substring(dh.getName().lastIndexOf('/') + 1); + log.debug(fileName); + resourceAdminServiceStub + .addResource("/" + fileName, MEDIA_TYPE_WSDL, description, dh, null, null); + } + + public void addWADL(String description, DataHandler dh) + throws ResourceAdminServiceExceptionException, RemoteException { + + String fileName; + fileName = dh.getName().substring(dh.getName().lastIndexOf('/') + 1); + log.debug(fileName); + resourceAdminServiceStub + .addResource("/" + fileName, MEDIA_TYPE_WADL, description, dh, null, null); + } + + public void addWSDL(String resourceName, String description, + String fetchURL) + throws ResourceAdminServiceExceptionException, RemoteException { + + resourceAdminServiceStub.importResource("/", resourceName, MEDIA_TYPE_WSDL, + description, fetchURL, null, null); + } + + public void addWADL(String resourceName, String description, + String fetchURL) + throws ResourceAdminServiceExceptionException, RemoteException { + + resourceAdminServiceStub.importResource("/", resourceName, MEDIA_TYPE_WADL, + description, fetchURL, null, null); + } + + public void addSchema(String description, DataHandler dh) + throws ResourceAdminServiceExceptionException, RemoteException { + String fileName; + fileName = dh.getName().substring(dh.getName().lastIndexOf('/') + 1); + resourceAdminServiceStub.addResource("/" + fileName, MEDIA_TYPE_SCHEMA, + description, dh, null, null); + } + + public void addSchema(String resourceName, String description, + String fetchURL) throws ResourceAdminServiceExceptionException, + RemoteException { + + resourceAdminServiceStub.importResource("/", resourceName, MEDIA_TYPE_SCHEMA, + description, fetchURL, null, null); + + } + + public void addPolicy(String description, DataHandler dh) + throws ResourceAdminServiceExceptionException, RemoteException { + String fileName; + fileName = dh.getName().substring(dh.getName().lastIndexOf('/') + 1); + resourceAdminServiceStub.addResource("/" + fileName, MEDIA_TYPE_POLICY, + description, dh, null, null); + } + + public void addPolicy(String resourceName, String description, + String fetchURL) + throws ResourceAdminServiceExceptionException, RemoteException { + + resourceAdminServiceStub.importResource("/", resourceName, MEDIA_TYPE_POLICY, + description, fetchURL, null, null); + } + + public void uploadArtifact(String description, DataHandler dh) + throws ResourceAdminServiceExceptionException, RemoteException { + String fileName; + fileName = dh.getName().substring(dh.getName().lastIndexOf('/') + 1); + resourceAdminServiceStub.addResource("/" + fileName, MEDIA_TYPE_GOVERNANCE_ARCHIVE, + description, dh, null, null); + } + + public String addCollection(String parentPath, String collectionName, + String mediaType, String description) + throws ResourceAdminServiceExceptionException, RemoteException { + return resourceAdminServiceStub + .addCollection(parentPath, collectionName, mediaType, description); + } + + public void addSymbolicLink(String parentPath, String name, + String targetPath) + throws ResourceAdminServiceExceptionException, RemoteException { + + resourceAdminServiceStub.addSymbolicLink(parentPath, name, targetPath); + } + + public void addTextResource(String parentPath, String fileName, + String mediaType, String description, String content) + throws RemoteException, ResourceAdminServiceExceptionException { + + resourceAdminServiceStub.addTextResource(parentPath, fileName, mediaType, + description, content); + } + + public void addResourcePermission(String pathToAuthorize, + String roleToAuthorize, + String actionToAuthorize, String permissionType) + throws RemoteException, ResourceAdminServiceResourceServiceExceptionException { + + resourceAdminServiceStub.addRolePermission(pathToAuthorize, roleToAuthorize, + actionToAuthorize, permissionType); + + } + + public String getProperty(String resourcePath, String key) + throws RemoteException, ResourceAdminServiceExceptionException { + + return resourceAdminServiceStub.getProperty(resourcePath, key); + + } + + public MetadataBean getMetadata(String resourcePath) + throws RemoteException, ResourceAdminServiceExceptionException { + + return resourceAdminServiceStub.getMetadata(resourcePath); + } + + public ContentBean getResourceContent(String resourcePath) + throws RemoteException, ResourceAdminServiceExceptionException { + + return resourceAdminServiceStub.getContentBean(resourcePath); + + } + + public ResourceData[] getResourceData(String resourcePath) + throws RemoteException, ResourceAdminServiceExceptionException { + String[] resourceArray = { resourcePath }; + + return resourceAdminServiceStub.getResourceData(resourceArray); + + } + + public String getHumanReadableMediaTypes() throws Exception { + try { + return resourceAdminServiceStub.getHumanReadableMediaTypes(); + } catch (Exception e) { + String msg = "get human readable media type error "; + throw new Exception(msg, e); + } + } + + public String getMimeTypeFromHuman(String mediaType) throws Exception { + + try { + return resourceAdminServiceStub.getMimeTypeFromHuman(mediaType); + } catch (Exception e) { + String msg = "get human readable media type error "; + throw new Exception(msg, e); + + } + } + + public void updateTextContent(String path, String content) + throws RemoteException, ResourceAdminServiceExceptionException { + try { + resourceAdminServiceStub.updateTextContent(path, content); + } catch (RemoteException e) { + log.error("Cannot edit the content of the resource : " + e.getMessage()); + throw new RemoteException("Edit content error : ", e); + + } catch (ResourceAdminServiceExceptionException e) { + log.error("Cannot edit the content of the resource : " + e.getMessage()); + throw new ResourceAdminServiceExceptionException("Get version error : ", e); + + } + } + + public void copyResource(String parentPath, String oldResourcePath, String destinationPath, + String targetName) + throws RemoteException, ResourceAdminServiceExceptionException { + try { + resourceAdminServiceStub + .copyResource(parentPath, oldResourcePath, destinationPath, targetName); + } catch (RemoteException e) { + log.error("Copy resource error "); + throw new RemoteException("Copy resource error ", e); + } catch (ResourceAdminServiceExceptionException e) { + log.error("Copy resource error"); + throw new ResourceAdminServiceExceptionException("Copy resource error", e); + } + } + + public void moveResource(String parentPath, String oldResourcePath, String destinationPath, + String targetName) + throws RemoteException, ResourceAdminServiceExceptionException { + try { + resourceAdminServiceStub + .moveResource(parentPath, oldResourcePath, destinationPath, targetName); + } catch (RemoteException e) { + log.error("Move resource error "); + throw new RemoteException("Copy resource error ", e); + } catch (ResourceAdminServiceExceptionException e) { + log.error("Move resource error"); + throw new ResourceAdminServiceExceptionException("Copy resource error", e); + } + } + + public VersionPath[] getVersionPaths(String path) + throws RemoteException, ResourceAdminServiceExceptionException { + VersionPath[] versionPaths = null; + try { + VersionsBean vb = resourceAdminServiceStub.getVersionsBean(path); + versionPaths = vb.getVersionPaths(); + } catch (RemoteException e) { + log.error("No versions for created path : " + e.getMessage()); + throw new RemoteException("Get version error : ", e); + } catch (ResourceAdminServiceExceptionException e) { + log.error("Get version error : " + e.getMessage()); + throw new ResourceAdminServiceExceptionException("Get version error : ", e); + } + return versionPaths; + } + + public VersionsBean getVersionsBean(String path) + throws RemoteException, ResourceAdminServiceExceptionException { + + try { + return resourceAdminServiceStub.getVersionsBean(path); + } catch (RemoteException e) { + log.error("Get version bean fails: " + e.getMessage()); + throw new RemoteException("Get version bean fails: ", e); + } catch (ResourceAdminServiceExceptionException e) { + log.error("Get version bean fails: " + e.getMessage()); + throw new ResourceAdminServiceExceptionException("Get version bean fails: : ", e); + } + } + + public void createVersion(String resourcePath) + throws RemoteException, ResourceAdminServiceExceptionException { + try { + resourceAdminServiceStub.createVersion(resourcePath); + } catch (RemoteException e) { + log.error("Create version error : " + e.getMessage()); + throw new RemoteException("Create version error : ", e); + } catch (ResourceAdminServiceExceptionException e) { + log.error("Create version error : " + e.getMessage()); + throw new ResourceAdminServiceExceptionException("Create version error : ", e); + } + } + + public void deleteVersionHistory(String path, String snapshotID) + throws RemoteException, ResourceAdminServiceExceptionException { + try { + resourceAdminServiceStub.deleteVersionHistory(path, snapshotID); + + } catch (RemoteException e) { + log.error("No versions to delete : " + e.getMessage()); + throw new RemoteException("Delete version error : ", e); + } catch (ResourceAdminServiceExceptionException e) { + log.error("Delete version error : " + e.getMessage()); + throw new ResourceAdminServiceExceptionException("Delete version error : ", e); + + } + } + + public boolean restoreVersion(String path) + throws RemoteException, ResourceAdminServiceExceptionException { + boolean status = false; + try { + status = resourceAdminServiceStub.restoreVersion(path); + + } catch (RemoteException e) { + log.error("No versions to restore : " + e.getMessage()); + throw new RemoteException("Restore version error : ", e); + } catch (ResourceAdminServiceExceptionException e) { + log.error("Restore version error : " + e.getMessage()); + throw new ResourceAdminServiceExceptionException("Restore version error : ", e); + } + return status; + } + + public String getTextContent(String path) + throws RemoteException, ResourceAdminServiceExceptionException { + String content = null; + try { + content = resourceAdminServiceStub.getTextContent(path); + } catch (RemoteException e) { + log.error("Unable get content : " + e.getMessage()); + throw new RemoteException("Restore version error : ", e); + } catch (ResourceAdminServiceExceptionException e) { + log.error("GetTextContent Error : " + e.getMessage()); + throw new ResourceAdminServiceExceptionException("GetTextContent Error : ", e); + } + return content; + } + + public PermissionBean getPermission(String path) throws Exception { + try { + return resourceAdminServiceStub.getPermissions(path); + } catch (Exception e) { + log.error("Unable to get permission : " + e.getMessage()); + throw new Exception("Unable to get permission : ", e); + } + } + + public void renameResource(String parentPath, String oldResourcePath, String newResourceName) + throws RemoteException, ResourceAdminServiceExceptionException { + try { + resourceAdminServiceStub.renameResource(parentPath, oldResourcePath, newResourceName); + } catch (RemoteException e) { + log.error("Rename resource error "); + throw new RemoteException("Rename resource error ", e); + } catch (ResourceAdminServiceExceptionException e) { + log.error("Rename resource error"); + throw new ResourceAdminServiceExceptionException("Rename resource error", e); + } + } + + public boolean addExtension(String name, DataHandler content) + throws RemoteException, ResourceAdminServiceExceptionException { + try { + return resourceAdminServiceStub.addExtension(name, content); + } catch (RemoteException e) { + log.error("Add extension error "); + throw new RemoteException("Rename resource error ", e); + } catch (ResourceAdminServiceExceptionException e) { + log.error("Add Extension error"); + throw new ResourceAdminServiceExceptionException("Rename resource error", e); + } + } + + public boolean removeExtension(String name) + throws RemoteException, ResourceAdminServiceExceptionException { + try { + return resourceAdminServiceStub.removeExtension(name); + } catch (RemoteException e) { + log.error("Remove extension error "); + throw new RemoteException("Remove resource error ", e); + } catch (ResourceAdminServiceExceptionException e) { + log.error("Remove Extension error"); + throw new ResourceAdminServiceExceptionException("Remove resource error", e); + } + } + + public String[] listExtensions() + throws RemoteException, ResourceAdminServiceExceptionException { + try { + return resourceAdminServiceStub.listExtensions(); + } catch (RemoteException e) { + log.error("List extensions error "); + throw new RemoteException("List extensions error ", e); + } catch (ResourceAdminServiceExceptionException e) { + log.error("List extensions error "); + throw new ResourceAdminServiceExceptionException("List extensions error ", e); + } + } + + public void setDescription(String path, String description) + throws RemoteException, RegistryExceptionException { + try { + resourceAdminServiceStub.setDescription(path, description); + } catch (RemoteException e) { + String msg = "Unable set description for the path - " + path; + log.error(msg, e); + throw new RemoteException("List extensions error ", e); + + } catch (ResourceAdminServiceExceptionException e) { + String msg = "Unable set description for the path - " + path; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public ContentDownloadBean getContentDownloadBean(String path) + throws RemoteException, RegistryExceptionException { + try { + return resourceAdminServiceStub.getContentDownloadBean(path); + } catch (RemoteException e) { + String msg = "Unable to retrieve content download bean - " + path; + log.error(msg, e); + throw new RemoteException(msg, e); + + } catch (ResourceAdminServiceExceptionException e) { + String msg = "Unable to retrieve content download bean - " + path; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public boolean importResource(String parentPath, String resourceName, String mediaType, + String description, String fetchURL, String symLink) + throws RemoteException, RegistryExceptionException { + try { + return resourceAdminServiceStub + .importResource(parentPath, resourceName, mediaType, description, fetchURL, + symLink, null); + } catch (RemoteException e) { + String msg = "Unable to import resource"; + log.error(msg, e); + throw new RemoteException(msg, e); + + } catch (ResourceAdminServiceExceptionException e) { + String msg = "Unable to import resource"; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + + public ResourceTreeEntryBean getResourceTreeEntryBean(String resourcePath) + throws RemoteException, RegistryExceptionException { + try { + return resourceAdminServiceStub.getResourceTreeEntry(resourcePath); + } catch (RemoteException e) { + String msg = "Unable get resource tree entry"; + log.error(msg, e); + throw new RemoteException(msg, e); + + } catch (ResourceAdminServiceExceptionException e) { + String msg = "Unable get resource tree entry"; + log.error(msg, e); + throw new RegistryExceptionException(msg, e); + } + } + +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/SearchAdminServiceClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/SearchAdminServiceClient.java new file mode 100644 index 0000000000..dbf27ae27a --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/registry/SearchAdminServiceClient.java @@ -0,0 +1,90 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.registry; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.registry.search.stub.SearchAdminServiceRegistryExceptionException; +import org.wso2.carbon.registry.search.stub.SearchAdminServiceStub; +import org.wso2.carbon.registry.search.stub.beans.xsd.AdvancedSearchResultsBean; +import org.wso2.carbon.registry.search.stub.beans.xsd.CustomSearchParameterBean; +import org.wso2.carbon.registry.search.stub.beans.xsd.MediaTypeValueList; +import org.wso2.carbon.registry.search.stub.beans.xsd.SearchResultsBean; + +import java.rmi.RemoteException; + +public class SearchAdminServiceClient { + private static final Log log = LogFactory.getLog(SearchAdminServiceClient.class); + + private final String serviceName = "SearchAdminService"; + private SearchAdminServiceStub searchAdminServiceStub; + + public SearchAdminServiceClient(String backEndUrl, String sessionCookie) throws AxisFault { + String endPoint = backEndUrl + serviceName; + searchAdminServiceStub = new SearchAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, searchAdminServiceStub); + } + + public SearchAdminServiceClient(String backEndUrl, String username, String password) + throws AxisFault { + String endPoint = backEndUrl + serviceName; + searchAdminServiceStub = new SearchAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(username, password, searchAdminServiceStub); + } + + public void deleteFilter(String filterName) + throws SearchAdminServiceRegistryExceptionException, RemoteException { + + searchAdminServiceStub.deleteFilter(filterName); + } + + public CustomSearchParameterBean getAdvancedSearchFilter(String filterName) + throws SearchAdminServiceRegistryExceptionException, RemoteException { + return searchAdminServiceStub.getAdvancedSearchFilter(filterName); + } + + public MediaTypeValueList getMediaTypeSearch(String mediaType) + throws SearchAdminServiceRegistryExceptionException, RemoteException { + return searchAdminServiceStub.getMediaTypeSearch(mediaType); + } + + public AdvancedSearchResultsBean getAdvancedSearchResults( + CustomSearchParameterBean searchParams) + throws SearchAdminServiceRegistryExceptionException, RemoteException { + return searchAdminServiceStub.getAdvancedSearchResults(searchParams); + } + + public String[] getSavedFilters() + throws SearchAdminServiceRegistryExceptionException, RemoteException { + return searchAdminServiceStub.getSavedFilters(); + } + + public SearchResultsBean getSearchResults(String searchType, String criteria) + throws SearchAdminServiceRegistryExceptionException, RemoteException { + return searchAdminServiceStub.getSearchResults(searchType, criteria); + + } + + public void saveAdvancedSearchFilter(CustomSearchParameterBean queryBean, String filterName) + throws SearchAdminServiceRegistryExceptionException, RemoteException { + searchAdminServiceStub.saveAdvancedSearchFilter(queryBean, filterName); + + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/rest/api/RestApiAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/rest/api/RestApiAdminClient.java new file mode 100644 index 0000000000..4380db0d9f --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/rest/api/RestApiAdminClient.java @@ -0,0 +1,60 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.rest.api; + +import org.apache.axiom.om.OMElement; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.rest.api.stub.RestApiAdminAPIException; +import org.wso2.carbon.rest.api.stub.RestApiAdminStub; + +import java.rmi.RemoteException; + +public class RestApiAdminClient { + private static final Log log = LogFactory.getLog(RestApiAdminClient.class); + + private RestApiAdminStub restApiAdminStub; + private final String serviceName = "RestApiAdmin"; + + public RestApiAdminClient(String backEndUrl, String sessionCookie) throws AxisFault { + String endPoint = backEndUrl + serviceName; + restApiAdminStub = new RestApiAdminStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, restApiAdminStub); + } + + public RestApiAdminClient(String backEndUrl, String userName, String password) + throws AxisFault { + String endPoint = backEndUrl + serviceName; + restApiAdminStub = new RestApiAdminStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, restApiAdminStub); + } + + public boolean add(OMElement apiData) throws RestApiAdminAPIException, RemoteException { + return restApiAdminStub.addApiFromString(apiData.toString()); + } + + public boolean deleteApi(String apiName) throws RestApiAdminAPIException, RemoteException { + return restApiAdminStub.deleteApi(apiName); + } + + public String[] getApiNames() throws RestApiAdminAPIException, RemoteException { + return restApiAdminStub.getApiNames(); + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/sequences/SequenceAdminServiceClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/sequences/SequenceAdminServiceClient.java new file mode 100644 index 0000000000..c58821294d --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/sequences/SequenceAdminServiceClient.java @@ -0,0 +1,233 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.sequences; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.sequences.stub.types.SequenceAdminServiceStub; +import org.wso2.carbon.sequences.stub.types.SequenceEditorException; +import org.wso2.carbon.sequences.stub.types.common.to.SequenceInfo; + +import javax.activation.DataHandler; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.rmi.RemoteException; + +public class SequenceAdminServiceClient { + private static final Log log = LogFactory.getLog(SequenceAdminServiceClient.class); + + private final String serviceName = "SequenceAdminService"; + private SequenceAdminServiceStub sequenceAdminServiceStub; + + public SequenceAdminServiceClient(String backEndUrl, String sessionCookie) throws AxisFault { + String endPoint = backEndUrl + serviceName; + sequenceAdminServiceStub = new SequenceAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, sequenceAdminServiceStub); + } + + public SequenceAdminServiceClient(String backEndUrl, String userName, String password) + throws AxisFault { + String endPoint = backEndUrl + serviceName; + sequenceAdminServiceStub = new SequenceAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, sequenceAdminServiceStub); + } + + /** + * adding sequence + * + * @param dh + * @throws SequenceEditorException + * @throws java.io.IOException + * @throws javax.xml.stream.XMLStreamException + */ + public void addSequence(DataHandler dh) + throws SequenceEditorException, IOException, XMLStreamException { + + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + //create the builder + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement sequenceElem = builder.getDocumentElement(); + sequenceAdminServiceStub.addSequence(sequenceElem); + } + + /** + * adding sequence + * + * @param sequence + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public void addSequence(OMElement sequence) throws SequenceEditorException, RemoteException { + sequenceAdminServiceStub.addSequence(sequence); + } + + /** + * updating existing sequence + * + * @param sequence + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public void updateSequence(OMElement sequence) throws SequenceEditorException, RemoteException { + sequenceAdminServiceStub.saveSequence(sequence); + } + + /** + * adding dynamic sequence + * + * @param key + * @param omElement + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public void addDynamicSequence(String key, OMElement omElement) + throws SequenceEditorException, RemoteException { + sequenceAdminServiceStub.addDynamicSequence(key, omElement); + + } + + /** + * getting sequence element + * + * @param sequenceName + * @return + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public OMElement getSequence(String sequenceName) + throws SequenceEditorException, RemoteException { + return sequenceAdminServiceStub.getSequence(sequenceName); + + } + + /** + * deleting existing sequence + * + * @param sequenceName + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public void deleteSequence(String sequenceName) + throws SequenceEditorException, RemoteException { + sequenceAdminServiceStub.deleteSequence(sequenceName); + + } + + /** + * updating dynamic sequence + * + * @param key + * @param OmSequence + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public void updateDynamicSequence(String key, OMElement OmSequence) + throws SequenceEditorException, RemoteException { + sequenceAdminServiceStub.updateDynamicSequence(key, OmSequence); + } + + /** + * getting dynamic sequence count + * + * @return + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public int getDynamicSequenceCount() + throws SequenceEditorException, RemoteException { + return sequenceAdminServiceStub.getDynamicSequenceCount(); + } + + /** + * deleting dynamic sequence + * + * @param key + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public void deleteDynamicSequence(String key) + throws SequenceEditorException, RemoteException { + sequenceAdminServiceStub.deleteDynamicSequence(key); + } + + /** + * getting sequence list + * + * @param pageNo + * @param sequencePerPage + * @return + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public SequenceInfo[] getSequences(int pageNo, int sequencePerPage) + throws SequenceEditorException, RemoteException { + return sequenceAdminServiceStub.getSequences(pageNo, sequencePerPage); + } + + /** + * getting sequence list + * + * @return + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public String[] getSequences() + throws SequenceEditorException, RemoteException { + SequenceInfo[] info = sequenceAdminServiceStub.getSequences(0, 200); + String[] sequences; + + if (info != null && info.length > 0) { + sequences = new String[info.length]; + } else { + return null; + } + for (int i = 0; i < info.length; i++) { + sequences[i] = info[i].getName(); + } + return sequences; + } + + /** + * getting dynamic sequence list + * + * @return + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public String[] getDynamicSequences() throws SequenceEditorException, RemoteException { + SequenceInfo[] seqInfo = sequenceAdminServiceStub.getDynamicSequences(0, 200); + String[] sequences; + + if (seqInfo != null && seqInfo.length > 0) { + sequences = new String[seqInfo.length]; + } else { + return null; + } + for (int i = 0; i < seqInfo.length; i++) { + sequences[i] = seqInfo[i].getName(); + } + return sequences; + } +} \ No newline at end of file diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/service/mgt/ServiceAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/service/mgt/ServiceAdminClient.java new file mode 100644 index 0000000000..ce9142f935 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/service/mgt/ServiceAdminClient.java @@ -0,0 +1,292 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.service.mgt; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.service.mgt.stub.ServiceAdminException; +import org.wso2.carbon.service.mgt.stub.ServiceAdminStub; +import org.wso2.carbon.service.mgt.stub.types.carbon.FaultyService; +import org.wso2.carbon.service.mgt.stub.types.carbon.FaultyServicesWrapper; +import org.wso2.carbon.service.mgt.stub.types.carbon.ServiceMetaData; +import org.wso2.carbon.service.mgt.stub.types.carbon.ServiceMetaDataWrapper; + +import java.rmi.RemoteException; + +public class ServiceAdminClient { + private static final Log log = LogFactory.getLog(ServiceAdminClient.class); + private final String serviceName = "ServiceAdmin"; + private ServiceAdminStub serviceAdminStub; + + public ServiceAdminClient(String backEndUrl, String sessionCookie) throws AxisFault { + + String endPoint = backEndUrl + serviceName; + serviceAdminStub = new ServiceAdminStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, serviceAdminStub); + } + + public ServiceAdminClient(String backEndUrl, String userName, String password) + throws AxisFault { + + String endPoint = backEndUrl + serviceName; + serviceAdminStub = new ServiceAdminStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, serviceAdminStub); + } + + public void deleteService(String[] serviceGroup) throws RemoteException { + + serviceAdminStub.deleteServiceGroups(serviceGroup); + + } + + public boolean deleteFaultyService(String archiveName) throws RemoteException { + try { + return serviceAdminStub.deleteFaultyServiceGroup(archiveName); + } catch (RemoteException e) { + log.error("Faulty service deletion fails", e); + throw new RemoteException("Faulty service deletion fails", e); + } + } + + public boolean deleteFaultyServiceByServiceName(String serviceName) throws RemoteException { + try { + return serviceAdminStub + .deleteFaultyServiceGroup(getFaultyData(serviceName).getArtifact()); + } catch (RemoteException e) { + log.error("Faulty service deletion fails", e); + throw new RemoteException("Faulty service deletion fails", e); + } + } + + public void deleteAllNonAdminServiceGroups() throws RemoteException { + + serviceAdminStub.deleteAllNonAdminServiceGroups(); + + } + + public ServiceMetaDataWrapper listServices(String serviceName) + throws RemoteException { + ServiceMetaDataWrapper serviceMetaDataWrapper; + serviceMetaDataWrapper = serviceAdminStub.listServices("ALL", serviceName, 0); + serviceAdminStub.getFaultyServiceArchives(0); + return serviceMetaDataWrapper; + } + + public ServiceMetaDataWrapper listServices(String serviceName, String filerType) + throws RemoteException { + ServiceMetaDataWrapper serviceMetaDataWrapper; + serviceMetaDataWrapper = serviceAdminStub.listServices(filerType, serviceName, 0); + serviceAdminStub.getFaultyServiceArchives(0); + return serviceMetaDataWrapper; + } + + public FaultyServicesWrapper getFaultyServiceArchives(int pageNumber) throws RemoteException { + FaultyServicesWrapper faultyServicesWrapper; + try { + faultyServicesWrapper = serviceAdminStub.getFaultyServiceArchives(pageNumber); + } catch (RemoteException e) { + log.error("Unable to get faulty service Archives", e); + throw new RemoteException("Unable to get faulty service Archives", e); + } + return faultyServicesWrapper; + } + + public FaultyServicesWrapper listFaultyServices() throws RemoteException { + FaultyServicesWrapper faultyServicesWrapper; + + faultyServicesWrapper = serviceAdminStub.getFaultyServiceArchives(0); + + return faultyServicesWrapper; + } + + public boolean isServiceExists(String serviceName) + throws RemoteException { + boolean serviceState = false; + ServiceMetaDataWrapper serviceMetaDataWrapper; + ServiceMetaData[] serviceMetaDataList; + serviceMetaDataWrapper = listServices(serviceName); + serviceMetaDataList = serviceMetaDataWrapper.getServices(); + if (serviceMetaDataList == null || serviceMetaDataList.length == 0) { + serviceState = false; + } else { + for (ServiceMetaData serviceData : serviceMetaDataList) { + if (serviceData != null && serviceData.getName().equalsIgnoreCase(serviceName)) { + return true; + } + } + } + return serviceState; + } + + public void deleteMatchingServiceByGroup(String serviceFileName) + throws RemoteException { + String matchingServiceName = getMatchingServiceName(serviceFileName); + if (matchingServiceName != null) { + String serviceGroup[] = { getServiceGroup(matchingServiceName) }; + log.info("Service group name " + serviceGroup[0]); + + serviceAdminStub.deleteServiceGroups(serviceGroup); + + } else { + log.error("Service group name cannot be null"); + } + } + + public String deleteAllServicesByType(String type) + throws RemoteException { + ServiceMetaDataWrapper serviceMetaDataWrapper; + + serviceMetaDataWrapper = serviceAdminStub.listServices("ALL", null, 0); + + ServiceMetaData[] serviceMetaDataList; + if (serviceMetaDataWrapper != null) { + serviceMetaDataList = serviceMetaDataWrapper.getServices(); + + String[] serviceGroup; + if (serviceMetaDataList != null && serviceMetaDataList.length > 0) { + + for (ServiceMetaData serviceData : serviceMetaDataList) { + if (serviceData.getServiceType().equalsIgnoreCase(type)) { + serviceGroup = new String[] { serviceData.getServiceGroupName() }; + deleteService(serviceGroup); + } + } + } + } + return null; + + } + + public String getMatchingServiceName(String serviceFileName) + throws RemoteException { + + ServiceMetaDataWrapper serviceMetaDataWrapper; + serviceMetaDataWrapper = serviceAdminStub.listServices("ALL", serviceFileName, 0); + + ServiceMetaData[] serviceMetaDataList; + if (serviceMetaDataWrapper != null) { + serviceMetaDataList = serviceMetaDataWrapper.getServices(); + if (serviceMetaDataList != null && serviceMetaDataList.length > 0) { + + for (ServiceMetaData serviceData : serviceMetaDataList) { + if (serviceData != null && serviceData.getName().contains(serviceFileName)) { + return serviceData.getName(); + } + } + } + } + return null; + } + + public String getServiceGroup(String serviceName) throws RemoteException { + ServiceMetaDataWrapper serviceMetaDataWrapper; + ServiceMetaData[] serviceMetaDataList; + serviceMetaDataWrapper = listServices(serviceName); + serviceMetaDataList = serviceMetaDataWrapper.getServices(); + if (serviceMetaDataList != null && serviceMetaDataList.length > 0) { + for (ServiceMetaData serviceData : serviceMetaDataList) { + if (serviceData != null && serviceData.getName().equalsIgnoreCase(serviceName)) { + return serviceData.getServiceGroupName(); + } + } + } + return null; + } + + public boolean isServiceFaulty(String serviceName) throws RemoteException { + boolean serviceState = false; + FaultyServicesWrapper faultyServicesWrapper; + FaultyService[] faultyServiceList; + faultyServicesWrapper = listFaultyServices(); + if (faultyServicesWrapper != null) { + faultyServiceList = faultyServicesWrapper.getFaultyServices(); + if (faultyServiceList == null || faultyServiceList.length == 0) { + serviceState = false; + } else { + for (FaultyService faultyServiceData : faultyServiceList) { + if (faultyServiceData != null && + faultyServiceData.getServiceName().equalsIgnoreCase(serviceName)) { + return true; + } + } + } + } + return serviceState; + } + + public FaultyService getFaultyData(String serviceName) throws RemoteException { + FaultyService faultyService = null; + FaultyServicesWrapper faultyServicesWrapper; + FaultyService[] faultyServiceList; + faultyServicesWrapper = listFaultyServices(); + if (faultyServicesWrapper != null) { + faultyServiceList = faultyServicesWrapper.getFaultyServices(); + if (faultyServiceList == null || faultyServiceList.length == 0) { + throw new RuntimeException("Service not found in faulty service list"); + } else { + for (FaultyService faultyServiceData : faultyServiceList) { + if (faultyServiceData != null && + faultyServiceData.getServiceName().equalsIgnoreCase(serviceName)) { + faultyService = faultyServiceData; + } + } + } + } + if (faultyService == null) { + throw new RuntimeException("Service not found in faulty service list " + faultyService); + } + return faultyService; + } + + public ServiceMetaData getServicesData(String serviceName) + throws ServiceAdminException, RemoteException { + + return serviceAdminStub.getServiceData(serviceName); + + } + + public void startService(String serviceName) throws ServiceAdminException, RemoteException { + + serviceAdminStub.startService(serviceName); + log.info("Service Started"); + + } + + public void stopService(String serviceName) throws ServiceAdminException, RemoteException { + + serviceAdminStub.stopService(serviceName); + log.info("Service Stopped"); + + } + + /** + * @param serviceName + * @return + * @throws ServiceAdminException + * @throws java.rmi.RemoteException + */ + public String[] getExposedTransports(String serviceName) + throws ServiceAdminException, RemoteException { + + return serviceAdminStub.getExposedTransports(serviceName); + + } + +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/tasks/TaskAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/tasks/TaskAdminClient.java new file mode 100755 index 0000000000..eff525abf8 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/tasks/TaskAdminClient.java @@ -0,0 +1,104 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.tasks; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.task.stub.TaskAdminStub; +import org.wso2.carbon.task.stub.TaskManagementException; + +import javax.activation.DataHandler; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class TaskAdminClient { + private static final Log log = LogFactory.getLog(TaskAdminClient.class); + + private final String serviceName = "TaskAdmin"; + private TaskAdminStub taskAdminStub; + + public TaskAdminClient(String backEndUrl, String sessionCookie) throws AxisFault { + String endPoint = backEndUrl + serviceName; + taskAdminStub = new TaskAdminStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, taskAdminStub); + } + + public TaskAdminClient(String backEndUrl, String userName, String password) throws AxisFault { + String endPoint = backEndUrl + serviceName; + taskAdminStub = new TaskAdminStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, taskAdminStub); + } + + public void addTask(DataHandler dh) + throws TaskManagementException, IOException, XMLStreamException { + + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + //create the builder + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement scheduleTaskElem = builder.getDocumentElement(); + // scheduleTaskElem.setText("test"); + taskAdminStub.addTaskDescription(scheduleTaskElem); + } + + public void addTask(OMElement scheduleTaskElem) + throws TaskManagementException, RemoteException { + taskAdminStub.addTaskDescription(scheduleTaskElem); + } + + public void deleteTask(String name, String group) + throws TaskManagementException, RemoteException { + taskAdminStub.deleteTaskDescription(name, group); + + } + + public OMElement getScheduleTask(String name, String group) + throws TaskManagementException, RemoteException { + return taskAdminStub.getTaskDescription(name, group); + + } + + public OMElement getAllTaskDescriptions() throws RemoteException, TaskManagementException { + return taskAdminStub.getAllTaskDescriptions(); + } + + public List getScheduleTaskList() throws RemoteException, TaskManagementException { + ArrayList taskList = new ArrayList(); + OMElement tasksOme = getAllTaskDescriptions().getFirstElement(); + if (tasksOme != null) { + Iterator itr = tasksOme.getChildrenWithName(new QName("task")); + while (itr.hasNext()) { + OMElement taskOme = itr.next(); + taskList.add(taskOme.getAttributeValue(new QName("name"))); + } + } + return taskList; + } + +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/template/EndpointTemplateAdminServiceClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/template/EndpointTemplateAdminServiceClient.java new file mode 100644 index 0000000000..e7b0ec1df9 --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/template/EndpointTemplateAdminServiceClient.java @@ -0,0 +1,116 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.template; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.mediation.templates.endpoint.stub.types.EndpointTemplateAdminServiceStub; +import org.wso2.carbon.mediation.templates.endpoint.stub.types.common.EndpointTemplateInfo; + +import javax.activation.DataHandler; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.rmi.RemoteException; + +/* +This class can be used to manage ESB Endpoint templates +*/ +public class EndpointTemplateAdminServiceClient { + private static final Log log = LogFactory.getLog(EndpointTemplateAdminServiceClient.class); + + private final String serviceName = "EndpointTemplateAdminService"; + private EndpointTemplateAdminServiceStub endpointTemplateAdminStub; + + public EndpointTemplateAdminServiceClient(String backEndUrl, String sessionCookie) + throws AxisFault { + String endPoint = backEndUrl + serviceName; + endpointTemplateAdminStub = new EndpointTemplateAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, endpointTemplateAdminStub); + } + + public EndpointTemplateAdminServiceClient(String backEndUrl, String userName, String password) + throws AxisFault { + String endPoint = backEndUrl + serviceName; + endpointTemplateAdminStub = new EndpointTemplateAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, endpointTemplateAdminStub); + } + + public void addEndpointTemplate(OMElement endpointTemplate) throws RemoteException { + endpointTemplateAdminStub.addEndpointTemplate(endpointTemplate.toString()); + } + + public void addEndpointTemplate(DataHandler dh) throws IOException, XMLStreamException { + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + //create the builder + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement endpointTemplate = builder.getDocumentElement(); + endpointTemplateAdminStub.addEndpointTemplate(endpointTemplate.toString()); + } + + public void addDynamicEndpointTemplate(String key, OMElement endpointTemplate) + throws RemoteException { + endpointTemplateAdminStub.addDynamicEndpointTemplate(key, endpointTemplate.toString()); + } + + public void addDynamicEndpointTemplate(String key, DataHandler dh) + throws IOException, XMLStreamException { + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + //create the builder + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement endpointTemplate = builder.getDocumentElement(); + endpointTemplateAdminStub.addDynamicEndpointTemplate(key, endpointTemplate.toString()); + } + + public void deleteEndpointTemplate(String templateName) throws RemoteException { + endpointTemplateAdminStub.deleteEndpointTemplate(templateName); + } + + public void deleteDynamicEndpointTemplate(String key) throws RemoteException { + endpointTemplateAdminStub.deleteDynamicEndpointTemplate(key); + } + + public int getDynamicEndpointTemplatesCount() throws RemoteException { + return endpointTemplateAdminStub.getDynamicEndpointTemplatesCount(); + } + + public int getEndpointTemplatesCount() throws RemoteException { + return endpointTemplateAdminStub.getEndpointTemplatesCount(); + } + + public String[] getEndpointTemplates() throws RemoteException { + EndpointTemplateInfo[] info = endpointTemplateAdminStub.getEndpointTemplates(0, 200); + if (info == null || info.length == 0) { + return null; + } + String[] templates = new String[info.length]; + int i = 0; + for (EndpointTemplateInfo tmpInfo : info) { + templates[i++] = tmpInfo.getTemplateName(); + } + return templates; + } + +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/template/SequenceTemplateAdminServiceClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/template/SequenceTemplateAdminServiceClient.java new file mode 100644 index 0000000000..81edfdab1d --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/template/SequenceTemplateAdminServiceClient.java @@ -0,0 +1,111 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.template; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.mediation.templates.stub.types.TemplateAdminServiceStub; +import org.wso2.carbon.mediation.templates.stub.types.common.TemplateInfo; + +import javax.activation.DataHandler; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.rmi.RemoteException; + +public class SequenceTemplateAdminServiceClient { + private static final Log log = LogFactory.getLog(SequenceTemplateAdminServiceClient.class); + + private final String serviceName = "TemplateAdminService"; + private TemplateAdminServiceStub templateAdminStub; + + public SequenceTemplateAdminServiceClient(String backEndUrl, String sessionCookie) + throws AxisFault { + String endPoint = backEndUrl + serviceName; + templateAdminStub = new TemplateAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, templateAdminStub); + } + + public SequenceTemplateAdminServiceClient(String backEndUrl, String userName, String password) + throws AxisFault { + String endPoint = backEndUrl + serviceName; + templateAdminStub = new TemplateAdminServiceStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, templateAdminStub); + } + + public void addSequenceTemplate(OMElement template) throws RemoteException { + templateAdminStub.addTemplate(template); + } + + public void addSequenceTemplate(DataHandler dh) throws IOException, XMLStreamException { + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + //create the builder + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement template = builder.getDocumentElement(); + templateAdminStub.addTemplate(template); + } + + public void addDynamicSequenceTemplate(String key, OMElement template) throws RemoteException { + templateAdminStub.addDynamicTemplate(key, template); + } + + public void addDynamicSequenceTemplate(String key, DataHandler dh) + throws IOException, XMLStreamException { + XMLStreamReader parser = + XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); + //create the builder + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement template = builder.getDocumentElement(); + templateAdminStub.addDynamicTemplate(key, template); + } + + public void deleteTemplate(String templateName) throws RemoteException { + templateAdminStub.deleteTemplate(templateName); + } + + public void deleteDynamicTemplate(String key) throws RemoteException { + templateAdminStub.deleteDynamicTemplate(key); + } + + public int getTemplatesCount() throws RemoteException { + return templateAdminStub.getTemplatesCount(); + } + + public int getDynamicTemplateCount() throws RemoteException { + return templateAdminStub.getDynamicTemplateCount(); + } + + public String[] getSequenceTemplates() throws RemoteException { + TemplateInfo[] info = templateAdminStub.getTemplates(0, 200); + if (info == null || info.length == 0) { + return null; + } + String[] templates = new String[info.length]; + int i = 0; + for (TemplateInfo tmpInfo : info) { + templates[i++] = tmpInfo.getName(); + } + return templates; + } +} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/transport/mgt/TransportManagementAdminServiceClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/transport/mgt/TransportManagementAdminServiceClient.java new file mode 100644 index 0000000000..9d3d0289ad --- /dev/null +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/am/admin/clients/transport/mgt/TransportManagementAdminServiceClient.java @@ -0,0 +1,68 @@ +/* +*Copyright (c) 2005-2010, 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.am.admin.clients.transport.mgt; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.am.admin.clients.client.utils.AuthenticateStub; +import org.wso2.carbon.transport.mgt.stub.Exception; +import org.wso2.carbon.transport.mgt.stub.TransportAdminStub; +import org.wso2.carbon.transport.mgt.stub.types.carbon.TransportData; + +import java.rmi.RemoteException; + +public class TransportManagementAdminServiceClient { + private static final Log log = LogFactory.getLog(TransportManagementAdminServiceClient.class); + + private final String serviceName = "TransportAdmin"; + private TransportAdminStub transportAdminStub; + + public TransportManagementAdminServiceClient(String backEndUrl, String sessionCookie) + throws AxisFault { + String endPoint = backEndUrl + serviceName; + transportAdminStub = new TransportAdminStub(endPoint); + AuthenticateStub.authenticateStub(sessionCookie, transportAdminStub); + } + + public TransportManagementAdminServiceClient(String backEndUrl, String userName, + String password) throws AxisFault { + String endPoint = backEndUrl + serviceName; + transportAdminStub = new TransportAdminStub(endPoint); + AuthenticateStub.authenticateStub(userName, password, transportAdminStub); + } + + public TransportData[] getAllTransportData() + throws RemoteException, org.wso2.carbon.transport.mgt.stub.Exception { + return transportAdminStub.getAllTransportData(); + } + + /** + * @param serviceName + * @param transport http or https + * @throws java.rmi.RemoteException + * @throws Exception + */ + public void addExposedTransports(String serviceName, String transport) + throws RemoteException, Exception { + + transportAdminStub.addExposedTransports(serviceName, transport); + } + +} diff --git a/modules/integration/tests-common/admin-clients/target/maven-archiver/pom.properties b/modules/integration/tests-common/admin-clients/target/maven-archiver/pom.properties new file mode 100644 index 0000000000..5e53fb76bb --- /dev/null +++ b/modules/integration/tests-common/admin-clients/target/maven-archiver/pom.properties @@ -0,0 +1,5 @@ +#Generated by Maven +#Mon Jan 26 14:52:32 IST 2015 +version=1.7.0-SNAPSHOT +groupId=org.wso2.am +artifactId=admin-clients diff --git a/modules/integration/tests-common/integration-test-utils/pom.xml b/modules/integration/tests-common/integration-test-utils/pom.xml new file mode 100644 index 0000000000..79d8c9a3c6 --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/pom.xml @@ -0,0 +1,34 @@ + + + + + org.wso2.am + integration-test-common + 1.7.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + integration-test-utils + 1.7.0-SNAPSHOT + jar + WSO2 API Manager - Integration - Tests Common - Integration Test Utils + + + + org.wso2.am + admin-clients + ${project.version} + + + + org.wso2.carbon + org.wso2.carbon.apimgt.api + 1.2.0 + compile + + + + \ No newline at end of file diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/APIManagerIntegrationTest.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/APIManagerIntegrationTest.java new file mode 100644 index 0000000000..40be92937c --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/APIManagerIntegrationTest.java @@ -0,0 +1,936 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.test.utils; + +import org.apache.axiom.attachments.ByteArrayDataSource; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.util.AXIOMUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.Assert; +import org.wso2.am.integration.test.utils.esb.ESBTestCaseUtils; +import org.wso2.am.integration.test.utils.esb.EndpointGenerator; +import org.wso2.am.integration.test.utils.esb.ServiceDeploymentUtil; +import org.wso2.carbon.authenticator.stub.LoginAuthenticationExceptionException; +import org.wso2.carbon.automation.engine.context.AutomationContext; +import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.carbon.automation.engine.context.beans.ContextUrls; +import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil; +import org.wso2.carbon.integration.common.admin.client.SecurityAdminServiceClient; +import org.wso2.carbon.integration.common.utils.LoginLogoutClient; +import org.wso2.carbon.security.mgt.stub.config.SecurityAdminServiceSecurityConfigExceptionException; +import org.wso2.carbon.sequences.stub.types.SequenceEditorException; +import org.xml.sax.SAXException; + +import javax.activation.DataHandler; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.xpath.XPathExpressionException; +import java.io.*; +import java.net.URISyntaxException; +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.regex.Matcher; + +public abstract class APIManagerIntegrationTest { + + protected Log log = LogFactory.getLog(getClass()); + + protected AutomationContext context; + + protected OMElement synapseConfiguration = null; + protected ESBTestCaseUtils esbUtils; + + private List proxyServicesList = null; + private List sequencesList = null; + private List endpointsList = null; + private List localEntryList = null; + private List messageProcessorsList = null; + private List messageStoresList = null; + private List sequenceTemplateList = null; + private List apiList = null; + private List priorityExecutorList = null; + private List scheduledTaskList = null; + + protected TestUserMode userMode; + protected ContextUrls contextUrls; + protected String sessionCookie; + + protected void init() throws Exception { + userMode = TestUserMode.SUPER_TENANT_ADMIN; + init(userMode); + } + + protected void init(TestUserMode userMode) throws Exception { + context = new AutomationContext("AM", userMode); + contextUrls = context.getContextUrls(); + sessionCookie = login(context); + esbUtils = new ESBTestCaseUtils(); + } + + protected void cleanup() throws Exception { + try { + if (synapseConfiguration != null) { + esbUtils.deleteArtifact(synapseConfiguration, contextUrls.getBackEndUrl(), + sessionCookie); + if (context.getProductGroup().isClusterEnabled()) { + + long deploymentDelay = + Long.parseLong(context.getConfigurationValue("//deploymentDelay")); + Thread.sleep(deploymentDelay); + Iterator proxies = + synapseConfiguration.getChildrenWithLocalName("proxy"); + while (proxies.hasNext()) { + String proxy = proxies.next().getAttributeValue(new QName("name")); + + Assert.assertTrue( + isProxyWSDlNotExist(getProxyServiceURLHttp(proxy), deploymentDelay) + , "UnDeployment Synchronizing failed in workers"); + Assert.assertTrue( + isProxyWSDlNotExist(getProxyServiceURLHttp(proxy), deploymentDelay) + , "UnDeployment Synchronizing failed in workers"); + Assert.assertTrue( + isProxyWSDlNotExist(getProxyServiceURLHttp(proxy), deploymentDelay) + , "UnDeployment Synchronizing failed in workers"); + } + } + } + + deleteProxyServices(); + + deleteSequences(); + + deleteEndpoints(); + + deleteMessageProcessors(); + + deleteMessageStores(); + + deleteSequenceTemplates(); + + deleteLocalEntries(); + + deleteApi(); + + deletePriorityExecutors(); + + deleteScheduledTasks(); + + } finally { + synapseConfiguration = null; + proxyServicesList = null; + messageProcessorsList = null; + proxyServicesList = null; + sequencesList = null; + endpointsList = null; + localEntryList = null; + apiList = null; + priorityExecutorList = null; + esbUtils = null; + scheduledTaskList = null; + + } + } + + protected String getMainSequenceURL() { + String mainSequenceUrl = contextUrls.getServiceUrl(); + if (mainSequenceUrl.endsWith("/services")) { + mainSequenceUrl = mainSequenceUrl.replace("/services", ""); + } + if (!mainSequenceUrl.endsWith("/")) { + mainSequenceUrl = mainSequenceUrl + "/"; + } + return mainSequenceUrl; + + } + + protected String getMainSequenceURLHttps() { + String mainSequenceUrl = contextUrls.getSecureServiceUrl(); + if (mainSequenceUrl.endsWith("/services")) { + mainSequenceUrl = mainSequenceUrl.replace("/services", ""); + } + if (!mainSequenceUrl.endsWith("/")) { + mainSequenceUrl = mainSequenceUrl + "/"; + } + return mainSequenceUrl; + + } + + protected String getApiInvocationURLHttp(String apiContext) throws XPathExpressionException { + if (isBuilderEnabled()) { + return getMainSequenceURL() + apiContext; + } else { + return getGatewayServerURLHttp() + apiContext; + } + } + + protected String getApiInvocationURLHttps(String apiContext) throws XPathExpressionException { + if (isBuilderEnabled()) { + return getMainSequenceURLHttps() + apiContext; + } else { + return getGatewayServerURLHttps() + apiContext; + } + } + + protected String getProxyServiceURLHttp(String proxyServiceName) { + return contextUrls.getServiceUrl() + "/" + proxyServiceName; + } + + protected String getProxyServiceURLHttps(String proxyServiceName) { + return contextUrls.getSecureServiceUrl() + "/" + proxyServiceName; + } + + protected String getServerURLHttp() throws XPathExpressionException { + return getServerBackendUrlHttp(); + } + + protected String getServerURLHttps() { + String serverUrl = contextUrls.getBackEndUrl(); + if (serverUrl.endsWith("/services")) { + serverUrl = serverUrl.replace("/services", ""); + } + if (serverUrl.endsWith("/")) { + serverUrl = serverUrl.substring(0, (serverUrl.length() - 1)); + } + return serverUrl; + } + + private String getServerBackendUrlHttp() throws XPathExpressionException { + String httpPort = context.getInstance().getPorts().get("http"); + String hostName = context.getInstance().getHosts().get("default"); + + String url = "http://" + hostName; + if (httpPort != null) { + url = url + ":" + httpPort; + } + return url; + } + + protected String login(AutomationContext context) + throws IOException, XPathExpressionException, URISyntaxException, SAXException, + XMLStreamException, LoginAuthenticationExceptionException { + LoginLogoutClient loginLogoutClient = new LoginLogoutClient(context); + return loginLogoutClient.login(); + } + + protected boolean isRunningOnStratos() throws XPathExpressionException { + return context.getConfigurationValue("//executionEnvironment").equals("platform"); + } + + protected String getAMResourceLocation() { + return FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + + File.separator + "AM"; + } + + protected String getBackEndServiceUrl(String serviceName) throws XPathExpressionException { + return EndpointGenerator.getBackEndServiceEndpointUrl(serviceName); + } + + protected boolean isBuilderEnabled() throws XPathExpressionException { + return context.getConfigurationValue("//executionEnvironment").equals("standalone"); + } + + protected boolean isClusterEnabled() throws XPathExpressionException { + return context.getProductGroup().isClusterEnabled(); + } + + protected String getExecutionEnvironment() throws XPathExpressionException { + return context.getConfigurationValue("//executionEnvironment"); + } + + protected void loadSampleESBConfiguration(int sampleNo) throws Exception { + OMElement synapseSample = esbUtils.loadESBSampleConfiguration(sampleNo); + updateESBConfiguration(synapseSample); + + } + + protected void loadESBConfigurationFromClasspath(String relativeFilePath) throws Exception { + relativeFilePath = relativeFilePath.replaceAll("[\\\\/]", Matcher + .quoteReplacement(File.separator)); + + OMElement synapseConfig = esbUtils.loadResource(relativeFilePath); + updateESBConfiguration(synapseConfig); + + } + + protected void loadESBConfigurationFromFileHierarchy(String dirPath) throws Exception { + + String initialPath = dirPath; + dirPath = dirPath.replaceAll("[\\\\/]", Matcher.quoteReplacement(File.separator)); + + String resourcePath = FrameworkPathUtil.getSystemResourceLocation(); + + if (resourcePath.endsWith("resources/")) { + resourcePath = resourcePath.replace("resources/", "resources"); + } + + dirPath = resourcePath + dirPath; + + File dir = new File(dirPath); + + if (dir.isDirectory()) { + + // load synapse config + OMElement synapseConfig = esbUtils.loadResource(initialPath + "/synapse.xml"); + updateESBConfiguration(synapseConfig); + + File[] files = new File(dirPath).listFiles(); + + for (File file : files) { + if (file.isDirectory()) { + + if (file.getName().equalsIgnoreCase("proxy-services")) { + File[] proxies = new File(file.getPath()).listFiles(); + + for (File proxyFile : proxies) { + synapseConfig = esbUtils.loadResource(initialPath + File.separator + + file.getName() + File.separator + + proxyFile.getName()); + addProxyService(synapseConfig); + } + } else if (file.getName().equalsIgnoreCase("endpoints")) { + File[] endpoints = new File(file.getPath()).listFiles(); + + for (File endpoint : endpoints) { + synapseConfig = esbUtils.loadResource(initialPath + File.separator + + file.getName() + File.separator + + endpoint.getName()); + addEndpoint(synapseConfig); + } + } else if (file.getName().equalsIgnoreCase("local-entries")) { + File[] localentries = new File(file.getPath()).listFiles(); + + for (File localentry : localentries) { + synapseConfig = esbUtils.loadResource(initialPath + File.separator + + file.getName() + File.separator + + localentry.getName()); + addLocalEntry(synapseConfig); + } + } else if (file.getName().equalsIgnoreCase("sequences")) { + File[] sequences = new File(file.getPath()).listFiles(); + + for (File sequence : sequences) { + synapseConfig = esbUtils.loadResource(initialPath + File.separator + + file.getName() + File.separator + + sequence.getName()); + addSequence(synapseConfig); + } + } else if (file.getName().equalsIgnoreCase("tasks")) { + File[] tasks = new File(file.getPath()).listFiles(); + + for (File task : tasks) { + synapseConfig = esbUtils.loadResource(initialPath + File.separator + + file.getName() + File.separator + + task.getName()); + addScheduledTask(synapseConfig); + } + } + } + } + } + } + + protected void updateESBConfiguration(OMElement synapseConfig) throws Exception { + + if (synapseConfiguration == null) { + synapseConfiguration = synapseConfig; + } else { + Iterator itr = synapseConfig.cloneOMElement().getChildElements(); + while (itr.hasNext()) { + synapseConfiguration.addChild(itr.next()); + } + } + esbUtils.updateESBConfiguration(setEndpoints(synapseConfig), contextUrls.getBackEndUrl(), + sessionCookie); + + if (context.getProductGroup().isClusterEnabled()) { + long deploymentDelay = + Long.parseLong(context.getConfigurationValue("//deploymentDelay")); + Thread.sleep(deploymentDelay); + Iterator proxies = synapseConfig.getChildrenWithLocalName("proxy"); + while (proxies.hasNext()) { + String proxy = proxies.next().getAttributeValue(new QName("name")); + + Assert.assertTrue(isProxyWSDlExist(getProxyServiceURLHttp(proxy), deploymentDelay) + , "Deployment Synchronizing failed in workers"); + Assert.assertTrue(isProxyWSDlExist(getProxyServiceURLHttp(proxy), deploymentDelay) + , "Deployment Synchronizing failed in workers"); + Assert.assertTrue(isProxyWSDlExist(getProxyServiceURLHttp(proxy), deploymentDelay) + , "Deployment Synchronizing failed in workers"); + } + } + } + + protected void addProxyService(OMElement proxyConfig) throws Exception { + String proxyName = proxyConfig.getAttributeValue(new QName("name")); + if (esbUtils.isProxyServiceExist(contextUrls.getBackEndUrl(), sessionCookie, proxyName)) { + esbUtils.deleteProxyService(contextUrls.getBackEndUrl(), sessionCookie, proxyName); + } + if (proxyServicesList == null) { + proxyServicesList = new ArrayList(); + } + proxyServicesList.add(proxyName); + esbUtils.addProxyService(contextUrls.getBackEndUrl(), sessionCookie, + setEndpoints(proxyConfig)); + + /* if (ExecutionEnvironment.stratos.name().equalsIgnoreCase(getExecutionEnvironment())) { + long deploymentDelay = FrameworkFactory.getFrameworkProperties( + ProductConstant.ESB_SERVER_NAME).getEnvironmentVariables().getDeploymentDelay(); + + Assert.assertTrue(isProxyWSDlExist(getProxyServiceURL(proxyName), deploymentDelay) + , "Deployment Synchronizing failed in workers"); + Assert.assertTrue(isProxyWSDlExist(getProxyServiceURL(proxyName), deploymentDelay) + , "Deployment Synchronizing failed in workers"); + Assert.assertTrue(isProxyWSDlExist(getProxyServiceURL(proxyName), deploymentDelay) + , "Deployment Synchronizing failed in workers"); + + }*/ + } + + protected void isProxyDeployed(String proxyServiceName) throws Exception { + Assert.assertTrue(esbUtils.isProxyDeployed(contextUrls.getBackEndUrl(), sessionCookie, + proxyServiceName), + "Proxy Deployment failed or time out"); + } + + protected void deleteProxyService(String proxyServiceName) throws Exception { + if (esbUtils.isProxyServiceExist(contextUrls.getBackEndUrl(), sessionCookie, + proxyServiceName)) { + esbUtils.deleteProxyService(contextUrls.getBackEndUrl(), sessionCookie, + proxyServiceName); + Assert.assertTrue(esbUtils.isProxyUnDeployed(contextUrls.getBackEndUrl(), sessionCookie, + proxyServiceName), + "Proxy Deletion failed or time out"); + } + if (proxyServicesList != null && proxyServicesList.contains(proxyServiceName)) { + proxyServicesList.remove(proxyServiceName); + } + } + + protected void deleteSequence(String sequenceName) + throws SequenceEditorException, RemoteException { + if (esbUtils.isSequenceExist(contextUrls.getBackEndUrl(), sessionCookie, sequenceName)) { + esbUtils.deleteSequence(contextUrls.getBackEndUrl(), sessionCookie, sequenceName); + } + if (sequencesList != null && sequencesList.contains(sequenceName)) { + sequencesList.remove(sequenceName); + } + } + + protected void addSequence(OMElement sequenceConfig) throws Exception { + String sequenceName = sequenceConfig.getAttributeValue(new QName("name")); + if (esbUtils.isSequenceExist(contextUrls.getBackEndUrl(), sessionCookie, sequenceName)) { + esbUtils.deleteSequence(contextUrls.getBackEndUrl(), sessionCookie, sequenceName); + } + esbUtils.addSequence(contextUrls.getBackEndUrl(), sessionCookie, + setEndpoints(sequenceConfig)); + if (sequencesList == null) { + sequencesList = new ArrayList(); + } + sequencesList.add(sequenceName); + } + + protected void addEndpoint(OMElement endpointConfig) + throws Exception { + String endpointName = endpointConfig.getAttributeValue(new QName("name")); + if (esbUtils.isSequenceExist(contextUrls.getBackEndUrl(), sessionCookie, endpointName)) { + esbUtils.deleteEndpoint(contextUrls.getBackEndUrl(), sessionCookie, endpointName); + } + esbUtils.addEndpoint(contextUrls.getBackEndUrl(), sessionCookie, + setEndpoints(endpointConfig)); + if (endpointsList == null) { + endpointsList = new ArrayList(); + } + endpointsList.add(endpointName); + + } + + protected void addLocalEntry(OMElement localEntryConfig) throws Exception { + String localEntryName = localEntryConfig.getAttributeValue(new QName("key")); + if (esbUtils + .isLocalEntryExist(contextUrls.getBackEndUrl(), sessionCookie, localEntryName)) { + esbUtils.deleteLocalEntry(contextUrls.getBackEndUrl(), sessionCookie, localEntryName); + } + esbUtils.addLocalEntry(contextUrls.getBackEndUrl(), sessionCookie, localEntryConfig); + + if (localEntryList == null) { + localEntryList = new ArrayList(); + } + localEntryList.add(localEntryName); + } + + protected void addMessageProcessor(OMElement messageProcessorConfig) throws Exception { + String messageProcessorName = messageProcessorConfig.getAttributeValue(new QName("name")); + if (esbUtils.isMessageProcessorExist(contextUrls.getBackEndUrl(), sessionCookie, + messageProcessorName)) { + esbUtils.deleteMessageProcessor(contextUrls.getBackEndUrl(), sessionCookie, + messageProcessorName); + } + esbUtils.addMessageProcessor(contextUrls.getBackEndUrl(), sessionCookie, + setEndpoints(messageProcessorConfig)); + if (messageProcessorsList == null) { + messageProcessorsList = new ArrayList(); + } + messageProcessorsList.add(messageProcessorName); + } + + protected void addMessageStore(OMElement messageStoreConfig) throws Exception { + String messageStoreName = messageStoreConfig.getAttributeValue(new QName("name")); + if (esbUtils.isMessageStoreExist(contextUrls.getBackEndUrl(), sessionCookie, + messageStoreName)) { + esbUtils.deleteMessageStore(contextUrls.getBackEndUrl(), sessionCookie, + messageStoreName); + } + esbUtils.addMessageStore(contextUrls.getBackEndUrl(), sessionCookie, + setEndpoints(messageStoreConfig)); + if (messageStoresList == null) { + messageStoresList = new ArrayList(); + } + messageStoresList.add(messageStoreName); + } + + protected void addSequenceTemplate(OMElement sequenceTemplate) throws Exception { + String name = sequenceTemplate.getAttributeValue(new QName("name")); + if (esbUtils.isSequenceTemplateExist(contextUrls.getBackEndUrl(), sessionCookie, name)) { + esbUtils.deleteSequenceTemplate(contextUrls.getBackEndUrl(), sessionCookie, name); + } + esbUtils.addSequenceTemplate(contextUrls.getBackEndUrl(), sessionCookie, + setEndpoints(sequenceTemplate)); + + if (sequenceTemplateList == null) { + sequenceTemplateList = new ArrayList(); + } + sequenceTemplateList.add(name); + } + + protected void addApi(OMElement api) throws Exception { + String apiName = api.getAttributeValue(new QName("name")); + if (esbUtils.isApiExist(contextUrls.getBackEndUrl(), sessionCookie, apiName)) { + esbUtils.deleteApi(contextUrls.getBackEndUrl(), sessionCookie, apiName); + } + esbUtils.addAPI(contextUrls.getBackEndUrl(), sessionCookie, api); + + if (apiList == null) { + apiList = new ArrayList(); + } + apiList.add(apiName); + } + + protected void addPriorityExecutor(OMElement priorityExecutor) throws Exception { + String executorName = priorityExecutor.getAttributeValue(new QName("name")); + if (esbUtils.isPriorityExecutorExist(contextUrls.getBackEndUrl(), sessionCookie, + executorName)) { + esbUtils.deletePriorityExecutor(contextUrls.getBackEndUrl(), sessionCookie, + executorName); + } + esbUtils.addPriorityExecutor(contextUrls.getBackEndUrl(), sessionCookie, priorityExecutor); + + if (priorityExecutorList == null) { + priorityExecutorList = new ArrayList(); + } + priorityExecutorList.add(executorName); + } + + protected void addScheduledTask(OMElement task) throws Exception { + String taskName = task.getAttributeValue(new QName("name")); + String taskGroup = task.getAttributeValue(new QName("group")); + if (esbUtils.isScheduleTaskExist(contextUrls.getBackEndUrl(), sessionCookie, taskName)) { + esbUtils.deleteScheduleTask(contextUrls.getBackEndUrl(), sessionCookie, taskName, + taskGroup); + } + esbUtils.addScheduleTask(contextUrls.getBackEndUrl(), sessionCookie, task); + + if (scheduledTaskList == null) { + scheduledTaskList = new ArrayList(); + } + scheduledTaskList.add(new String[] { taskName, taskGroup }); + } + + protected void applySecurity(String serviceName, int policyId, String[] userGroups) + throws SecurityAdminServiceSecurityConfigExceptionException, RemoteException, + InterruptedException { + SecurityAdminServiceClient securityAdminServiceClient = + new SecurityAdminServiceClient(contextUrls.getBackEndUrl(), sessionCookie); + // if (FrameworkFactory.getFrameworkProperties(ProductConstant.ESB_SERVER_NAME).getEnvironmentSettings().is_runningOnStratos()) { + + // securityAdminServiceClient.applySecurity(serviceName, policyId + "", userGroups, + // new String[]{"service.jks"}, "service.jks"); + // } else { + securityAdminServiceClient.applySecurity(serviceName, policyId + "", userGroups, + new String[] { "wso2carbon.jks" }, + "wso2carbon.jks"); + // } + log.info("Security Scenario " + policyId + " Applied"); + + Thread.sleep(1000); + + } + + protected void applySecurity(String serviceName, String policyPath, String[] userGroups) + throws SecurityAdminServiceSecurityConfigExceptionException, RemoteException, + InterruptedException { + + /*SecurityAdminServiceClient securityAdminServiceClient = + new SecurityAdminServiceClient(contextUrls.getBackEndUrl(), sessionCookie); + securityAdminServiceClient.applySecurity(serviceName, policyPath, + new String[] { "wso2carbon.jks" }, + "wso2carbon.jks", userGroups); + + log.info("Security Scenario " + policyPath + " Applied"); + + Thread.sleep(1000);*/ + + } + + private void deleteMessageProcessors() { + if (messageProcessorsList != null) { + Iterator itr = messageProcessorsList.iterator(); + while (itr.hasNext()) { + String messageProcessor = itr.next(); + try { + if (esbUtils.isMessageProcessorExist(contextUrls.getBackEndUrl(), sessionCookie, + messageProcessor)) { + esbUtils.deleteMessageProcessor(contextUrls.getBackEndUrl(), sessionCookie, + messageProcessor); + } + } catch (Exception e) { + Assert.fail("while undeploying Message Processor. " + e.getMessage()); + } + } + messageProcessorsList.clear(); + } + } + + private void deleteMessageStores() { + if (messageStoresList != null) { + Iterator itr = messageStoresList.iterator(); + while (itr.hasNext()) { + String messageStore = itr.next(); + try { + if (esbUtils.isMessageStoreExist(contextUrls.getBackEndUrl(), sessionCookie, + messageStore)) { + esbUtils.deleteMessageStore(contextUrls.getBackEndUrl(), sessionCookie, + messageStore); + } + } catch (Exception e) { + Assert.fail("while undeploying Message store. " + e.getMessage()); + } + } + messageStoresList.clear(); + } + } + + private void deleteSequences() { + if (sequencesList != null) { + Iterator itr = sequencesList.iterator(); + while (itr.hasNext()) { + String sequence = itr.next(); + if (!sequence.equalsIgnoreCase("fault")) { + try { + if (esbUtils.isSequenceExist(contextUrls.getBackEndUrl(), sessionCookie, + sequence)) { + esbUtils.deleteSequence(contextUrls.getBackEndUrl(), sessionCookie, + sequence); + } + } catch (Exception e) { + Assert.fail("while undeploying Sequence. " + e.getMessage()); + } + } + } + sequencesList.clear(); + } + } + + private void deleteProxyServices() { + if (proxyServicesList != null) { + Iterator itr = proxyServicesList.iterator(); + while (itr.hasNext()) { + String proxyName = itr.next(); + try { + if (esbUtils.isProxyServiceExist(contextUrls.getBackEndUrl(), sessionCookie, + proxyName)) { + esbUtils.deleteProxyService(contextUrls.getBackEndUrl(), sessionCookie, + proxyName); + + /* if (ExecutionEnvironment.stratos.name().equalsIgnoreCase(getExecutionEnvironment())) { + long deploymentDelay = FrameworkFactory.getFrameworkProperties( + ProductConstant.ESB_SERVER_NAME).getEnvironmentVariables().getDeploymentDelay(); + + Assert.assertTrue(isProxyWSDlNotExist(getProxyServiceURL(proxyName), deploymentDelay) + , "Proxy UnDeployment Synchronizing failed in workers"); + Assert.assertTrue(isProxyWSDlNotExist(getProxyServiceURL(proxyName), deploymentDelay) + , "Proxy UnDeployment Synchronizing failed in workers"); + Assert.assertTrue(isProxyWSDlNotExist(getProxyServiceURL(proxyName), deploymentDelay) + , "Proxy UnDeployment Synchronizing failed in workers"); + + }*/ + } + } catch (Exception e) { + Assert.fail("while undeploying Proxy. " + e.getMessage()); + } + } + proxyServicesList.clear(); + } + } + + private void deleteEndpoints() { + if (endpointsList != null) { + Iterator itr = endpointsList.iterator(); + while (itr.hasNext()) { + String endpoint = itr.next(); + try { + if (esbUtils.isEndpointExist(contextUrls.getBackEndUrl(), sessionCookie, + endpoint)) { + esbUtils.deleteEndpoint(contextUrls.getBackEndUrl(), sessionCookie, + endpoint); + } + } catch (Exception e) { + Assert.fail("while undeploying Endpoint. " + e.getMessage()); + } + } + endpointsList.clear(); + } + } + + private void deleteLocalEntries() { + if (localEntryList != null) { + Iterator itr = localEntryList.iterator(); + while (itr.hasNext()) { + String localEntry = itr.next(); + try { + if (esbUtils.isLocalEntryExist(contextUrls.getBackEndUrl(), sessionCookie, + localEntry)) { + esbUtils.deleteLocalEntry(contextUrls.getBackEndUrl(), sessionCookie, + localEntry); + } + } catch (Exception e) { + Assert.fail("while undeploying LocalEntry. " + e.getMessage()); + } + } + localEntryList.clear(); + } + } + + private void deleteSequenceTemplates() { + if (sequenceTemplateList != null) { + Iterator itr = sequenceTemplateList.iterator(); + while (itr.hasNext()) { + String localEntry = itr.next(); + try { + if (esbUtils.isSequenceTemplateExist(contextUrls.getBackEndUrl(), sessionCookie, + localEntry)) { + esbUtils.deleteSequenceTemplate(contextUrls.getBackEndUrl(), sessionCookie, + localEntry); + } + } catch (Exception e) { + Assert.fail("while undeploying Sequence Template. " + e.getMessage()); + } + } + sequenceTemplateList.clear(); + } + } + + private void deleteApi() { + if (apiList != null) { + Iterator itr = apiList.iterator(); + while (itr.hasNext()) { + String api = itr.next(); + try { + if (esbUtils.isApiExist(contextUrls.getBackEndUrl(), sessionCookie, api)) { + esbUtils.deleteApi(contextUrls.getBackEndUrl(), sessionCookie, api); + } + } catch (Exception e) { + Assert.fail("while undeploying Api. " + e.getMessage()); + } + } + apiList.clear(); + } + } + + private void deletePriorityExecutors() { + if (priorityExecutorList != null) { + Iterator itr = priorityExecutorList.iterator(); + while (itr.hasNext()) { + String executor = itr.next(); + try { + if (esbUtils.isPriorityExecutorExist(contextUrls.getBackEndUrl(), sessionCookie, + executor)) { + esbUtils.deleteProxyService(contextUrls.getBackEndUrl(), sessionCookie, + executor); + } + } catch (Exception e) { + Assert.fail("while undeploying Priority Executor. " + e.getMessage()); + } + } + priorityExecutorList.clear(); + } + } + + private void deleteScheduledTasks() { + if (scheduledTaskList != null) { + Iterator itr = scheduledTaskList.iterator(); + while (itr.hasNext()) { + String[] executor = itr.next(); + try { + if (esbUtils.isScheduleTaskExist(contextUrls.getBackEndUrl(), sessionCookie, + executor[0])) { + esbUtils.deleteScheduleTask(contextUrls.getBackEndUrl(), sessionCookie, + executor[0], executor[1]); + } + } catch (Exception e) { + Assert.fail("while undeploying ScheduledTask Executor. " + e.getMessage()); + } + } + scheduledTaskList.clear(); + } + } + + protected OMElement setEndpoints(OMElement synapseConfig) + throws XMLStreamException, XPathExpressionException { + if (isBuilderEnabled()) { + return synapseConfig; + } + String config = replaceEndpoints(synapseConfig.toString()); + return AXIOMUtil.stringToOM(config); + } + + protected DataHandler setEndpoints(DataHandler dataHandler) + throws XMLStreamException, IOException, XPathExpressionException { + if (isBuilderEnabled()) { + return dataHandler; + } + String config = readInputStreamAsString(dataHandler.getInputStream()); + config = replaceEndpoints(config); + ByteArrayDataSource dbs = new ByteArrayDataSource(config.getBytes()); + return new DataHandler(dbs); + } + + private String replaceEndpoints(String config) throws XPathExpressionException { + //this should be AS context + String serviceUrl = + new AutomationContext("AS", TestUserMode.SUPER_TENANT_ADMIN).getContextUrls() + .getServiceUrl(); + + config = config.replace("http://localhost:9000/services/" + , serviceUrl); + config = config.replace("http://127.0.0.1:9000/services/" + , serviceUrl); + return config; + } + + protected OMElement replaceEndpoints(String relativePathToConfigFile, String serviceName, + String port) + throws XMLStreamException, FileNotFoundException, XPathExpressionException { + String config = esbUtils.loadResource(relativePathToConfigFile).toString(); + config = config.replace("http://localhost:" + port + "/services/" + serviceName, + getBackEndServiceUrl(serviceName)); + + return AXIOMUtil.stringToOM(config); + } + + private boolean isProxyWSDlExist(String serviceUrl, long synchronizingDelay) + throws Exception { + return new ServiceDeploymentUtil().isServiceWSDlExist(serviceUrl, synchronizingDelay); + + } + + private boolean isProxyWSDlNotExist(String serviceUrl, long synchronizingDelay) + throws Exception { + + return new ServiceDeploymentUtil().isServiceWSDlNotExist(serviceUrl, synchronizingDelay); + + } + + protected String getSessionCookie() { + return sessionCookie; + } + + //todo - getting role as the user + protected String[] getUserRole() { + return new String[] { "admin" }; + } + + private String readInputStreamAsString(InputStream in) + throws IOException { + + BufferedInputStream bis = new BufferedInputStream(in); + ByteArrayOutputStream buf = new ByteArrayOutputStream(); + int result = bis.read(); + while (result != -1) { + byte b = (byte) result; + buf.write(b); + result = bis.read(); + } + return buf.toString(); + } + + + + // todo: Need to implement the following urls for clustered setup + /* + am.distributed.store.http.url=http://localhost:9763 +am.distributed.store.https.url=https://localhost:9443 +am.distributed.publisher.http.url=http://localhost:9763 +am.distributed.publisher.https.url=https://localhost:9443 +am.distributed.gateway.http.url=http://localhost:8280/ +am.distributed.gateway.https.url=https://localhost:8243/ +am.test.application.usage.http.url=http://localhost:9763/testapp/testUsageWithBAM.jag +am.test.application.store.http.url=http://localhost:9763/testapp/testStore.jag +am.test.application.publisher.http.url=http://localhost:9763/testapp/testPublisher.jag + */ + + protected String getStoreServerURLHttp() { + return "http://localhost:9763"; + } + + protected String getStoreServerURLHttps() { + return "https://localhost:9443"; + } + + protected String getPublisherServerURLHttp() { + return "http://localhost:9763"; + } + + protected String getPublisherServerURLHttps() { + return "https://localhost:9443"; + } + + protected String getGatewayServerURLHttp() { + return "http://localhost:8280/"; + } + + protected String getGatewayServerURLHttps() { + return "https://localhost:8243/"; + } + + protected String getTestApplicationUsagePublisherServerURLHttp() { + return "http://localhost:9763/testapp/testUsageWithBAM.jag"; + } + + protected String getTestApplicationStoreServerURLHttp() { + return "http://localhost:9763/testapp/testStore.jag"; + } + + protected String getTestApplicationPublisherServerURLHttp() { + return "http://localhost:9763/testapp/testPublisher.jag"; + } + +} diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/APIMgtTestUtil.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/APIMgtTestUtil.java new file mode 100644 index 0000000000..3ecb770a8b --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/APIMgtTestUtil.java @@ -0,0 +1,146 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.test.utils; + +import org.apache.commons.codec.binary.Base64; +import org.json.JSONException; +import org.json.JSONObject; +import org.wso2.am.integration.test.utils.bean.APIBean; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; +import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; + +import javax.xml.xpath.XPathExpressionException; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.regex.Pattern; + +public class APIMgtTestUtil { + + public static APIBean getAPIBeanFromHttpResponse(HttpResponse httpResponse) { + JSONObject jsonObject = null; + String APIName = null; + String APIProvider = null; + String APIVersion = null; + APIBean apiBean = null; + try { + jsonObject = new JSONObject(httpResponse.getData()); + APIName = ((JSONObject) jsonObject.get("api")).getString("name"); + APIVersion = ((JSONObject) jsonObject.get("api")).getString("version"); + APIProvider = ((JSONObject) jsonObject.get("api")).getString("provider"); + APIIdentifier identifier = new APIIdentifier(APIProvider, APIName, APIVersion); + apiBean = new APIBean(identifier); + apiBean.setContext(((JSONObject) jsonObject.get("api")).getString("context")); + apiBean.setDescription(((JSONObject) jsonObject.get("api")).getString("description")); + apiBean.setWsdlUrl(((JSONObject) jsonObject.get("api")).getString("wsdl")); + apiBean.setTags(((JSONObject) jsonObject.get("api")).getString("tags")); + apiBean.setAvailableTiers( + ((JSONObject) jsonObject.get("api")).getString("availableTiers")); + apiBean.setThumbnailUrl(((JSONObject) jsonObject.get("api")).getString("thumb")); + apiBean.setSandboxUrl(((JSONObject) jsonObject.get("api")).getString("sandbox")); + apiBean.setBusinessOwner(((JSONObject) jsonObject.get("api")).getString("bizOwner")); + apiBean.setBusinessOwnerEmail( + ((JSONObject) jsonObject.get("api")).getString("bizOwnerMail")); + apiBean.setTechnicalOwner(((JSONObject) jsonObject.get("api")).getString("techOwner")); + apiBean.setTechnicalOwnerEmail( + ((JSONObject) jsonObject.get("api")).getString("techOwnerMail")); + apiBean.setWadlUrl(((JSONObject) jsonObject.get("api")).getString("wadl")); + apiBean.setVisibility(((JSONObject) jsonObject.get("api")).getString("visibility")); + apiBean.setVisibleRoles(((JSONObject) jsonObject.get("api")).getString("roles")); + apiBean.setEndpointUTUsername( + ((JSONObject) jsonObject.get("api")).getString("epUsername")); + apiBean.setEndpointUTPassword( + ((JSONObject) jsonObject.get("api")).getString("epPassword")); + apiBean.setEndpointSecured((Boolean.getBoolean( + ((JSONObject) jsonObject.get("api")).getString("endpointTypeSecured")))); + apiBean.setTransports(((JSONObject) jsonObject.get("api")).getString("transport_http")); + apiBean.setTransports( + ((JSONObject) jsonObject.get("api")).getString("transport_https")); + apiBean.setInSequence(((JSONObject) jsonObject.get("api")).getString("inSequence")); + apiBean.setOutSequence(((JSONObject) jsonObject.get("api")).getString("outSequence")); + apiBean.setAvailableTiers( + ((JSONObject) jsonObject.get("api")).getString("availableTiersDisplayNames")); + //-----------Here are some of unused properties, if we need to use them add params to APIBean class + //((JSONObject) jsonObject.get("api")).getString("name"); + //((JSONObject) jsonObject.get("api")).getString("endpoint"); + //((JSONObject) jsonObject.get("api")).getString("subscriptionAvailability"); + //((JSONObject) jsonObject.get("api")).getString("subscriptionTenants"); + //((JSONObject) jsonObject.get("api")).getString("endpointConfig"); + //((JSONObject) jsonObject.get("api")).getString("responseCache"); + //(((JSONObject) jsonObject.get("api")).getString("cacheTimeout"); + //((JSONObject) jsonObject.get("api")).getString("endpointConfig"); + //((JSONObject) jsonObject.get("api")).getString("version"); + //((JSONObject) jsonObject.get("api")).getString("apiStores"); + // ((JSONObject) jsonObject.get("api")).getString("provider"); + //)((JSONObject) jsonObject.get("api")).getString("tierDescs"); + //((JSONObject) jsonObject.get("api")).getString("subs"); + //((JSONObject) jsonObject.get("api")).getString("context"); + // apiBean.setLastUpdated(Date.parse((JSONObject); jsonObject.get("api")).getString("lastUpdated"))); + // apiBean.setUriTemplates((JSONObject) jsonObject.get("api")).getString("templates")); + } catch (JSONException e) { + e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } + return apiBean; + } + + public static void sendGetRequest(String url, String accessToken) throws XPathExpressionException, IOException { + HttpResponse httpResponse; + + URL urlAPI = new URL(url); + HttpURLConnection conn = (HttpURLConnection) urlAPI.openConnection(); + conn.setRequestMethod("GET"); + conn.setDoOutput(true); + conn.setReadTimeout(10000); + //setting headers + + conn.setRequestProperty("Authorization", "Bearer " + accessToken); + + conn.connect(); + // Get the response + StringBuilder sb = new StringBuilder(); + BufferedReader rd = null; + try { + rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line; + while ((line = rd.readLine()) != null) { + sb.append(line); + } + httpResponse = new HttpResponse(sb.toString(), conn.getResponseCode()); + httpResponse.setResponseMessage(conn.getResponseMessage()); + } catch (IOException ignored) { + + } finally { + if (rd != null) { + rd.close(); + } + } + } + + + public static String getDecodedJWT(String serverMessage) { + String[] headerArray = serverMessage.split("\n"); + String[] jwtEncodedArray = headerArray[1].trim().split(":"); + String[] jwtTokenArray = jwtEncodedArray[1].split(Pattern.quote(".")); + + byte[] jwtByteArray = Base64.decodeBase64(jwtTokenArray[1].getBytes()); + return new String(jwtByteArray); + } +} diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/WireMonitor.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/WireMonitor.java new file mode 100644 index 0000000000..dcc3bf67e5 --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/WireMonitor.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2005-2010, 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.am.integration.test.utils; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; + +class WireMonitor extends Thread { + private Log log = LogFactory.getLog(WireMonitor.class); + private static final int TIMEOUT_VALUE = 60000; + private int port; + private ServerSocket providerSocket; + private Socket connection = null; + public String message = ""; + private WireMonitorServer trigger; + + public void run() { + try { + + // creating a server socket + providerSocket = new ServerSocket(port, 10); + + log.info("Waiting for connection"); + connection = providerSocket.accept(); + log.info("Connection received from " + + connection.getInetAddress().getHostName()); + InputStreamReader in = new InputStreamReader(connection.getInputStream()); + BufferedReader rd = + new BufferedReader(new InputStreamReader(connection.getInputStream())); + String line = ""; + Long time = System.currentTimeMillis(); + while ((line = rd.readLine()) != null && !line.equals("")) { + message = message + line; + // In this case no need of reading more than timeout value + if (System.currentTimeMillis() > (time + TIMEOUT_VALUE)) { + break; + } + } + + // Signaling Main thread to continue + trigger.response = message; + trigger.isFinished = true; + + //Sending default response + PrintWriter out = new PrintWriter(connection.getOutputStream()); + String responseText = "[Response] Request Received. This is the default Response."; + String httpResponse = "HTTP/1.1 200 OK\n" + + "Content-Type: text/xml;charset=utf-8\n" + + "Content-Length: " + responseText.length() + "\n" + + "\n" + + responseText; + out.write(httpResponse); + out.flush(); + + in.close(); + rd.close(); + out.close(); + + } catch (IOException ioException) { + ioException.printStackTrace(); + } finally { + try { + connection.close(); + providerSocket.close(); + } catch (Exception e) { + + } + } + + } + + public WireMonitor(int listenPort, WireMonitorServer trigger) { + port = listenPort; + this.trigger = trigger; + } + +} diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/WireMonitorServer.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/WireMonitorServer.java new file mode 100644 index 0000000000..a83bd4dddc --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/WireMonitorServer.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2005-2010, 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.am.integration.test.utils; + +/** + * This class can be used to capture wire messages + */ +public class WireMonitorServer { + private static final int TIMEOUT_VALUE = 60000; + boolean isFinished = false; + String response; + int port; + + /** + * Start listening to a port + * + * @param port to be listened + */ + public WireMonitorServer(int port) { + this.port = port; + } + + public void start() { + response = ""; + isFinished = false; + Thread thread = new WireMonitor(port, this); + thread.start(); + } + + /** + * Wait until response is received and returns + * + * @return will return null if response is not received + */ + public String getCapturedMessage() { + Long time = System.currentTimeMillis(); + while (!isFinished) { + // If wire monitor is not responding than 2min this will continue + if (System.currentTimeMillis() > (time + TIMEOUT_VALUE)) { + break; + } + } + return response; + } +} diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/APIBean.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/APIBean.java new file mode 100644 index 0000000000..b52122ed80 --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/APIBean.java @@ -0,0 +1,48 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.test.utils.bean; + +import org.wso2.carbon.apimgt.api.model.API; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; + +import java.util.HashSet; +import java.util.Set; + +public class APIBean extends API { + private String tags; + private String availableTiers; + + public APIBean(APIIdentifier id) { + super(id); + } + + public void setAvailableTiers(String availableTiers) { + this.availableTiers = availableTiers; + } + + public void setTags(String tags) { + this.tags = tags; + Set stringSet = new HashSet(); + String[] strings = tags.split(","); + for (String str : strings) { + stringSet.add(str); + } + super.addTags(stringSet); + } +} diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/APILifeCycleState.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/APILifeCycleState.java new file mode 100644 index 0000000000..694f4f1027 --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/APILifeCycleState.java @@ -0,0 +1,34 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.test.utils.bean; + +public enum APILifeCycleState { + + PUBLISHED("PUBLISHED"), CREATED("CREATED"), DEPRECATED("DEPRECATED"), BLOCKED("BLOCKED"), RETIRED("RETIRED"); + + private String state; + + APILifeCycleState(String state) { + this.state = state; + } + + public String getState() { + return state; + } +} diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/APILifeCycleStateRequest.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/APILifeCycleStateRequest.java new file mode 100644 index 0000000000..6b2d994f42 --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/APILifeCycleStateRequest.java @@ -0,0 +1,83 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.test.utils.bean; + +/** + * action=updateStatus&name=YoutubeFeeds&version=1.0.0&provider=provider1&status=PUBLISHED&publishToGateway=true + */ +public class APILifeCycleStateRequest extends AbstractRequest { + private String name; + private String status; + private String provider; + private String version = "1.0.0"; + private String publishToGateway = "true"; + + public APILifeCycleStateRequest(String apiName, String provider, APILifeCycleState status) { + this.name = apiName; + this.status = status.getState(); + this.provider = provider; + } + + @Override + public void setAction() { + setAction("updateStatus"); + } + + @Override + public void init() { + addParameter("name", name); + addParameter("status", status); + addParameter("provider", provider); + + addParameter("version", version); + addParameter("publishToGateway", publishToGateway); + } + + public String getName() { + return name; + } + + public String getState() { + return status; + } + + public void setState(APILifeCycleState status) { + this.status = status.getState(); + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getProvider() { + return provider; + } + + public boolean getPublishToGateway() { + return Boolean.valueOf(publishToGateway); + } + + public void setPublishToGateway(boolean publishToGateway) { + this.publishToGateway = String.valueOf(publishToGateway); + } +} diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/APIRequest.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/APIRequest.java new file mode 100644 index 0000000000..921c1ffa10 --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/APIRequest.java @@ -0,0 +1,292 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.test.utils.bean; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.net.URL; + +/** + * action=addAPI&name=YoutubeFeeds&visibility=public&version=1.0.0&description=Youtube Live Feeds&endpointType=nonsecured + * &http_checked=http&https_checked=https&endpoint=http://gdata.youtube.com/feeds/api/standardfeeds&wsdl=& + * tags=youtube,gdata,multimedia&tier=Silver&thumbUrl=http://www.10bigideas.com.au/www/573/files/pf-thumbnail-youtube_logo.jpg + * &context=/youtube&tiersCollection=Gold&resourceCount=0&resourceMethod-0=GET + * &resourceMethodAuthType-0=Application&resourceMethodThrottlingTier-0=Unlimited&uriTemplate-0=/* + */ + +public class APIRequest extends AbstractRequest { + + private String name; + private String context; + private JSONObject endpoint; + + private String visibility = "public"; + private String version = "1.0.0"; + private String description = "description"; + private String endpointType = "nonsecured"; + private String http_checked = "http"; + private String https_checked = "https"; + private String tags = "tags"; + private String tier = "Silver"; + private String thumbUrl = ""; + private String tiersCollection = "Gold"; + private String resourceCount = "0"; + private String resourceMethod = "GET,POST"; + private String resourceMethodAuthType = + "Application & Application User,Application & Application User"; + private String resourceMethodThrottlingTier = "Unlimited,Unlimited"; + private String uriTemplate = "/*"; + private String roles = ""; + private String wsdl = ""; + private String defaultVersion = ""; + + public String getSandbox() { + return sandbox; + } + + public void setSandbox(String sandbox) { + this.sandbox = sandbox; + } + + private String sandbox = ""; + + public String getRoles() { + return roles; + } + + public void setRoles(String roles) { + this.roles = roles; + } + + public String getWsdl() { + return wsdl; + } + + public void setWsdl(String wsdl) { + this.wsdl = wsdl; + } + + private String provider = "admin"; + + public APIRequest(String apiName, String context, URL endpointUrl) { + this.name = apiName; + this.context = context; + try { + this.endpoint = new JSONObject("{\"production_endpoints\":{\"url\":\"" + + endpointUrl + + "\",\"config\":null},\"endpoint_type\":\"" + + endpointUrl.getProtocol() + "\"}"); + } catch (JSONException e) { + //ignore + } + + } + + @Override + public void setAction() { + setAction("addAPI"); + } + + public void setAction(String action) { + super.setAction(action); + } + + @Override + public void init() { + addParameter("name", name); + addParameter("context", context); + addParameter("endpoint_config", endpoint.toString()); + addParameter("provider", getProvider()); + addParameter("visibility", getVisibility()); + addParameter("version", getVersion()); + addParameter("description", getDescription()); + addParameter("endpointType", getEndpointType()); + addParameter("http_checked", getHttp_checked()); + addParameter("https_checked", getHttps_checked()); + addParameter("tags", getTags()); + addParameter("tier", getTier()); + addParameter("thumbUrl", getThumbUrl()); + addParameter("tiersCollection", getTiersCollection()); + addParameter("resourceCount", getResourceCount()); + addParameter("resourceMethod-0", getResourceMethod()); + addParameter("resourceMethodAuthType-0", getResourceMethodAuthType()); + addParameter("resourceMethodThrottlingTier-0", getResourceMethodThrottlingTier()); + addParameter("uriTemplate-0", getUriTemplate()); + addParameter("default_version_checked", getDefaultVersion()); + if (roles.length() > 1) { + addParameter("roles", getRoles()); + } + if (wsdl.length() > 1) { + addParameter("wsdl", getWsdl()); + } + if (sandbox.length() > 1) { + addParameter("sandbox", getSandbox()); + } + + } + + public String getProvider() { + return provider; + } + + public void setProvider(String provider) { + this.provider = provider; + } + + public String getName() { + return name; + } + + public JSONObject getEndpointConfig() { + return endpoint; + } + + public String getContext() { + return context; + } + + public String getVisibility() { + return visibility; + } + + public void setVisibility(String visibility) { + this.visibility = visibility; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getEndpointType() { + return endpointType; + } + + public void setEndpointType(String endpointType) { + this.endpointType = endpointType; + } + + public String getHttp_checked() { + return http_checked; + } + + public void setHttp_checked(String http_checked) { + this.http_checked = http_checked; + } + + public String getHttps_checked() { + return https_checked; + } + + public void setHttps_checked(String https_checked) { + this.https_checked = https_checked; + } + + public String getTags() { + return tags; + } + + public void setTags(String tags) { + this.tags = tags; + } + + public String getTier() { + return tier; + } + + public void setTier(String tier) { + this.tier = tier; + } + + public String getThumbUrl() { + return thumbUrl; + } + + public void setThumbUrl(String thumbUrl) { + this.thumbUrl = thumbUrl; + } + + public String getTiersCollection() { + return tiersCollection; + } + + public void setTiersCollection(String tiersCollection) { + this.tiersCollection = tiersCollection; + } + + public String getResourceCount() { + return resourceCount; + } + + public void setResourceCount(String resourceCount) { + this.resourceCount = resourceCount; + } + + public String getResourceMethod() { + return resourceMethod; + } + + public void setResourceMethod(String resourceMethod) { + this.resourceMethod = resourceMethod; + } + + public String getResourceMethodAuthType() { + return resourceMethodAuthType; + } + + public void setResourceMethodAuthType(String resourceMethodAuthType) { + this.resourceMethodAuthType = resourceMethodAuthType; + } + + public String getResourceMethodThrottlingTier() { + return resourceMethodThrottlingTier; + } + + public void setResourceMethodThrottlingTier(String resourceMethodThrottlingTier) { + this.resourceMethodThrottlingTier = resourceMethodThrottlingTier; + } + + public String getUriTemplate() { + return uriTemplate; + } + + public void setUriTemplate(String uriTemplate) { + this.uriTemplate = uriTemplate; + } + + public String getDefaultVersion() { + return defaultVersion; + } + + public void setDefaultVersion(String defaultVersion) { + this.defaultVersion = defaultVersion; + } +} diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/AbstractRequest.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/AbstractRequest.java new file mode 100644 index 0000000000..95b63b48b6 --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/AbstractRequest.java @@ -0,0 +1,62 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.test.utils.bean; + +import java.util.HashMap; +import java.util.Map; + +public abstract class AbstractRequest { + public String action; + private Map parameterMap = new HashMap(); + private static final String ACTION_PARAMETER_VALUE = "action"; + + public String generateRequestParameters() { + parameterMap.clear(); + setAction(); + init(); + String requestParams = ACTION_PARAMETER_VALUE + "=" + action; + for (String key : parameterMap.keySet()) { + requestParams = requestParams + "&" + key + "=" + parameterMap.get(key); + } + return requestParams; + } + + public String generateRequestParameters(String actionName) { + parameterMap.clear(); + setAction(); + init(); + String requestParams = ACTION_PARAMETER_VALUE + "=" + actionName; + for (String key : parameterMap.keySet()) { + requestParams = requestParams + "&" + key + "=" + parameterMap.get(key); + } + return requestParams; + } + + public void addParameter(String key, String value) { + parameterMap.put(key, value); + } + + public abstract void setAction(); + + public abstract void init(); + + public void setAction(String actionName) { + this.action = actionName; + } +} diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/GenerateAppKeyRequest.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/GenerateAppKeyRequest.java new file mode 100644 index 0000000000..f87ef65c0a --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/GenerateAppKeyRequest.java @@ -0,0 +1,81 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.test.utils.bean; + +/** + * action=generateApplicationKey&application=DefaultApplication&keytype=PRODUCTION&callbackUrl=&authorizedDomains=ALL&validityTime=360000 + */ +public class GenerateAppKeyRequest extends AbstractRequest { + + private String application = "DefaultApplication"; + private String keyType = "PRODUCTION"; + private String callbackUrl = "some-url"; + private String authorizedDomains = "ALL"; + private int validityTime = 360000; + + public GenerateAppKeyRequest(String application) { + this.application = application; + } + + @Override + public void setAction() { + setAction("generateApplicationKey"); + } + + @Override + public void init() { + addParameter("application", application); + addParameter("keytype", keyType); + addParameter("callbackUrl", callbackUrl); + addParameter("authorizedDomains", authorizedDomains); + addParameter("validityTime", String.valueOf(validityTime)); + } + + public String getKeyType() { + return keyType; + } + + public void setKeyType(String keyType) { + this.keyType = keyType; + } + + public String getCallbackUrl() { + return callbackUrl; + } + + public void setCallbackUrl(String callbackUrl) { + this.callbackUrl = callbackUrl; + } + + public String getAuthorizedDomains() { + return authorizedDomains; + } + + public void setAuthorizedDomains(String authorizedDomains) { + this.authorizedDomains = authorizedDomains; + } + + public int getValidityTime() { + return validityTime; + } + + public void setValidityTime(int validityTime) { + this.validityTime = validityTime; + } +} diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/SubscriptionRequest.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/SubscriptionRequest.java new file mode 100644 index 0000000000..7fd131c927 --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/bean/SubscriptionRequest.java @@ -0,0 +1,82 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.test.utils.bean; + +/** + * action=addAPISubscription&name=apiName&version=1.0.0&provider=provider&tier=Gold&applicationName=DefaultApplication + */ +public class SubscriptionRequest extends AbstractRequest { + + private String name; + private String provider; + private String version = "1.0.0"; + private String applicationName = "DefaultApplication"; + private String tier = "Gold"; + + public SubscriptionRequest(String apiName, String provider) { + this.name = apiName; + this.provider = provider; + } + + @Override + public void setAction() { + setAction("addAPISubscription"); + } + + @Override + public void init() { + addParameter("name", name); + addParameter("provider", provider); + addParameter("version", version); + addParameter("applicationName", applicationName); + addParameter("tier", tier); + } + + public String getName() { + return name; + } + + public String getProvider() { + return provider; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getApplicationName() { + return applicationName; + } + + public void setApplicationName(String applicationName) { + this.applicationName = applicationName; + } + + public String getTier() { + return tier; + } + + public void setTier(String tier) { + this.tier = tier; + } +} diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/clients/APIPublisherRestClient.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/clients/APIPublisherRestClient.java new file mode 100644 index 0000000000..6eccf4bd30 --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/clients/APIPublisherRestClient.java @@ -0,0 +1,383 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.test.utils.clients; + +import org.wso2.am.integration.test.utils.bean.APILifeCycleStateRequest; +import org.wso2.am.integration.test.utils.bean.APIRequest; +import org.wso2.am.integration.test.utils.validation.VerificationUtil; +import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; +import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class APIPublisherRestClient { + private String backEndUrl; + private static final String URL_SURFIX = "/publisher/site/blocks"; + private Map requestHeaders = new HashMap(); + + public APIPublisherRestClient(String backEndUrl) { + this.backEndUrl = backEndUrl; + if (requestHeaders.get("Content-Type") == null) { + this.requestHeaders.put("Content-Type", "application/x-www-form-urlencoded"); + } + } + + public HttpResponse login(String userName, String password) + throws Exception { + HttpResponse response = HttpRequestUtil + .doPost(new URL(backEndUrl + URL_SURFIX + "/user/login/ajax/login.jag") + , "action=login&username=" + userName + "&password=" + password + "", + requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + String session = getSession(response.getHeaders()); + if (session == null) { + throw new Exception("No session cookie found with response"); + } + setSession(session); + return response; + } else { + throw new Exception("User Login failed> " + response.getData()); + } + + } + + public HttpResponse logout() + throws Exception { + HttpResponse response = HttpRequestUtil + .doGet(backEndUrl + URL_SURFIX + "/user/login/ajax/login.jag?action=logout", + requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + String session = getSession(response.getHeaders()); + if (session == null) { + throw new Exception("No session cookie found with response"); + } + setSession(session); + return response; + } else { + throw new Exception("User Login failed> " + response.getData()); + } + + } + + public HttpResponse addAPI(APIRequest apiRequest) + throws Exception { + checkAuthentication(); + HttpResponse response = + HttpRequestUtil.doPost(new URL(backEndUrl + URL_SURFIX + "/item-add/ajax/add.jag") + , apiRequest.generateRequestParameters() + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Adding failed> " + response.getData()); + } + } + + public HttpResponse copyAPI(String provider, String APIName, String oldVersion, + String newVersion, String isDefaultVersion) + throws Exception { + checkAuthentication(); + HttpResponse response = + HttpRequestUtil.doPost(new URL(backEndUrl + URL_SURFIX + "/overview/ajax/overview.jag") + , "action=createNewAPI&provider=" + provider + "&apiName=" + APIName + "&version=" + + oldVersion + "&newVersion=" + newVersion + "&isDefaultVersion=" + isDefaultVersion + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Copying failed> " + response.getData()); + } + } + + public HttpResponse updateAPI(APIRequest apiRequest) + throws Exception { + checkAuthentication(); + HttpResponse response = + HttpRequestUtil.doPost(new URL(backEndUrl + URL_SURFIX + "/item-add/ajax/add.jag") + , apiRequest.generateRequestParameters("updateAPI") + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Adding failed> " + response.getData()); + } + } + + public HttpResponse changeAPILifeCycleStatusTo(APILifeCycleStateRequest updateRequest) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL( + backEndUrl + "/publisher/site/blocks/life-cycles/ajax/life-cycles.jag") + , updateRequest.generateRequestParameters() + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API LifeCycle Updating failed> " + response.getData()); + } + + } + + public HttpResponse getApi(String apiName, String provider) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doPost(new URL(backEndUrl + "/publisher/site/blocks/listing/ajax/item-list.jag") + , + "action=getAPI&name=" + apiName + "&version=1.0.0&provider=" + provider + "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get API Information failed> " + response.getData()); + } + + /* name=YoutubeFeeds&version=1.0.0&provider=provider1&status=PUBLISHED&publishToGateway=true&action=updateStatus */ + + } + + public HttpResponse deleteApi(String name, String version, String provider) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doPost(new URL(backEndUrl + "/publisher/site/blocks/item-add/ajax/remove.jag") + , "action=removeAPI&name=" + name + "&version=" + version + "&provider=" + + provider + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Deletion failed> " + response.getData()); + } + } + + public void setHttpHeader(String headerName, String value) { + this.requestHeaders.put(headerName, value); + } + + public String getHttpHeader(String headerName) { + return this.requestHeaders.get(headerName); + } + + public void removeHttpHeader(String headerName) { + this.requestHeaders.remove(headerName); + } + + private String getSession(Map responseHeaders) { + return responseHeaders.get("Set-Cookie"); + } + + private String setSession(String session) { + return requestHeaders.put("Cookie", session); + } + + private boolean checkAuthentication() throws Exception { + if (requestHeaders.get("Cookie") == null) { + throw new Exception("No Session Cookie found. Please login first"); + } + return true; + } + + /** + * @param apiName String name of the API that need to remove + * @param version String version of the API that need to remove + * @param provider String provider name of the API that need to remove + * @return + * @throws Exception when invocation does ont return 200 response + */ + public HttpResponse removeAPI(String apiName, String version, String provider) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doPost(new URL(backEndUrl + "/publisher/site/blocks/item-add/ajax/remove.jag") + , "action=removeAPI" + "&name=" + apiName + "&version=" + version + + "&provider=" + provider + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse addDocument(String apiName, String version, String provider, String docName, + String docType, String sourceType, String docUrl, + String summary, String docLocation) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doPost(new URL(backEndUrl + "/publisher/site/blocks/documentation/ajax/docs.jag") + , "action=addDocumentation" + "&mode=''&provider=" + provider + "&apiName=" + + apiName + "&version=" + version + "&docName=" + docName + "&docType=" + + docType + "&sourceType=" + sourceType + "&docUrl=" + docUrl + + summary + "&docLocation=" + docLocation + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse updateDocument(String apiName, String version, String provider, String docName, + String docType, String sourceType, String docUrl, + String summary, String docLocation) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doPost(new URL(backEndUrl + "/publisher/site/blocks/documentation/ajax/docs.jag") + , "action=addDocumentation" + "&mode=Update&provider=" + provider + "&apiName=" + + apiName + "&version=" + version + "&docName=" + docName + "&docType=" + + docType + "&sourceType=" + sourceType + "&docUrl=" + docUrl + + summary + "&docLocation=" + docLocation + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse inlineContent(String apiName, String version, String provider, + String docName, String content, String docDetails) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doPost(new URL(backEndUrl + "/publisher/site/blocks/documentation/ajax/docs.jag") + , "action=addInlineContent" + "&provider=" + provider + "&apiName=" + + apiName + "&version=" + version + "&docName=" + docName + "&content=" + + content + "&docDetails=" + docDetails + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse removeDocumentation(String apiName, String version, String provider, + String docName, String docType) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doPost(new URL(backEndUrl + "/publisher/site/blocks/documentation/ajax/docs.jag") + , "action=removeDocumentation" + "&provider=" + provider + "&apiName=" + + apiName + "&version=" + version + "&docName=" + docName + "&docType=" + + docType + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse getAccessTokenData(String accessToken) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doPost(new URL(backEndUrl + "/publisher/site/blocks/tokens/ajax/token.jag") + , "action=getAccessTokenData" + "&accessToken=" + accessToken + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse revokeAccessToken(String accessToken, String consumerKey, String authUser) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doPost(new URL(backEndUrl + "/publisher/site/blocks/tokens/ajax/revokeToken.jag") + , + "action=revokeAccessToken" + "&accessToken=" + accessToken + "&authUser=" + + authUser + "&consumerKey=" + consumerKey + , requestHeaders + ); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse revokeAccessTokenBySubscriber(String subscriberName) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doPost(new URL(backEndUrl + "/publisher/site/blocks/tokens/ajax/revokeToken.jag") + , + "action=revokeAccessTokenBySubscriber" + "&subscriberName=" + subscriberName + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse updatePermissions(String tierName, String permissionType, String roles) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doPost(new URL(backEndUrl + "/publisher/site/blocks/tiers/ajax/tiers.jag") + , + "action=updatePermissions" + "&tierName=" + tierName + "&permissiontype=" + + permissionType + "&roles=" + roles + , requestHeaders + ); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse createNewAPI(String provider, String apiName, String version, + String newVersion) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doPost(new URL(backEndUrl + "/publisher/site/blocks/overview/ajax/overview.jag") + , "action=createNewAPI" + "&provider=" + provider + "&apiName=" + apiName + + "&version=" + version + "&newVersion=" + newVersion + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } +} diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/clients/APIStoreRestClient.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/clients/APIStoreRestClient.java new file mode 100644 index 0000000000..8bf98dcc8d --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/clients/APIStoreRestClient.java @@ -0,0 +1,486 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.test.utils.clients; + +import org.apache.commons.codec.binary.Base64; +import org.wso2.am.integration.test.utils.bean.GenerateAppKeyRequest; +import org.wso2.am.integration.test.utils.bean.SubscriptionRequest; +import org.wso2.am.integration.test.utils.validation.VerificationUtil; +import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; +import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class APIStoreRestClient { + private String backEndUrl; + private Map requestHeaders = new HashMap(); + + public APIStoreRestClient(String backEndUrl) { + this.backEndUrl = backEndUrl; + if (requestHeaders.get("Content-Type") == null) { + this.requestHeaders.put("Content-Type", "application/x-www-form-urlencoded"); + } + } + + public HttpResponse login(String userName, String password) + throws Exception { + HttpResponse response = HttpRequestUtil + .doPost(new URL(backEndUrl + "/store/site/blocks/user/login/ajax/login.jag") + , "action=login&username=" + userName + "&password=" + password + "", + requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + String session = getSession(response.getHeaders()); + if (session == null) { + throw new Exception("No session cookie found with response"); + } + setSession(session); + return response; + } else { + throw new Exception("User Login failed> " + response.getData()); + } + + } + + public HttpResponse subscribe(SubscriptionRequest subscriptionRequest) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + + "/store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag") + , subscriptionRequest.generateRequestParameters() + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + + } + + public HttpResponse generateApplicationKey(GenerateAppKeyRequest generateAppKeyRequest) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + + "/store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag") + , generateAppKeyRequest.generateRequestParameters() + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + + } + + public HttpResponse getAPI(String apiName) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + + "/store/site/blocks/api/listing/ajax/list.jag?action=getAllPublishedAPIs") + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public void setHttpHeader(String headerName, String value) { + this.requestHeaders.put(headerName, value); + } + + public String getHttpHeader(String headerName) { + return this.requestHeaders.get(headerName); + } + + public void removeHttpHeader(String headerName) { + this.requestHeaders.remove(headerName); + } + + private String getSession(Map responseHeaders) { + return responseHeaders.get("Set-Cookie"); + } + + private String setSession(String session) { + return requestHeaders.put("Cookie", session); + } + + private boolean checkAuthentication() throws Exception { + if (requestHeaders.get("Cookie") == null) { + throw new Exception("No Session Cookie found. Please login first"); + } + return true; + } + + public HttpResponse generateUserAccessKey(String consumeKey, String consumerSecret, String body, + URL tokenEndpointURL) + throws Exception { + checkAuthentication(); + Map authenticationRequestHeaders = new HashMap(); + String basicAuthHeader = consumeKey + ":" + consumerSecret; + byte[] encodedBytes = Base64.encodeBase64(basicAuthHeader.getBytes()); + authenticationRequestHeaders.put("Content-Type", "application/x-www-form-urlencoded"); + authenticationRequestHeaders.put("Authorization", "Basic " + new String(encodedBytes)); + HttpResponse response = HttpRequestUtil.doPost(tokenEndpointURL + , body + , authenticationRequestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + public HttpResponse getAllPublishedAPIs() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl + + "/store/site/blocks/api/listing/ajax/list.jag?action=getAllPublishedAPIs" + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + public HttpResponse getAllApplications() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl + + "/store/site/blocks/application/application-list/ajax/application-list.jag?action=getApplications" + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + public HttpResponse getPublishedAPIsByApplication(String applicationName) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl + + "/store/site/blocks/subscription/subscription-list/ajax/subscription-list.jag?action=getSubscriptionByApplication&app=" + + applicationName + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + public HttpResponse addRatingToAPI(String apiName, String version, String provider, + String rating) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doGet(backEndUrl + "/store/site/blocks/api/api-info/ajax/api-info.jag?" + + "action=addRating&name=" + apiName + "&version=" + version + "&provider=" + + provider + "&rating=" + rating + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + public HttpResponse removeRatingFromAPI(String apiName, String version, String provider) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doGet(backEndUrl + "/store/site/blocks/api/api-info/ajax/api-info.jag?" + + "action=removeRating&name=" + apiName + "&version=" + version + + "&provider=" + provider + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + public HttpResponse isRatingActivated() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doGet(backEndUrl + "/store/site/blocks/api/api-info/ajax/api-info.jag?" + + "action=isRatingActivated" + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + /* + apiData.name = request.getParameter("name"); + apiData.version = request.getParameter("version"); + apiData.provider = request.getParameter("provider") + */ + public HttpResponse getAllDocumentationOfApi(String apiName, String version, String provider) + throws Exception { + checkAuthentication(); + HttpResponse response = + HttpRequestUtil.doGet(backEndUrl + "/store/site/blocks/api/listing/ajax/list.jag?" + + "action=getAllDocumentationOfApi&name=" + apiName + + "&version=" + version + "&provider=" + provider + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + /* + tenant = request.getParameter("tenant"); + var start=request.getParameter("start"); + var end=request.getParameter("end"); + */ + public HttpResponse getAllPaginatedPublishedAPIs(String tenant, String start, String end) + throws Exception { + checkAuthentication(); + HttpResponse response = + HttpRequestUtil.doGet(backEndUrl + "/store/site/blocks/api/listing/ajax/list.jag?" + + "action=getAllPaginatedPublishedAPIs&tenant=" + tenant + + "&start=" + start + "&end=" + end + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + public HttpResponse getAllPublishedAPIs(String tenant) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + + "/store/site/blocks/api/listing/ajax/list.jag?action=getAllPublishedAPIs&tenant=" + + tenant) + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse addApplication(String application, String tier, String callbackUrl, + String description) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + + "/store/site/blocks/application/application-add/ajax/application-add.jag?action=addApplication&tier=" + + tier + "&callbackUrl=" + + callbackUrl + "&description=" + + description + "&application=" + + application) + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse getApplications() + throws Exception { + checkAuthentication(); + + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + + "/store/site/blocks/application/application-list/ajax/application-list.jag?action=getApplications") + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse removeApplication(String application) + throws Exception { + checkAuthentication(); + + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + + "/store/site/blocks/application/application-remove/ajax/application-remove.jag?action=removeApplication&application=" + + application) + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse updateApplication(String applicationOld, String applicationNew, + String callbackUrlNew, String descriptionNew, String tier) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + + "/store/site/blocks/application/application-update/ajax/application-update.jag?" + + "action=updateApplication&applicationOld=" + + applicationOld + "&applicationNew=" + + applicationNew + "&callbackUrlNew=" + + callbackUrlNew + + "&descriptionNew=" + descriptionNew + + "&tier=" + tier) + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse getAllSubscriptions() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + + "/store/site/blocks/subscription/subscription-list/ajax/subscription-list.jag?" + + "action=getAllSubscriptions") + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse removeAPISubscription(String API, String version, String provider, String applicationId) + throws Exception { + checkAuthentication(); + + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + + "/site/blocks/subscription/subscription-remove/ajax/subscription-remove.jag?action=removeSubscription&name=" + + API + "&version=" + version + "&provider=" + provider + "&applicationId=" + applicationId) + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse getAllTags() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL( + backEndUrl + "/store/site/blocks/tag/tag-cloud/ajax/list.jag?action=getAllTags") + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + /* + name = request.getParameter("name"); + version = request.getParameter("version"); + provider = request.getParameter("provider"); + comment = request.getParameter("comment"); + /home/sanjeewa/carbon/turing/components/apimgt/api-store-web/1.2.0/src/site/blocks/comment/comment-add/ajax/comment-add.jag + */ + public HttpResponse addComment(String name, String version, String provider, String comment) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doPost(new URL(backEndUrl + "/store/site/blocks/comment/comment-add/ajax/comment-add.jag?" + + "action=addComment&name=" + name + "&version=" + version + "&provider=" + + provider + "&comment=" + comment), "", requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse isCommentActivated() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil + .doGet(backEndUrl + "/store/site/blocks/comment/comment-add/ajax/comment-add.jag?" + + "action=isCommentActivated" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse getRecentlyAddedAPIs(String tenant, String limit) + throws Exception { + ///home/sanjeewa/carbon/turing/components/apimgt/api-store-web/1.2.0/src/site/blocks/api/recently-added/ajax/list.jag + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + + "/store/site/blocks/api/recently-added/ajax/list.jag?action=getRecentlyAddedAPIs" + + "&tenant=" + tenant + "&limit=" + + limit) + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } +} diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/esb/ESBTestCaseUtils.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/esb/ESBTestCaseUtils.java new file mode 100644 index 0000000000..8a00e0a7a3 --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/esb/ESBTestCaseUtils.java @@ -0,0 +1,2005 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.test.utils.esb; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.OMNamespace; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.Assert; +import org.wso2.am.admin.clients.endpoint.EndPointAdminClient; +import org.wso2.am.admin.clients.localentry.LocalEntriesAdminClient; +import org.wso2.am.admin.clients.mediation.MessageProcessorClient; +import org.wso2.am.admin.clients.mediation.MessageStoreAdminClient; +import org.wso2.am.admin.clients.mediation.PriorityMediationAdminClient; +import org.wso2.am.admin.clients.proxy.admin.ProxyServiceAdminClient; +import org.wso2.am.admin.clients.rest.api.RestApiAdminClient; +import org.wso2.am.admin.clients.sequences.SequenceAdminServiceClient; +import org.wso2.am.admin.clients.service.mgt.ServiceAdminClient; +import org.wso2.am.admin.clients.tasks.TaskAdminClient; +import org.wso2.am.admin.clients.template.EndpointTemplateAdminServiceClient; +import org.wso2.am.admin.clients.template.SequenceTemplateAdminServiceClient; +import org.wso2.carbon.endpoint.stub.types.EndpointAdminEndpointAdminException; +import org.wso2.carbon.localentry.stub.types.LocalEntryAdminException; +import org.wso2.carbon.proxyadmin.stub.ProxyServiceAdminProxyAdminException; +import org.wso2.carbon.rest.api.stub.RestApiAdminAPIException; +import org.wso2.carbon.sequences.stub.types.SequenceEditorException; +import org.wso2.carbon.task.stub.TaskManagementException; + +import javax.servlet.ServletException; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.rmi.RemoteException; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +public class ESBTestCaseUtils { + + protected Log log = LogFactory.getLog(getClass()); + private static int SERVICE_DEPLOYMENT_DELAY = + TestConfigurationProvider.getServiceDeploymentDelay(); + private static final String PROXY = "proxy"; + private static final String LOCAL_ENTRY = "localEntry"; + private static final String ENDPOINT = "endpoint"; + private static final String SEQUENCE = "sequence"; + private static final String MESSAGE_STORE = "messageStore"; + private static final String MESSAGE_PROCESSOR = "messageProcessor"; + private static final String TEMPLATE = "template"; + private static final String API = "api"; + private static final String PRIORITY_EXECUTOR = "priorityExecutor"; + private static final String KEY = "key"; + private static final String NAME = "name"; + private static final String VERSION = "version"; + + /** + * Loads the specified resource from the classpath and returns its content as an OMElement. + * + * @param path A relative path to the resource file + * @return An OMElement containing the resource content + */ + public OMElement loadResource(String path) throws FileNotFoundException, + XMLStreamException { + OMElement documentElement = null; + FileInputStream inputStream = null; + XMLStreamReader parser = null; + StAXOMBuilder builder = null; + path = TestConfigurationProvider.getResourceLocation() + path; + File file = new File(path); + if (file.exists()) { + try { + inputStream = new FileInputStream(file); + parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream); + //create the builder + builder = new StAXOMBuilder(parser); + //get the root element (in this case the envelope) + documentElement = builder.getDocumentElement().cloneOMElement(); + } finally { + if (builder != null) { + builder.close(); + } + if (parser != null) { + try { + parser.close(); + } catch (XMLStreamException e) { + //ignore + } + } + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException e) { + //ignore + } + } + + } + } else { + throw new FileNotFoundException("File Not Exist at " + path); + } + return documentElement; + } + + /** + * Loads the specified ESB configuration file from the classpath and deploys it into the ESB. + * + * @param synapseFilePath A relative path to the configuration file + * @throws java.rmi.RemoteException If an error occurs while loading the specified configuration + */ + public void loadESBConfigurationFrom(String synapseFilePath, String backendURL, + String sessionCookie) + throws Exception { + OMElement configElement = loadResource(synapseFilePath); + updateESBConfiguration(configElement, backendURL, sessionCookie); + } + + /** + * Loads the configuration of the specified sample into the ESB. + * + * @param number Sample number + * @throws Exception If an error occurs while loading the sample configuration + */ + public OMElement loadESBSampleConfiguration(int number) + throws Exception { + String filePath = TestConfigurationProvider.getResourceLocation("ESB") + + File.separator + "samples" + File.separator + "synapse_sample_" + number + + ".xml"; + File configFile = new File(filePath); + FileInputStream inputStream = null; + XMLStreamReader parser = null; + StAXOMBuilder builder = null; + OMElement documentElement = null; + try { + inputStream = new FileInputStream(configFile.getAbsolutePath()); + parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream); + builder = new StAXOMBuilder(parser); + documentElement = builder.getDocumentElement().cloneOMElement(); + + } finally { + if (builder != null) { + builder.close(); + } + if (parser != null) { + try { + parser.close(); + } catch (XMLStreamException e) { + //ignore + } + } + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException e) { + //ignore + } + } + } + return documentElement; + } + + /** + * load synapse configuration from OMElement + * + * @param synapseConfig synapse configuration + * @param backendURL server backEnd url + * @param sessionCookie session Cookie + * @throws java.rmi.RemoteException + * @throws javax.xml.stream.XMLStreamException + * @throws ServletException + */ + public void updateESBConfiguration(OMElement synapseConfig, String backendURL, + String sessionCookie) + throws Exception { + ProxyServiceAdminClient proxyAdmin = new ProxyServiceAdminClient(backendURL, sessionCookie); + EndPointAdminClient endPointAdminClient = + new EndPointAdminClient(backendURL, sessionCookie); + SequenceAdminServiceClient sequenceAdminClient = + new SequenceAdminServiceClient(backendURL, sessionCookie); + LocalEntriesAdminClient localEntryAdminServiceClient = + new LocalEntriesAdminClient(backendURL, sessionCookie); + MessageProcessorClient messageProcessorClient = + new MessageProcessorClient(backendURL, sessionCookie); + MessageStoreAdminClient messageStoreAdminClient = + new MessageStoreAdminClient(backendURL, sessionCookie); + ServiceAdminClient adminServiceService = new ServiceAdminClient(backendURL, sessionCookie); + EndpointTemplateAdminServiceClient endpointTemplateAdminServiceClient = + new EndpointTemplateAdminServiceClient(backendURL, sessionCookie); + SequenceTemplateAdminServiceClient sequenceTemplateAdminServiceClient = + new SequenceTemplateAdminServiceClient(backendURL, sessionCookie); + RestApiAdminClient apiAdminClient = new RestApiAdminClient(backendURL, sessionCookie); + PriorityMediationAdminClient priorityMediationAdminClient = + new PriorityMediationAdminClient(backendURL, sessionCookie); + + Iterator localEntries = synapseConfig.getChildrenWithLocalName(LOCAL_ENTRY); + while (localEntries.hasNext()) { + OMElement localEntry = localEntries.next(); + String le = localEntry.getAttributeValue(new QName(KEY)); + if (ArrayUtils.contains(localEntryAdminServiceClient.getEntryNames(), le)) { + Assert.assertTrue(localEntryAdminServiceClient.deleteLocalEntry(le), + le + " Local Entry deletion failed"); + Assert.assertTrue(isLocalEntryUnDeployed(backendURL, sessionCookie, le), + le + " Local Entry undeployment failed"); + } + Assert.assertTrue(localEntryAdminServiceClient.addLocalEntry(localEntry), + le + " Local Entry addition failed"); + log.info(le + " LocalEntry Uploaded"); + } + + Iterator endpoints = synapseConfig.getChildrenWithLocalName(ENDPOINT); + while (endpoints.hasNext()) { + OMElement endpoint = endpoints.next(); + String ep = endpoint.getAttributeValue(new QName(NAME)); + if (ArrayUtils.contains(endPointAdminClient.getEndpointNames(), ep)) { + Assert.assertTrue(endPointAdminClient.deleteEndpoint(ep), + ep + " Endpoint deletion failed"); + Assert.assertTrue(isEndpointUnDeployed(backendURL, sessionCookie, ep), + ep + " Endpoint undeployment failed"); + } + Assert.assertTrue(endPointAdminClient.addEndPoint(endpoint), + ep + " Endpoint addition failed"); + log.info(ep + " Endpoint Uploaded"); + } + + Iterator sequences = synapseConfig.getChildrenWithLocalName(SEQUENCE); + while (sequences.hasNext()) { + OMElement sequence = sequences.next(); + String sqn = sequence.getAttributeValue(new QName(NAME)); + boolean isSequenceExist = ArrayUtils.contains(sequenceAdminClient.getSequences(), sqn); + if (("main".equalsIgnoreCase(sqn) || "fault".equalsIgnoreCase(sqn)) && + isSequenceExist) { + sequenceAdminClient.updateSequence(sequence); + } else { + if (isSequenceExist) { + sequenceAdminClient.deleteSequence(sqn); + Assert.assertTrue(isSequenceUnDeployed(backendURL, sessionCookie, sqn), + sqn + " Sequence undeployment failed"); + } + sequenceAdminClient.addSequence(sequence); + } + log.info(sqn + " Sequence Uploaded"); + } + + Iterator proxies = synapseConfig.getChildrenWithLocalName(PROXY); + while (proxies.hasNext()) { + OMElement proxy = proxies.next(); + String proxyName = proxy.getAttributeValue(new QName(NAME)); + if (adminServiceService.isServiceExists(proxyName)) { + proxyAdmin.deleteProxy(proxyName); + Assert.assertTrue(isProxyUnDeployed(backendURL, sessionCookie, proxyName), + proxyName + " Undeployment failed"); + } + proxyAdmin.addProxyService(proxy); + log.info(proxyName + " Proxy Uploaded"); + } + + Iterator messageStores = synapseConfig.getChildrenWithLocalName(MESSAGE_STORE); + while (messageStores.hasNext()) { + OMElement messageStore = messageStores.next(); + String mStore = messageStore.getAttributeValue(new QName(NAME)); + if (ArrayUtils.contains(messageStoreAdminClient.getMessageStores(), mStore)) { + messageStoreAdminClient.deleteMessageStore(mStore); + Assert.assertTrue(isMessageStoreUnDeployed(backendURL, sessionCookie, mStore), + mStore + " Message Store undeployment failed"); + } + messageStoreAdminClient.addMessageStore(messageStore); + log.info(mStore + " Message Store Uploaded"); + } + + Iterator messageProcessors = + synapseConfig.getChildrenWithLocalName(MESSAGE_PROCESSOR); + while (messageProcessors.hasNext()) { + OMElement messageProcessor = messageProcessors.next(); + String mProcessor = messageProcessor.getAttributeValue(new QName(NAME)); + if (ArrayUtils + .contains(messageProcessorClient.getMessageProcessorNames(), mProcessor)) { + messageProcessorClient.deleteMessageProcessor(mProcessor); + Assert.assertTrue( + isMessageProcessorUnDeployed(backendURL, sessionCookie, mProcessor) + , mProcessor + " Message Processor undeployment failed"); + } + messageProcessorClient.addMessageProcessor(messageProcessor); + log.info(mProcessor + " Message Processor Uploaded"); + } + + Iterator templates = synapseConfig.getChildrenWithLocalName(TEMPLATE); + while (templates.hasNext()) { + OMElement template = templates.next(); + String templateName = template.getAttributeValue(new QName(NAME)); + if (template.getFirstChildWithName( + new QName(template.getNamespace().getNamespaceURI(), SEQUENCE)) != null) { + if (ArrayUtils.contains(sequenceTemplateAdminServiceClient.getSequenceTemplates(), + templateName)) { + sequenceTemplateAdminServiceClient.deleteTemplate(templateName); + Assert.assertTrue( + isSequenceTemplateUnDeployed(backendURL, sessionCookie, templateName) + , templateName + " Sequence Template undeployment failed"); + } + sequenceTemplateAdminServiceClient.addSequenceTemplate(template); + + } else { + + if (ArrayUtils.contains(endpointTemplateAdminServiceClient.getEndpointTemplates(), + templateName)) { + endpointTemplateAdminServiceClient.deleteEndpointTemplate(templateName); + Assert.assertTrue( + isEndpointTemplateUnDeployed(backendURL, sessionCookie, templateName) + , templateName + " Endpoint Template undeployment failed"); + } + endpointTemplateAdminServiceClient.addEndpointTemplate(template); + } + log.info(templateName + " Template Uploaded"); + } + + Iterator apiElements = synapseConfig.getChildrenWithLocalName(API); + while (apiElements.hasNext()) { + OMElement api = apiElements.next(); + String apiName = api.getAttributeValue(new QName(NAME)); + if (ArrayUtils.contains(apiAdminClient.getApiNames(), apiName)) { + apiAdminClient.deleteApi(apiName); + Assert.assertTrue(isApiUnDeployed(backendURL, sessionCookie, apiName) + , apiName + " Api undeployment failed"); + } + apiAdminClient.add(api); + log.info(apiName + " API Uploaded"); + } + + Iterator priorityExecutorList = + synapseConfig.getChildrenWithLocalName(PRIORITY_EXECUTOR); + while (priorityExecutorList.hasNext()) { + OMElement executor = priorityExecutorList.next(); + String executorName = executor.getAttributeValue(new QName(NAME)); + if (ArrayUtils.contains(priorityMediationAdminClient.getExecutorList(), executorName)) { + priorityMediationAdminClient.remove(executorName); + Assert.assertTrue( + isPriorityExecutorUnDeployed(backendURL, sessionCookie, executorName) + , executorName + " Priority Executor undeployment failed"); + } + priorityMediationAdminClient.addPriorityMediator(executorName, executor); + log.info(executorName + " Priority Executor Uploaded"); + } + + Thread.sleep(1000); + verifySynapseDeployment(synapseConfig, backendURL, sessionCookie); + log.info("Synapse configuration Deployed"); + + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param proxyConfig + * @throws javax.xml.stream.XMLStreamException + * @throws java.io.IOException + * @throws ProxyServiceAdminProxyAdminException + * @throws InterruptedException + */ + public void addProxyService(String backEndUrl, String sessionCookie, OMElement proxyConfig) + throws Exception { + ProxyServiceAdminClient proxyAdmin = new ProxyServiceAdminClient(backEndUrl, sessionCookie); + proxyAdmin.addProxyService(proxyConfig); + String proxyName = proxyConfig.getAttributeValue(new QName(NAME)); + Assert.assertTrue(isProxyDeployed(backEndUrl, sessionCookie, proxyName), + "Proxy Deployment failed or time out"); + + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param endpointConfig + * @throws Exception + */ + public void addEndpoint(String backEndUrl, String sessionCookie, OMElement endpointConfig) + throws Exception { + EndPointAdminClient endPointAdminClient = + new EndPointAdminClient(backEndUrl, sessionCookie); + endPointAdminClient.addEndPoint(endpointConfig); + String ep = endpointConfig.getAttributeValue(new QName(NAME)); + Assert.assertTrue(isEndpointDeployed(backEndUrl, sessionCookie, ep), + ep + "Endpoint deployment not found or time out"); + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param localEntryConfig + * @return + * @throws Exception + */ + public void addLocalEntry(String backEndUrl, String sessionCookie, + OMElement localEntryConfig) throws Exception { + LocalEntriesAdminClient localEntryAdminServiceClient = + new LocalEntriesAdminClient(backEndUrl, + sessionCookie); + boolean value = localEntryAdminServiceClient.addLocalEntry(localEntryConfig); + Assert.assertTrue(value, "LocalEntry Addition failed"); + if (value) { + String le = localEntryConfig.getAttributeValue(new QName(KEY)); + Assert.assertTrue(isLocalEntryDeployed(backEndUrl, sessionCookie, le), + le + "LocalEntry deployment not found or time out"); + } + + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param sequenceConfig + * @throws Exception + */ + public void addSequence(String backEndUrl, String sessionCookie, OMElement sequenceConfig) + throws Exception { + SequenceAdminServiceClient sequenceAdminClient = new SequenceAdminServiceClient(backEndUrl, + sessionCookie); + sequenceAdminClient.addSequence(sequenceConfig); + String sqn = sequenceConfig.getAttributeValue(new QName(NAME)); + Assert.assertTrue(isSequenceDeployed(backEndUrl, sessionCookie, sqn), + sqn + "Sequence deployment not found or time out"); + + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param messageStore + * @throws java.rmi.RemoteException + */ + public void addMessageStore(String backEndUrl, String sessionCookie, OMElement messageStore) + throws Exception { + MessageStoreAdminClient messageStoreAdminClient = + new MessageStoreAdminClient(backEndUrl, sessionCookie); + messageStoreAdminClient.addMessageStore(messageStore); + String mStoreName = messageStore.getAttributeValue(new QName(NAME)); + Assert.assertTrue(isMessageStoreDeployed(backEndUrl, sessionCookie, mStoreName), + "Message Store Deployment failed"); + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param messageProcessor + * @throws java.rmi.RemoteException + */ + public void addMessageProcessor(String backEndUrl, String sessionCookie, + OMElement messageProcessor) + throws Exception { + MessageProcessorClient messageProcessorClient = + new MessageProcessorClient(backEndUrl, sessionCookie); + messageProcessorClient.addMessageProcessor(messageProcessor); + String mProcessorName = messageProcessor.getAttributeValue(new QName(NAME)); + Assert.assertTrue(isMessageProcessorDeployed(backEndUrl, sessionCookie, mProcessorName), + "Message Processor deployment failed"); + } + + public void addSequenceTemplate(String backEndUrl, String sessionCookie, + OMElement sequenceTemplate) throws RemoteException { + SequenceTemplateAdminServiceClient sequenceTemplateAdminServiceClient = + new SequenceTemplateAdminServiceClient(backEndUrl, sessionCookie); + sequenceTemplateAdminServiceClient.addSequenceTemplate(sequenceTemplate); + String seqTmpName = sequenceTemplate.getAttributeValue(new QName(NAME)); + Assert.assertTrue(isSequenceTemplateDeployed(backEndUrl, sessionCookie, seqTmpName), + "Sequence Template deployment failed"); + + } + + public void addEndpointTemplate(String backEndUrl, String sessionCookie, + OMElement endpointTemplate) throws RemoteException { + EndpointTemplateAdminServiceClient endpointTemplateAdminServiceClient = + new EndpointTemplateAdminServiceClient(backEndUrl, sessionCookie); + endpointTemplateAdminServiceClient.addEndpointTemplate(endpointTemplate); + String endpointTmpName = endpointTemplate.getAttributeValue(new QName(NAME)); + Assert.assertTrue(isEndpointTemplateDeployed(backEndUrl, sessionCookie, endpointTmpName), + "Endpoint Template deployment failed"); + + } + + public void addAPI(String backEndUrl, String sessionCookie, + OMElement api) throws RemoteException, RestApiAdminAPIException { + RestApiAdminClient apiAdminClient = new RestApiAdminClient(backEndUrl, sessionCookie); + apiAdminClient.add(api); + String apiName = api.getAttributeValue(new QName(NAME)); + Assert.assertTrue(isApiDeployed(backEndUrl, sessionCookie, apiName), + "Rest Api deployment failed"); + } + + public void addPriorityExecutor(String backEndUrl, String sessionCookie, + OMElement priorityExecutor) + throws RemoteException { + PriorityMediationAdminClient priorityMediationAdminClient = + new PriorityMediationAdminClient(backEndUrl, sessionCookie); + String executorName = priorityExecutor.getAttributeValue(new QName(NAME)); + priorityMediationAdminClient.addPriorityMediator(executorName, priorityExecutor); + Assert.assertTrue(isPriorityExecutorDeployed(backEndUrl, sessionCookie, executorName), + "Priority Executor deployment failed"); + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param taskDescription + * @throws TaskManagementException + * @throws java.rmi.RemoteException + */ + public void addScheduleTask(String backEndUrl, String sessionCookie, OMElement taskDescription) + throws TaskManagementException, RemoteException { + TaskAdminClient taskAdminClient = new TaskAdminClient(backEndUrl, sessionCookie); + taskAdminClient.addTask(taskDescription); + Assert.assertTrue(isScheduleTaskDeployed(backEndUrl, sessionCookie + , taskDescription.getAttributeValue(new QName("name"))), + "ScheduleTask deployment failed" + ); + } + + /** + * Waiting for proxy to deploy + * + * @param backEndUrl + * @param sessionCookie + * @param proxyName + * @return + * @throws java.rmi.RemoteException + */ + public boolean isProxyDeployed(String backEndUrl, String sessionCookie, String proxyName) + throws RemoteException { + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Proxy deployment " + + proxyName); + + boolean isServiceDeployed = false; + ServiceAdminClient adminServiceService = new ServiceAdminClient(backEndUrl, sessionCookie); + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + if (adminServiceService.isServiceExists(proxyName)) { + isServiceDeployed = true; + log.info(proxyName + " Proxy Deployed in " + time + " millis"); + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException ignored) { + + } + } + + return isServiceDeployed; + + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param endpointName + * @return + * @throws EndpointAdminEndpointAdminException + * @throws java.rmi.RemoteException + */ + public boolean isEndpointDeployed(String backEndUrl, String sessionCookie, String endpointName) + throws EndpointAdminEndpointAdminException, RemoteException { + EndPointAdminClient endPointAdminClient = new EndPointAdminClient(backEndUrl, + sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Endpoint " + endpointName); + boolean isEndpointExist = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] endpoints = endPointAdminClient.getEndpointNames(); + if (endpoints != null && endpoints.length > 0) { + for (String endpoint : endpoints) { + + if (endpointName.equals(endpoint)) { + isEndpointExist = true; + log.info(endpointName + " Endpoint Found in " + time + " millis"); + break; + } + } + } + if (isEndpointExist) { + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isEndpointExist; + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param messageProcessorName + * @return + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public boolean isMessageProcessorDeployed(String backEndUrl, String sessionCookie, + String messageProcessorName) + throws SequenceEditorException, RemoteException { + MessageProcessorClient messageProcessorClient = + new MessageProcessorClient(backEndUrl, sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Message Processor " + + messageProcessorName); + boolean isMessageStoreExist = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] messageProcessors = messageProcessorClient.getMessageProcessorNames(); + if (messageProcessors != null && messageProcessors.length > 0) { + for (String mp : messageProcessors) { + + if (mp.equals(messageProcessorName)) { + isMessageStoreExist = true; + log.info(messageProcessorName + " Message Processor Found in " + time + + " millis"); + break; + } + } + } + if (isMessageStoreExist) { + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isMessageStoreExist; + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param sequenceName + * @return + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public boolean isSequenceDeployed(String backEndUrl, String sessionCookie, String sequenceName) + throws SequenceEditorException, RemoteException { + SequenceAdminServiceClient sequenceAdminServiceClient = + new SequenceAdminServiceClient(backEndUrl, + sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Sequence " + sequenceName); + boolean isSequenceExist = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] sequences = sequenceAdminServiceClient.getSequences(); + if (sequences != null && sequences.length > 0) { + for (String sequence : sequences) { + + if (sequence.equals(sequenceName)) { + isSequenceExist = true; + log.info(sequenceName + " Sequence Found in " + time + " millis"); + break; + } + } + } + if (isSequenceExist) { + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isSequenceExist; + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param messageStoreName + * @return + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public boolean isMessageStoreDeployed(String backEndUrl, String sessionCookie, + String messageStoreName) + throws SequenceEditorException, RemoteException { + MessageStoreAdminClient messageStoreAdminClient = + new MessageStoreAdminClient(backEndUrl, sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Message Store " + + messageStoreName); + boolean isMessageStoreExist = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] messageStores = messageStoreAdminClient.getMessageStores(); + if (messageStores != null && messageStores.length > 0) { + for (String ms : messageStores) { + + if (ms.equals(messageStoreName)) { + isMessageStoreExist = true; + log.info(messageStoreName + " Message Store Found in " + time + " millis"); + break; + } + } + } + if (isMessageStoreExist) { + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isMessageStoreExist; + } + + public boolean isSequenceTemplateDeployed(String backEndUrl, String sessionCookie, + String sequenceTemplateName) throws RemoteException { + SequenceTemplateAdminServiceClient sequenceTemplateAdminServiceClient = + new SequenceTemplateAdminServiceClient(backEndUrl, sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Sequence Template " + + sequenceTemplateName); + boolean isSequenceTmpFound = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] templates = sequenceTemplateAdminServiceClient.getSequenceTemplates(); + if (templates != null && templates.length > 0) { + for (String tmpl : templates) { + + if (tmpl.equals(sequenceTemplateName)) { + isSequenceTmpFound = true; + log.info(sequenceTemplateName + " Sequence Template Found in " + time + + " millis"); + break; + } + } + } + if (isSequenceTmpFound) { + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isSequenceTmpFound; + } + + public boolean isEndpointTemplateDeployed(String backEndUrl, String sessionCookie, + String endpointTemplateName) throws RemoteException { + EndpointTemplateAdminServiceClient endpointTemplateAdminServiceClient = + new EndpointTemplateAdminServiceClient(backEndUrl, sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Endpoint Template " + + endpointTemplateName); + boolean isEndpointTmpFound = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] templates = endpointTemplateAdminServiceClient.getEndpointTemplates(); + if (templates != null && templates.length > 0) { + for (String tmpl : templates) { + + if (tmpl.equals(endpointTemplateName)) { + isEndpointTmpFound = true; + log.info(endpointTemplateName + " Endpoint Template Found in " + time + + " millis"); + break; + } + } + } + if (isEndpointTmpFound) { + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isEndpointTmpFound; + } + + public boolean isApiDeployed(String backEndUrl, String sessionCookie, String apiName) + throws RemoteException, RestApiAdminAPIException { + RestApiAdminClient apiAdminClient = new RestApiAdminClient(backEndUrl, sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for API " + apiName); + boolean isApiFound = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] apiList = apiAdminClient.getApiNames(); + if (apiList != null && apiList.length > 0) { + for (String restApi : apiList) { + + if (restApi.equals(apiName)) { + isApiFound = true; + log.info(apiName + " API Found in " + time + " millis"); + break; + } + } + } + if (isApiFound) { + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isApiFound; + } + + public boolean isPriorityExecutorDeployed(String backEndUrl, String sessionCookie, + String executorName) + throws RemoteException { + PriorityMediationAdminClient priorityMediationAdminClient = + new PriorityMediationAdminClient(backEndUrl, sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Priority Executor " + + executorName); + boolean isExecutorFound = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] executorList = priorityMediationAdminClient.getExecutorList(); + if (executorList != null && executorList.length > 0) { + for (String executor : executorList) { + + if (executor.equals(executorName)) { + isExecutorFound = true; + log.info(executorName + " Priority Executor Found in " + time + " millis"); + break; + } + } + } + if (isExecutorFound) { + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isExecutorFound; + } + + /** + * Wait for task to to deploy and return true once it deploy + * + * @param backEndUrl + * @param sessionCookie + * @param taskName + * @return + * @throws java.rmi.RemoteException + * @throws TaskManagementException + */ + public boolean isScheduleTaskDeployed(String backEndUrl, String sessionCookie, String taskName) + throws RemoteException, TaskManagementException { + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Task deployment " + taskName); + + boolean isTaskDeployed = false; + TaskAdminClient taskAdminClient = new TaskAdminClient(backEndUrl, sessionCookie); + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + if (taskAdminClient.getScheduleTaskList().contains(taskName)) { + isTaskDeployed = true; + log.info(taskName + " Task Deployed in " + time + " millis"); + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException ignored) { + + } + } + + return isTaskDeployed; + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param proxyName + * @return + * @throws java.rmi.RemoteException + */ + public boolean isProxyServiceExist(String backEndUrl, String sessionCookie, String proxyName) + throws RemoteException { + ServiceAdminClient adminServiceService = new ServiceAdminClient(backEndUrl, sessionCookie); + return adminServiceService.isServiceExists(proxyName); + + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param localEntryName + * @return + * @throws LocalEntryAdminException + * @throws java.rmi.RemoteException + */ + public boolean isLocalEntryExist(String backEndUrl, String sessionCookie, String localEntryName) + throws LocalEntryAdminException, RemoteException { + LocalEntriesAdminClient localEntryAdminServiceClient = + new LocalEntriesAdminClient(backEndUrl, + sessionCookie); + String[] localEntries = localEntryAdminServiceClient.getEntryNames(); + if (localEntries == null || localEntries.length == 0) { + return false; + } + return ArrayUtils.contains(localEntries, localEntryName); + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param sequenceName + * @return + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public boolean isSequenceExist(String backEndUrl, String sessionCookie, String sequenceName) + throws SequenceEditorException, RemoteException { + SequenceAdminServiceClient sequenceAdminServiceClient = + new SequenceAdminServiceClient(backEndUrl, + sessionCookie); + String[] sequences = sequenceAdminServiceClient.getSequences(); + if (sequences == null || sequences.length == 0) { + return false; + } + return ArrayUtils.contains(sequences, sequenceName); + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param endpointName + * @return + * @throws EndpointAdminEndpointAdminException + * @throws java.rmi.RemoteException + */ + public boolean isEndpointExist(String backEndUrl, String sessionCookie, String endpointName) + throws EndpointAdminEndpointAdminException, RemoteException { + EndPointAdminClient endPointAdminClient = new EndPointAdminClient(backEndUrl, + sessionCookie); + String[] endpoints = endPointAdminClient.getEndpointNames(); + if (endpoints == null || endpoints.length == 0) { + return false; + } + return ArrayUtils.contains(endpoints, endpointName); + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param messageProcessor + * @return + * @throws java.rmi.RemoteException + */ + public boolean isMessageStoreExist(String backEndUrl, String sessionCookie, + String messageProcessor) throws RemoteException { + MessageStoreAdminClient messageStoreAdminClient = + new MessageStoreAdminClient(backEndUrl, sessionCookie); + return ArrayUtils.contains(messageStoreAdminClient.getMessageStores(), messageProcessor); + + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param messageProcessor + * @return + * @throws java.rmi.RemoteException + */ + public boolean isMessageProcessorExist(String backEndUrl, String sessionCookie, + String messageProcessor) throws RemoteException { + MessageProcessorClient messageProcessorClient = + new MessageProcessorClient(backEndUrl, sessionCookie); + return ArrayUtils + .contains(messageProcessorClient.getMessageProcessorNames(), messageProcessor); + + } + + public boolean isSequenceTemplateExist(String backEndUrl, String sessionCookie, + String sequenceTemplate) throws RemoteException { + SequenceTemplateAdminServiceClient sequenceTemplateAdminServiceClient = + new SequenceTemplateAdminServiceClient(backEndUrl, sessionCookie); + return ArrayUtils.contains(sequenceTemplateAdminServiceClient.getSequenceTemplates(), + sequenceTemplate); + + } + + public boolean isEndpointTemplateExist(String backEndUrl, String sessionCookie, + String endpointTemplate) throws RemoteException { + EndpointTemplateAdminServiceClient endpointTemplateAdminServiceClient = + new EndpointTemplateAdminServiceClient(backEndUrl, sessionCookie); + return ArrayUtils.contains(endpointTemplateAdminServiceClient.getEndpointTemplates(), + endpointTemplate); + + } + + public boolean isApiExist(String backEndUrl, String sessionCookie, String apiName) + throws RemoteException, RestApiAdminAPIException { + RestApiAdminClient apiAdminClient = new RestApiAdminClient(backEndUrl, sessionCookie); + return ArrayUtils.contains(apiAdminClient.getApiNames(), apiName); + + } + + public boolean isPriorityExecutorExist(String backEndUrl, String sessionCookie, + String priorityExecutorName) throws RemoteException { + PriorityMediationAdminClient priorityMediationAdminClient = + new PriorityMediationAdminClient(backEndUrl, sessionCookie); + return ArrayUtils + .contains(priorityMediationAdminClient.getExecutorList(), priorityExecutorName); + + } + + public boolean isScheduleTaskExist(String backEndUrl, String sessionCookie, String taskName) + throws RemoteException, TaskManagementException { + TaskAdminClient taskAdminClient = new TaskAdminClient(backEndUrl, sessionCookie); + return taskAdminClient.getScheduleTaskList().contains(taskName); + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param proxyServiceName + * @throws ProxyServiceAdminProxyAdminException + * @throws java.rmi.RemoteException + */ + public void deleteProxyService(String backEndUrl, String sessionCookie, String proxyServiceName) + throws ProxyServiceAdminProxyAdminException, RemoteException { + ProxyServiceAdminClient proxyAdmin = new ProxyServiceAdminClient(backEndUrl, sessionCookie); + proxyAdmin.deleteProxy(proxyServiceName); + Assert.assertTrue(isProxyUnDeployed(backEndUrl, sessionCookie, proxyServiceName), + "Proxy service undeployment failed"); + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param localEntryName + * @throws LocalEntryAdminException + * @throws java.rmi.RemoteException + */ + public void deleteLocalEntry(String backEndUrl, String sessionCookie, String localEntryName) + throws LocalEntryAdminException, RemoteException { + LocalEntriesAdminClient localEntryAdminServiceClient = + new LocalEntriesAdminClient(backEndUrl, + sessionCookie); + Assert.assertTrue(localEntryAdminServiceClient.deleteLocalEntry(localEntryName), + "LocalEntry Deletion failed"); + Assert.assertTrue(isLocalEntryUnDeployed(backEndUrl, sessionCookie, localEntryName), + "LocalEntry undeployment failed"); + + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param endpointName + * @throws EndpointAdminEndpointAdminException + * @throws java.rmi.RemoteException + */ + public void deleteEndpoint(String backEndUrl, String sessionCookie, String endpointName) + throws EndpointAdminEndpointAdminException, RemoteException { + EndPointAdminClient endPointAdminClient = new EndPointAdminClient(backEndUrl, + sessionCookie); + Assert.assertTrue(endPointAdminClient.deleteEndpoint(endpointName), + "Endpoint deletion failed"); + Assert.assertTrue(isEndpointUnDeployed(backEndUrl, sessionCookie, endpointName), + "Endpoint undeployment failed"); + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param sequenceName + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public void deleteSequence(String backEndUrl, String sessionCookie, String sequenceName) + throws SequenceEditorException, RemoteException { + SequenceAdminServiceClient sequenceAdminServiceClient = + new SequenceAdminServiceClient(backEndUrl, + sessionCookie); + sequenceAdminServiceClient.deleteSequence(sequenceName); + Assert.assertTrue(isSequenceUnDeployed(backEndUrl, sessionCookie, sequenceName), + "Sequence undeployment failed"); + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param messageStore + * @throws java.rmi.RemoteException + */ + public void deleteMessageStore(String backEndUrl, String sessionCookie, String messageStore) + throws RemoteException, SequenceEditorException { + MessageStoreAdminClient messageStoreAdminClient = + new MessageStoreAdminClient(backEndUrl, sessionCookie); + messageStoreAdminClient.deleteMessageStore(messageStore); + Assert.assertTrue(isMessageStoreUnDeployed(backEndUrl, sessionCookie, messageStore), + "Message Store undeployment failed"); + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param messageProcessor + * @throws java.rmi.RemoteException + */ + public void deleteMessageProcessor(String backEndUrl, String sessionCookie, + String messageProcessor) + throws RemoteException, SequenceEditorException { + MessageProcessorClient messageProcessorClient = + new MessageProcessorClient(backEndUrl, sessionCookie); + messageProcessorClient.deleteMessageProcessor(messageProcessor); + Assert.assertTrue(isMessageProcessorUnDeployed(backEndUrl, sessionCookie, messageProcessor), + "Message Processor undeployment failed"); + } + + public void deleteEndpointTemplate(String backEndUrl, String sessionCookie, + String endpointTemplate) + throws RemoteException, SequenceEditorException, EndpointAdminEndpointAdminException { + + EndpointTemplateAdminServiceClient endpointTemplateAdminServiceClient = + new EndpointTemplateAdminServiceClient(backEndUrl, sessionCookie); + endpointTemplateAdminServiceClient.deleteEndpointTemplate(endpointTemplate); + Assert.assertTrue(isEndpointTemplateUnDeployed(backEndUrl, sessionCookie, endpointTemplate), + "Endpoint Template undeployment failed"); + } + + public void deleteSequenceTemplate(String backEndUrl, String sessionCookie, + String sequenceTemplateName) + throws RemoteException, SequenceEditorException, EndpointAdminEndpointAdminException { + SequenceTemplateAdminServiceClient sequenceTemplateAdminServiceClient = + new SequenceTemplateAdminServiceClient(backEndUrl, sessionCookie); + sequenceTemplateAdminServiceClient.deleteTemplate(sequenceTemplateName); + Assert.assertTrue( + isSequenceTemplateUnDeployed(backEndUrl, sessionCookie, sequenceTemplateName), + "Sequence Template undeployment failed"); + } + + public void deleteApi(String backEndUrl, String sessionCookie, String apiName) + throws RemoteException, RestApiAdminAPIException { + RestApiAdminClient apiAdminClient = new RestApiAdminClient(backEndUrl, sessionCookie); + apiAdminClient.deleteApi(apiName); + Assert.assertTrue(isApiUnDeployed(backEndUrl, sessionCookie, apiName), + "API undeployment failed"); + } + + public void deletePriorityExecutor(String backEndUrl, String sessionCookie, String executorName) + throws RemoteException { + PriorityMediationAdminClient priorityMediationAdminClient = + new PriorityMediationAdminClient(backEndUrl, sessionCookie); + priorityMediationAdminClient.remove(executorName); + Assert.assertTrue(isPriorityExecutorUnDeployed(backEndUrl, sessionCookie, executorName), + "Priority Executor undeployment failed"); + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param taskName name of the ScheduleTask + * @param group group of the ScheduleTask + * @throws TaskManagementException + * @throws java.rmi.RemoteException + */ + public void deleteScheduleTask(String backEndUrl, String sessionCookie, String taskName, + String group) + throws TaskManagementException, RemoteException { + TaskAdminClient taskAdminClient = new TaskAdminClient(backEndUrl, sessionCookie); + taskAdminClient.deleteTask(taskName, group); + Assert.assertTrue(isScheduleTaskUnDeployed(backEndUrl, sessionCookie, taskName), + "ScheduleTask deployment failed"); + + } + + /** + * waiting for proxy to undeploy + * + * @param backEndUrl + * @param sessionCookie + * @param proxyName + * @return + * @throws java.rmi.RemoteException + */ + + public boolean isProxyUnDeployed(String backEndUrl, String sessionCookie, String proxyName) + throws RemoteException { + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Proxy undeployment"); + ServiceAdminClient adminServiceService = new ServiceAdminClient(backEndUrl, sessionCookie); + boolean isServiceDeleted = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + if (!adminServiceService.isServiceExists(proxyName)) { + isServiceDeleted = true; + log.info(proxyName + " Proxy undeployed in " + time + " millis"); + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + + } + } + return isServiceDeleted; + } + + public boolean isMessageStoreUnDeployed(String backEndUrl, String sessionCookie, + String messageStoreName) + throws SequenceEditorException, RemoteException { + MessageStoreAdminClient messageStoreAdminClient = + new MessageStoreAdminClient(backEndUrl, sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Undeployment Message Store " + + messageStoreName); + boolean isMessageStoreDeleted = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] mStores = messageStoreAdminClient.getMessageStores(); + if (!ArrayUtils.contains(mStores, messageStoreName)) { + isMessageStoreDeleted = true; + break; + } + + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isMessageStoreDeleted; + } + + public boolean isMessageProcessorUnDeployed(String backEndUrl, String sessionCookie, + String messageProcessorName) + throws SequenceEditorException, RemoteException { + MessageProcessorClient messageProcessorClient = + new MessageProcessorClient(backEndUrl, sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + + " millis for Undeployment Message Processor " + messageProcessorName); + boolean isMessageProcessorDeleted = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] mProcessors = messageProcessorClient.getMessageProcessorNames(); + if (!ArrayUtils.contains(mProcessors, messageProcessorName)) { + isMessageProcessorDeleted = true; + break; + } + + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isMessageProcessorDeleted; + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param localEntryName + * @return + * @throws LocalEntryAdminException + * @throws java.rmi.RemoteException + */ + public boolean isLocalEntryDeployed(String backEndUrl, String sessionCookie, + String localEntryName) + throws LocalEntryAdminException, RemoteException { + LocalEntriesAdminClient localEntryAdminServiceClient = + new LocalEntriesAdminClient(backEndUrl, + sessionCookie); + log.info( + "waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for LocalEntry " + localEntryName); + boolean isLocalEntryExist = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] localEntries = localEntryAdminServiceClient.getEntryNames(); + if (localEntries != null && localEntries.length > 0) { + for (String localEntry : localEntries) { + + if (localEntryName.equals(localEntry)) { + isLocalEntryExist = true; + log.info(localEntryName + " LocalEntry Found in " + time + " millis"); + break; + } + } + } + if (isLocalEntryExist) { + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isLocalEntryExist; + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param localEntryName + * @return + * @throws LocalEntryAdminException + * @throws java.rmi.RemoteException + */ + public boolean isLocalEntryUnDeployed(String backEndUrl, String sessionCookie, + String localEntryName) + throws LocalEntryAdminException, RemoteException { + LocalEntriesAdminClient localEntryAdminServiceClient = + new LocalEntriesAdminClient(backEndUrl, + sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Undeployment LocalEntry " + + localEntryName); + boolean isLocalEntryUnDeployed = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] localEntries = localEntryAdminServiceClient.getEntryNames(); + if (!ArrayUtils.contains(localEntries, localEntryName)) { + isLocalEntryUnDeployed = true; + break; + } + + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isLocalEntryUnDeployed; + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param sequenceName + * @return + * @throws SequenceEditorException + * @throws java.rmi.RemoteException + */ + public boolean isSequenceUnDeployed(String backEndUrl, String sessionCookie, + String sequenceName) + throws SequenceEditorException, RemoteException { + SequenceAdminServiceClient sequenceAdminServiceClient = + new SequenceAdminServiceClient(backEndUrl, + sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Undeployment Sequence " + + sequenceName); + boolean isSequenceUnDeployed = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] sequences = sequenceAdminServiceClient.getSequences(); + if (!ArrayUtils.contains(sequences, sequenceName)) { + isSequenceUnDeployed = true; + break; + } + + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isSequenceUnDeployed; + } + + /** + * @param backEndUrl + * @param sessionCookie + * @param endpointName + * @return + * @throws EndpointAdminEndpointAdminException + * @throws java.rmi.RemoteException + */ + public boolean isEndpointUnDeployed(String backEndUrl, String sessionCookie, + String endpointName) + throws EndpointAdminEndpointAdminException, RemoteException { + EndPointAdminClient endPointAdminClient = new EndPointAdminClient(backEndUrl, + sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Undeployment Endpoint " + + endpointName); + boolean isEndpointUnDeployed = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] endpoints = endPointAdminClient.getEndpointNames(); + if (!ArrayUtils.contains(endpoints, endpointName)) { + isEndpointUnDeployed = true; + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isEndpointUnDeployed; + } + + public boolean isEndpointTemplateUnDeployed(String backEndUrl, String sessionCookie, + String endpointTemplateName) + throws EndpointAdminEndpointAdminException, RemoteException { + EndpointTemplateAdminServiceClient endpointTemplateAdminServiceClient = + new EndpointTemplateAdminServiceClient(backEndUrl, sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + + " millis for Undeployment Endpoint Template " + endpointTemplateName); + boolean isEndpointTemplateUnDeployed = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] endpointTemplates = endpointTemplateAdminServiceClient.getEndpointTemplates(); + if (!ArrayUtils.contains(endpointTemplates, endpointTemplateName)) { + isEndpointTemplateUnDeployed = true; + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isEndpointTemplateUnDeployed; + } + + public boolean isSequenceTemplateUnDeployed(String backEndUrl, String sessionCookie, + String sequenceTemplateName) + throws EndpointAdminEndpointAdminException, RemoteException { + SequenceTemplateAdminServiceClient sequenceTemplateAdminServiceClient = + new SequenceTemplateAdminServiceClient(backEndUrl, sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + + " millis for Undeployment Sequence Template " + sequenceTemplateName); + boolean isSequenceTemplateUnDeployed = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] sequenceTemplates = sequenceTemplateAdminServiceClient.getSequenceTemplates(); + if (!ArrayUtils.contains(sequenceTemplates, sequenceTemplateName)) { + isSequenceTemplateUnDeployed = true; + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isSequenceTemplateUnDeployed; + } + + public boolean isApiUnDeployed(String backEndUrl, String sessionCookie, + String apiName) + throws RemoteException, RestApiAdminAPIException { + RestApiAdminClient apiAdminClient = new RestApiAdminClient(backEndUrl, sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Undeployment API " + apiName); + boolean isApiUnDeployed = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] apiList = apiAdminClient.getApiNames(); + if (!ArrayUtils.contains(apiList, apiName)) { + isApiUnDeployed = true; + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isApiUnDeployed; + } + + public boolean isPriorityExecutorUnDeployed(String backEndUrl, String sessionCookie, + String executorName) + throws RemoteException { + PriorityMediationAdminClient priorityMediationAdminClient = + new PriorityMediationAdminClient(backEndUrl, sessionCookie); + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + + " millis for Undeployment Priority Executor " + executorName); + boolean isExecutorUnDeployed = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + String[] executorList = priorityMediationAdminClient.getExecutorList(); + if (!ArrayUtils.contains(executorList, executorName)) { + isExecutorUnDeployed = true; + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + //ignore + } + } + return isExecutorUnDeployed; + } + + /** + * wait for task to undeploy and return true once it is undeployed + * + * @param backEndUrl + * @param sessionCookie + * @param taskName + * @return + * @throws java.rmi.RemoteException + * @throws TaskManagementException + */ + public boolean isScheduleTaskUnDeployed(String backEndUrl, String sessionCookie, + String taskName) + throws RemoteException, TaskManagementException { + log.info("waiting " + SERVICE_DEPLOYMENT_DELAY + " millis for Task Undeployment " + + taskName); + + boolean isTaskUnDeployed = false; + TaskAdminClient taskAdminClient = new TaskAdminClient(backEndUrl, sessionCookie); + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + SERVICE_DEPLOYMENT_DELAY) { + if (!taskAdminClient.getScheduleTaskList().contains(taskName)) { + isTaskUnDeployed = true; + log.info(taskName + " Task UnDeployed in " + time + " millis"); + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException ignored) { + + } + } + + return isTaskUnDeployed; + } + + /** + * @param synapseConfig + * @param backendURL + * @param sessionCookie + * @throws LocalEntryAdminException + * @throws java.rmi.RemoteException + * @throws EndpointAdminEndpointAdminException + * @throws SequenceEditorException + */ + public void verifySynapseDeployment(OMElement synapseConfig, String backendURL, + String sessionCookie) + throws LocalEntryAdminException, RemoteException, EndpointAdminEndpointAdminException, + SequenceEditorException, RestApiAdminAPIException { + Iterator localEntries = synapseConfig.getChildrenWithLocalName(LOCAL_ENTRY); + while (localEntries.hasNext()) { + String le = localEntries.next().getAttributeValue(new QName(KEY)); + Assert.assertTrue(isLocalEntryDeployed(backendURL, sessionCookie, le), + le + " LocalEntry deployment not found or time out"); + } + + Iterator endpoints = synapseConfig.getChildrenWithLocalName(ENDPOINT); + while (endpoints.hasNext()) { + String ep = endpoints.next().getAttributeValue(new QName(NAME)); + Assert.assertTrue(isEndpointDeployed(backendURL, sessionCookie, ep), + ep + " Endpoint deployment not found or time out"); + } + + Iterator sequences = synapseConfig.getChildrenWithLocalName(SEQUENCE); + while (sequences.hasNext()) { + String sqn = sequences.next().getAttributeValue(new QName(NAME)); + Assert.assertTrue(isSequenceDeployed(backendURL, sessionCookie, sqn), + sqn + " Sequence deployment not found or time out"); + } + + Iterator proxies = synapseConfig.getChildrenWithLocalName(PROXY); + while (proxies.hasNext()) { + String proxy = proxies.next().getAttributeValue(new QName(NAME)); + Assert.assertTrue(isProxyDeployed(backendURL, sessionCookie, proxy), + proxy + " Proxy Deployment not found or time out"); + } + + Iterator messageStores = synapseConfig.getChildrenWithLocalName(MESSAGE_STORE); + while (messageStores.hasNext()) { + String mStore = messageStores.next().getAttributeValue(new QName(NAME)); + Assert.assertTrue(isMessageStoreDeployed(backendURL, sessionCookie, mStore), + mStore + " Message Store Deployment not found or time out"); + } + + Iterator messageProcessor = + synapseConfig.getChildrenWithLocalName(MESSAGE_PROCESSOR); + while (messageProcessor.hasNext()) { + String mProcessor = messageProcessor.next().getAttributeValue(new QName(NAME)); + Assert.assertTrue(isMessageProcessorDeployed(backendURL, sessionCookie, mProcessor), + mProcessor + " Message Processor Deployment not found or time out"); + } + + Iterator templates = synapseConfig.getChildrenWithLocalName(TEMPLATE); + while (templates.hasNext()) { + OMElement template = templates.next(); + String templateName = template.getAttributeValue(new QName(NAME)); + if (template.getFirstChildWithName( + new QName(template.getNamespace().getNamespaceURI(), SEQUENCE)) != null) { + Assert.assertTrue( + isSequenceTemplateDeployed(backendURL, sessionCookie, templateName), + templateName + " Sequence Template Deployment not found or time out"); + } else { + + Assert.assertTrue( + isEndpointTemplateDeployed(backendURL, sessionCookie, templateName), + templateName + " Endpoint Template Deployment not found or time out"); + } + log.info("Template Uploaded"); + } + + Iterator apiList = synapseConfig.getChildrenWithLocalName(API); + while (apiList.hasNext()) { + OMElement api = apiList.next(); + String apiName = api.getAttributeValue(new QName(NAME)); + String version = api.getAttributeValue(new QName(VERSION)); + if(version != null && !version.equals("")){ + apiName = apiName + ":v" + version; + } + Assert.assertTrue(isApiDeployed(backendURL, sessionCookie, apiName), + apiName + " API Deployment not found or time out"); + } + + Iterator executorList = + synapseConfig.getChildrenWithLocalName(PRIORITY_EXECUTOR); + while (executorList.hasNext()) { + String executorName = executorList.next().getAttributeValue(new QName(NAME)); + Assert.assertTrue(isPriorityExecutorDeployed(backendURL, sessionCookie, executorName), + executorName + " Priority Executor Deployment not found or time out"); + } + + } + + public void deleteArtifact(OMElement synapseConfig, String backendURL, + String sessionCookie) + throws Exception { + ProxyServiceAdminClient proxyAdmin = new ProxyServiceAdminClient(backendURL, sessionCookie); + EndPointAdminClient endPointAdminClient = + new EndPointAdminClient(backendURL, sessionCookie); + SequenceAdminServiceClient sequenceAdminClient = + new SequenceAdminServiceClient(backendURL, sessionCookie); + LocalEntriesAdminClient localEntryAdminServiceClient = + new LocalEntriesAdminClient(backendURL, sessionCookie); + MessageProcessorClient messageProcessorClient = + new MessageProcessorClient(backendURL, sessionCookie); + MessageStoreAdminClient messageStoreAdminClient = + new MessageStoreAdminClient(backendURL, sessionCookie); + ServiceAdminClient adminServiceService = new ServiceAdminClient(backendURL, sessionCookie); + RestApiAdminClient apiAdminClient = new RestApiAdminClient(backendURL, sessionCookie); + PriorityMediationAdminClient priorityMediationAdminClient = + new PriorityMediationAdminClient(backendURL, sessionCookie); + + Iterator localEntries = synapseConfig.getChildrenWithLocalName(LOCAL_ENTRY); + while (localEntries.hasNext()) { + OMElement localEntry = localEntries.next(); + String le = localEntry.getAttributeValue(new QName(KEY)); + if (ArrayUtils.contains(localEntryAdminServiceClient.getEntryNames(), le)) { + Assert.assertTrue(localEntryAdminServiceClient.deleteLocalEntry(le), + le + " Local Entry deletion failed"); + Assert.assertTrue(isLocalEntryUnDeployed(backendURL, sessionCookie, le), + le + " Local Entry undeployment failed"); + } + } + + Iterator endpoints = synapseConfig.getChildrenWithLocalName(ENDPOINT); + while (endpoints.hasNext()) { + OMElement endpoint = endpoints.next(); + String ep = endpoint.getAttributeValue(new QName(NAME)); + if (ArrayUtils.contains(endPointAdminClient.getEndpointNames(), ep)) { + Assert.assertTrue(endPointAdminClient.deleteEndpoint(ep), + ep + " Endpoint deletion failed"); + Assert.assertTrue(isEndpointUnDeployed(backendURL, sessionCookie, ep), + ep + " Endpoint undeployment failed"); + } + } + + Iterator sequences = synapseConfig.getChildrenWithLocalName(SEQUENCE); + while (sequences.hasNext()) { + OMElement sequence = sequences.next(); + String sqn = sequence.getAttributeValue(new QName(NAME)); + if (sqn.equalsIgnoreCase("fault") || sqn.equalsIgnoreCase("main")) { + continue; + } + if (ArrayUtils.contains(sequenceAdminClient.getSequences(), sqn)) { + sequenceAdminClient.deleteSequence(sqn); + Assert.assertTrue(isSequenceUnDeployed(backendURL, sessionCookie, sqn), + sqn + " Sequence undeployment failed"); + } + + } + + Iterator proxies = synapseConfig.getChildrenWithLocalName(PROXY); + while (proxies.hasNext()) { + OMElement proxy = proxies.next(); + String proxyName = proxy.getAttributeValue(new QName(NAME)); + if (adminServiceService.isServiceExists(proxyName)) { + proxyAdmin.deleteProxy(proxyName); + Assert.assertTrue(isProxyUnDeployed(backendURL, sessionCookie, proxyName), + proxyName + " Undeployment failed"); + } + } + + Iterator messageStores = synapseConfig.getChildrenWithLocalName(MESSAGE_STORE); + while (messageStores.hasNext()) { + OMElement messageStore = messageStores.next(); + String mStore = messageStore.getAttributeValue(new QName(NAME)); + if (ArrayUtils.contains(messageStoreAdminClient.getMessageStores(), mStore)) { + messageStoreAdminClient.deleteMessageStore(mStore); + Assert.assertTrue(isMessageStoreUnDeployed(backendURL, sessionCookie, mStore), + mStore + " Message Store undeployment failed"); + } + } + + Iterator messageProcessors = + synapseConfig.getChildrenWithLocalName(MESSAGE_PROCESSOR); + while (messageProcessors.hasNext()) { + OMElement messageProcessor = messageProcessors.next(); + String mProcessor = messageProcessor.getAttributeValue(new QName(NAME)); + if (ArrayUtils + .contains(messageProcessorClient.getMessageProcessorNames(), mProcessor)) { + messageProcessorClient.deleteMessageProcessor(mProcessor); + Assert.assertTrue( + isMessageProcessorUnDeployed(backendURL, sessionCookie, mProcessor) + , mProcessor + " Message Processor undeployment failed"); + } + } + + Iterator templates = synapseConfig.getChildrenWithLocalName(TEMPLATE); + while (templates.hasNext()) { + OMElement template = templates.next(); + String templateName = template.getAttributeValue(new QName(NAME)); + if (template.getFirstChildWithName( + new QName(template.getNamespace().getNamespaceURI(), SEQUENCE)) != null) { + deleteSequenceTemplate(backendURL, sessionCookie, templateName); + + } else { + deleteEndpointTemplate(backendURL, sessionCookie, templateName); + } + log.info("Template UnUploaded"); + } + + Iterator apiList = synapseConfig.getChildrenWithLocalName(API); + while (apiList.hasNext()) { + OMElement api = apiList.next(); + String apiName = api.getAttributeValue(new QName(NAME)); + if (ArrayUtils.contains(apiAdminClient.getApiNames(), apiName)) { + apiAdminClient.deleteApi(apiName); + Assert.assertTrue(isApiUnDeployed(backendURL, sessionCookie, apiName) + , apiName + " API undeployment failed"); + } + } + + Iterator executorList = + synapseConfig.getChildrenWithLocalName(PRIORITY_EXECUTOR); + while (executorList.hasNext()) { + OMElement executor = executorList.next(); + String executorName = executor.getAttributeValue(new QName(NAME)); + if (ArrayUtils.contains(priorityMediationAdminClient.getExecutorList(), executorName)) { + priorityMediationAdminClient.remove(executorName); + Assert.assertTrue( + isPriorityExecutorUnDeployed(backendURL, sessionCookie, executorName) + , executorName + " Priority Executor undeployment failed"); + } + } + + log.info("Synapse configuration unDeployed"); + + } + + public void deploySynapseArtifactsFromFileSystem(String directoryPath, String backendURL, + String sessionCookie) throws Exception { + + File[] fileList = new File(directoryPath).listFiles(); + + HashMap fileStructure = new HashMap(); + + for (int x = 0; x <= fileList.length - 1; x++) { + File FileName = fileList[x]; + fileStructure.put(FileName.getName(), FileName.listFiles()); + } + + for (Map.Entry stringEntry : fileStructure.entrySet()) { + + Map.Entry entry = (Map.Entry) stringEntry; + File[] fileArr = (File[]) entry.getValue(); + + if (entry.getKey().equals("api")) { + + OMElement apiOmElement; + + for (File aFileArr : fileArr) { + //deploying the api to esb + String filePathArr[] = aFileArr.getAbsolutePath() + .split(TestConfigurationProvider + .getResourceLocation()); + apiOmElement = loadResource(filePathArr[1]); + + String apiName = apiOmElement.getAttributeValue(new QName("name")); + + if (isApiExist(backendURL, sessionCookie, apiName)) { + deleteApi(backendURL, sessionCookie, apiName); + } + addAPI(backendURL, sessionCookie, apiOmElement); + Assert.assertTrue(isApiDeployed(backendURL, sessionCookie, apiName), + "api " + apiName + "deployment failure"); + } + } else if (entry.getKey().equals("endpoints")) { + OMElement endpointOmElement; + + for (File aFileArr : fileArr) { + //deploying the endpoints to esb + String filePathArr[] = aFileArr.getAbsolutePath() + .split(TestConfigurationProvider + .getResourceLocation()); + endpointOmElement = loadResource(filePathArr[1]); + + String endpointName = endpointOmElement.getAttributeValue(new QName("name")); + + if (isEndpointExist(backendURL, sessionCookie, endpointName)) { + deleteEndpoint(backendURL, sessionCookie, endpointName); + } + addEndpoint(backendURL, sessionCookie, endpointOmElement); + Assert.assertTrue(isEndpointDeployed(backendURL, sessionCookie, endpointName), + "endpoint " + endpointName + "deployment failure"); + } + } else if (entry.getKey().equals("priority-executors")) { + OMElement priorityExecutorsOmElement; + + for (File aFileArr : fileArr) { + //deploying the priority-executors to esb + String filePathArr[] = aFileArr.getAbsolutePath() + .split(TestConfigurationProvider + .getResourceLocation()); + priorityExecutorsOmElement = loadResource(filePathArr[1]); + + String proxyExecutorName = + priorityExecutorsOmElement.getAttributeValue(new QName("name")); + + if (isPriorityExecutorExist(backendURL, sessionCookie, proxyExecutorName)) { + deletePriorityExecutor(backendURL, sessionCookie, proxyExecutorName); + } + addPriorityExecutor(backendURL, sessionCookie, priorityExecutorsOmElement); + Assert.assertTrue(isPriorityExecutorDeployed(backendURL, sessionCookie, + proxyExecutorName), + "priority-executor " + proxyExecutorName + + "deployment failure"); + } + + } else if (entry.getKey().equals("sequences")) { + OMElement sequencesOmElement; + + for (File aFileArr : fileArr) { + //deploying the sequences to esb + String filePathArr[] = aFileArr.getAbsolutePath() + .split(TestConfigurationProvider + .getResourceLocation()); + sequencesOmElement = loadResource(filePathArr[1]); + + String sequenceName = sequencesOmElement.getAttributeValue(new QName("name")); + + if (isSequenceExist(backendURL, sessionCookie, sequenceName)) { + deleteSequence(backendURL, sessionCookie, sequenceName); + } + addSequence(backendURL, sessionCookie, sequencesOmElement); + Assert.assertTrue(isSequenceDeployed(backendURL, sessionCookie, sequenceName), + "sequence " + sequenceName + "deployment failure"); + } + } else if (entry.getKey().equals("proxy-services")) { + OMElement proxyServicesOmElement; + + for (File aFileArr : fileArr) { + //deploying the proxy-services to esb + String filePathArr[] = aFileArr.getAbsolutePath() + .split(TestConfigurationProvider + .getResourceLocation()); + proxyServicesOmElement = loadResource(filePathArr[1]); + + String proxyServiceName = + proxyServicesOmElement.getAttributeValue(new QName("name")); + + if (isProxyServiceExist(backendURL, sessionCookie, proxyServiceName)) { + deleteProxyService(backendURL, sessionCookie, proxyServiceName); + } + addProxyService(backendURL, sessionCookie, proxyServicesOmElement); + Assert.assertTrue(isProxyDeployed(backendURL, sessionCookie, proxyServiceName), + "proxy-service " + proxyServiceName + "deployment failure"); + } + } else if (entry.getKey().equals("local-entries")) { + OMElement localEntriesOmElement; + + for (File aFileArr : fileArr) { + //deploying the local-entries to esb + String filePathArr[] = aFileArr.getAbsolutePath() + .split(TestConfigurationProvider + .getResourceLocation()); + localEntriesOmElement = loadResource(filePathArr[1]); + + String localEntryKey = + localEntriesOmElement.getAttributeValue(new QName("key")); + + if (isLocalEntryExist(backendURL, sessionCookie, localEntryKey)) { + deleteLocalEntry(backendURL, sessionCookie, localEntryKey); + } + addLocalEntry(backendURL, sessionCookie, localEntriesOmElement); + Assert.assertTrue( + isLocalEntryDeployed(backendURL, sessionCookie, localEntryKey), + "local-entry " + localEntryKey + "deployment failure"); + } + } else if (entry.getKey().equals("tasks")) { + OMElement taskOmElement; + + for (File aFileArr : fileArr) { + //deploying the tasks to esb + String filePathArr[] = aFileArr.getAbsolutePath() + .split(TestConfigurationProvider + .getResourceLocation()); + taskOmElement = loadResource(filePathArr[1]); + + if (taskOmElement.getNamespace().getPrefix().equals("")) { + + OMFactory fac = OMAbstractFactory.getOMFactory(); + OMNamespace omNs = fac.createOMNamespace( + "http://www.wso2.org/products/wso2commons/tasks", "task"); + taskOmElement.setNamespace(omNs); + + Iterator it = taskOmElement.getChildElements(); + + while (it.hasNext()) { + ((OMElement) it.next()).setNamespace(omNs); + } + } + + String taskName = taskOmElement.getAttributeValue(new QName("name")); + String taskGroup = taskOmElement.getAttributeValue(new QName("group")); + + if (isScheduleTaskExist(backendURL, sessionCookie, taskName)) { + deleteScheduleTask(backendURL, sessionCookie, taskName, taskGroup); + } + addScheduleTask(backendURL, sessionCookie, taskOmElement); + Assert.assertTrue(isScheduleTaskDeployed(backendURL, sessionCookie, taskName), + "task " + taskName + "deployment failure"); + + } + } else { + log.info(entry.getKey() + " was not deployed"); + } + } + } +} diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/esb/EndpointGenerator.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/esb/EndpointGenerator.java new file mode 100644 index 0000000000..3128484575 --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/esb/EndpointGenerator.java @@ -0,0 +1,44 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.test.utils.esb; + +import org.wso2.carbon.automation.engine.context.AutomationContext; +import org.wso2.carbon.automation.engine.context.TestUserMode; + +import javax.xml.xpath.XPathExpressionException; + +public class EndpointGenerator { + public static String getBackEndServiceEndpointUrl(String serviceName) + throws XPathExpressionException { + String backEndServiceUrl; + if (TestConfigurationProvider.isIntegration()) { + // AutomationContext axis2 = new AutomationContext("AXIS2", TestUserMode.SUPER_TENANT_ADMIN); + // backEndServiceUrl = axis2.getContextUrls().getServiceUrl(); + backEndServiceUrl = "http://localhost:9000/services"; + } else { + AutomationContext appServer = + new AutomationContext("AS", TestUserMode.SUPER_TENANT_ADMIN); + backEndServiceUrl = appServer.getContextUrls().getServiceUrl(); + } + + return (backEndServiceUrl + "/" + serviceName); + } + +} + diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/esb/ServiceDeploymentUtil.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/esb/ServiceDeploymentUtil.java new file mode 100644 index 0000000000..e5ea28dcaf --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/esb/ServiceDeploymentUtil.java @@ -0,0 +1,212 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.test.utils.esb; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.Assert; +import org.wso2.am.admin.clients.aar.services.AARServiceUploaderClient; +import org.wso2.am.admin.clients.service.mgt.ServiceAdminClient; +import org.wso2.carbon.authenticator.stub.LoginAuthenticationExceptionException; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.rmi.RemoteException; +import java.util.Calendar; + +public class ServiceDeploymentUtil { + private Log log = LogFactory.getLog(ServiceDeploymentUtil.class); + + public void deployArrService(String backEndUrl, String sessionCookie, String serviceName, + String serviceFilePath, int deploymentDelay) + throws RemoteException, MalformedURLException, LoginAuthenticationExceptionException, + org.wso2.carbon.aarservices.stub.ExceptionException { + + AARServiceUploaderClient adminServiceAARServiceUploader = + new AARServiceUploaderClient(backEndUrl, sessionCookie); + ServiceAdminClient adminServiceService = new ServiceAdminClient(backEndUrl, sessionCookie); + if (adminServiceService.isServiceExists(serviceName)) { + adminServiceService.deleteService(new String[] { serviceName }); + isServiceUnDeployed(backEndUrl, sessionCookie, serviceName, deploymentDelay); + } + + adminServiceAARServiceUploader.uploadAARFile(serviceName + ".aar", serviceFilePath, ""); + Assert.assertTrue(isServiceDeployed(backEndUrl, sessionCookie, serviceName, deploymentDelay) + , serviceName + " deployment failed in Application Server"); + } + + public void unDeployArrService(String backEndUrl, String sessionCookie, String serviceName, + int deploymentDelay) + throws RemoteException, MalformedURLException, LoginAuthenticationExceptionException { + ServiceAdminClient adminServiceService = new ServiceAdminClient(backEndUrl, sessionCookie); + if (adminServiceService.isServiceExists(serviceName)) { + adminServiceService.deleteService(new String[] { serviceName }); + isServiceUnDeployed(backEndUrl, sessionCookie, serviceName, deploymentDelay); + } + } + + public boolean isServiceDeployed(String backEndUrl, String sessionCookie, String serviceName, + int deploymentDelay) + throws RemoteException { + log.info("waiting " + deploymentDelay + " millis for Service deployment " + serviceName); + + boolean isServiceDeployed = false; + ServiceAdminClient adminServiceService = new ServiceAdminClient(backEndUrl, sessionCookie); + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + deploymentDelay) { + if (adminServiceService.isServiceExists(serviceName)) { + isServiceDeployed = true; + log.info(serviceName + " Service Deployed in " + time + " millis"); + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException ignored) { + + } + } + + return isServiceDeployed; + + } + + public boolean isServiceUnDeployed(String backEndUrl, String sessionCookie, String serviceName, + int deploymentDelay) + throws RemoteException { + log.info("waiting " + deploymentDelay + " millis for Service undeployment"); + ServiceAdminClient adminServiceService = new ServiceAdminClient(backEndUrl, sessionCookie); + boolean isServiceDeleted = false; + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + deploymentDelay) { + if (!adminServiceService.isServiceExists(serviceName)) { + isServiceDeleted = true; + log.info(serviceName + " Service undeployed in " + time + " millis"); + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + + } + } + return isServiceDeleted; + } + + public boolean isServiceWSDlExist(String serviceUrl, long synchronizingDelay) + throws Exception, IOException { + + log.info("waiting " + synchronizingDelay + " millis for Proxy deployment in worker"); + + boolean isServiceDeployed = false; + + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + synchronizingDelay) { + if (isWSDLAvailable(serviceUrl)) { + isServiceDeployed = true; + log.info("Proxy Deployed in " + time + " millis in worker"); + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException ignored) { + + } + } + + return isServiceDeployed; + + } + + public boolean isServiceWSDlNotExist(String serviceUrl, long synchronizingDelay) + throws Exception, IOException { + + log.info("waiting " + synchronizingDelay + " millis for Proxy undeployment in worker"); + + boolean isServiceUnDeployed = false; + + Calendar startTime = Calendar.getInstance(); + long time; + while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < + synchronizingDelay) { + if (!isWSDLAvailable(serviceUrl)) { + isServiceUnDeployed = true; + log.info("Proxy UnDeployed in " + time + " millis in worker"); + break; + } + try { + Thread.sleep(500); + } catch (InterruptedException ignored) { + + } + } + + return isServiceUnDeployed; + + } + + public boolean isWSDLAvailable(String serviceEndpoint) throws IOException { + URL url = new URL(serviceEndpoint + "?wsdl"); + boolean isWsdlExist = false; + BufferedReader rd = null; + HttpURLConnection conn; + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + conn.setDoOutput(true); + conn.setReadTimeout(6000); + try { + conn.connect(); + + // Get the response + StringBuilder sb = new StringBuilder(); + + rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line; + while ((line = rd.readLine()) != null) { + sb.append(line); + if (sb.toString().contains("wsdl:definitions")) { + isWsdlExist = true; + break; + } + } + } catch (Exception ignored) { + } finally { + if (rd != null) { + try { + rd.close(); + } catch (IOException e) { + //ignored + } + } + if (conn != null) { + conn.disconnect(); + } + } + return isWsdlExist; + + } +} diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/esb/TestConfigurationProvider.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/esb/TestConfigurationProvider.java new file mode 100644 index 0000000000..398b792be6 --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/esb/TestConfigurationProvider.java @@ -0,0 +1,113 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.test.utils.esb; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.automation.engine.context.AutomationContext; +import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil; + +import javax.xml.xpath.XPathExpressionException; +import java.io.File; + +public class TestConfigurationProvider { + private static Log log = LogFactory.getLog(TestConfigurationProvider.class); + private AutomationContext context; + private static TestConfigurationProvider instance = new TestConfigurationProvider(); + + private TestConfigurationProvider() { + try { + context = new AutomationContext(); + } catch (XPathExpressionException e) { + log.error("Loading Automation Configuration failed", e); + } + } + + public static String getResourceLocation(String productName) { + return FrameworkPathUtil.getSystemResourceLocation() + File.separator + "artifacts" + + File.separator + productName; + } + + public static String getSecurityPolicyLocation() { + return getResourceLocation() + File.separator + "security" + File.separator + "policies"; + } + + public static String getKeyStoreLocation() throws XPathExpressionException { + return getResourceLocation() + File.separator + + instance.context.getConfigurationValue("//keystore/fileName/text()"); + } + + public static String getKeyStorePassword() throws XPathExpressionException { + return getResourceLocation() + File.separator + + instance.context.getConfigurationValue("//keystore/password/text()"); + } + + public static String getKeyStoreType() throws XPathExpressionException { + return getResourceLocation() + File.separator + + instance.context.getConfigurationValue("//keystore/type/text()"); + } + + public static String getTrustStoreLocation() throws XPathExpressionException { + return getResourceLocation() + File.separator + + instance.context.getConfigurationValue("//truststore/fileName/text()"); + } + + public static String getTrustStorePassword() throws XPathExpressionException { + return getResourceLocation() + File.separator + + instance.context.getConfigurationValue("//truststore/password/text()"); + } + + public static String getTrustStoreType() throws XPathExpressionException { + return getResourceLocation() + File.separator + + instance.context.getConfigurationValue("//truststore/type/text()"); + } + + public static String getResourceLocation() { + return FrameworkPathUtil.getSystemResourceLocation(); + } + + public static String getExecutionEnvironment() throws XPathExpressionException { + return instance.context.getConfigurationValue("//executionEnvironment"); + } + + public static int getServiceDeploymentDelay() { + try { + return Integer.parseInt(instance.context.getConfigurationValue("//deploymentDelay")); + } catch (XPathExpressionException e) { + log.error("Error reading deploymentDelay from automation.xml", e); + log.warn( + "Service deployment Delay configuration not found. Running with default value " + + "30000" + " mils"); + } + //if there is an error, setting to default value 30000 milliseconds + return 30000; + } + + public static boolean isIntegration() throws XPathExpressionException { + return "standalone".equalsIgnoreCase(getExecutionEnvironment()); + } + + public static boolean isPlatform() throws XPathExpressionException { + return "platform".equalsIgnoreCase(getExecutionEnvironment()); + } + + public static AutomationContext getAutomationContext() { + return instance.context; + } +} diff --git a/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/validation/VerificationUtil.java b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/validation/VerificationUtil.java new file mode 100644 index 0000000000..08119b2b16 --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/validation/VerificationUtil.java @@ -0,0 +1,32 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.test.utils.validation; + +import org.json.JSONObject; +import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; + +public class VerificationUtil { + public static void checkErrors(HttpResponse response) throws Exception { + JSONObject jsonObject = new JSONObject(response.getData()); + if ((Boolean) jsonObject.get("error")) { + throw new Exception( + "Operation not successful: " + jsonObject.get("message").toString()); + } + } +} diff --git a/modules/integration/tests-common/integration-test-utils/target/maven-archiver/pom.properties b/modules/integration/tests-common/integration-test-utils/target/maven-archiver/pom.properties new file mode 100644 index 0000000000..835fe07615 --- /dev/null +++ b/modules/integration/tests-common/integration-test-utils/target/maven-archiver/pom.properties @@ -0,0 +1,5 @@ +#Generated by Maven +#Mon Jan 26 14:52:34 IST 2015 +version=1.7.0-SNAPSHOT +groupId=org.wso2.am +artifactId=integration-test-utils diff --git a/modules/integration/tests-common/pom.xml b/modules/integration/tests-common/pom.xml new file mode 100644 index 0000000000..ff11e8070d --- /dev/null +++ b/modules/integration/tests-common/pom.xml @@ -0,0 +1,254 @@ + + + + + org.wso2.am + integration + 1.7.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + integration-test-common + 1.7.0-SNAPSHOT + pom + WSO2 API Manager - Integration - Tests Common + + + admin-clients + integration-test-utils + test-artifacts + + + + + org.wso2.carbon.automation + org.wso2.carbon.automation.engine + compile + + + org.wso2.carbon.automation + org.wso2.carbon.automation.extensions + compile + + + org.seleniumhq.selenium + selenium-htmlunit-driver + + + org.seleniumhq.selenium + selenium-java + + + + + org.wso2.carbon.automation + org.wso2.carbon.automation.test.utils + compile + + + org.wso2.carbon + org.wso2.carbon.integration.common.admin.client + compile + + + org.wso2.carbon + org.wso2.carbon.integration.common.extensions + compile + + + org.seleniumhq.selenium + selenium-htmlunit-driver + + + org.seleniumhq.selenium + selenium-java + + + + + org.wso2.carbon + org.wso2.carbon.integration.common.utils + compile + + + + org.wso2.carbon + org.wso2.carbon.aarservices.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.endpoint.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.localentry.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.mediation.configadmin.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.priority.executors.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.rest.api + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.sequences.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.task.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.mediation.templates.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.transport.mgt.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.message.store.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.message.processor.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.mediation.artifactuploader.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.proxyadmin.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.service.mgt.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.registry.relations.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.registry.activities.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.registry.indexing.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.registry.handler.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.registry.info.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.registry.profiles.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.registry.properties.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.registry.reporting.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.registry.extensions.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.registry.search.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.registry.resource.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.rest.api.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.logging.admin.stub + ${carbon.platform.version} + compile + + + org.wso2.carbon + org.wso2.carbon.security.mgt.stub + ${carbon.platform.version} + compile + + + + + \ No newline at end of file diff --git a/modules/integration/tests-common/test-artifacts/pom.xml b/modules/integration/tests-common/test-artifacts/pom.xml new file mode 100644 index 0000000000..5a5bfe1dea --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/pom.xml @@ -0,0 +1,79 @@ + + + + + org.wso2.am + integration-test-common + 1.7.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + WSO2 API Manager - Integration - Tests Common - Test Artifacts + test-artifacts + 1.7.0-SNAPSHOT + jar + + + 2.7.2 + 1.9.12 + + + + + com.google.code.gson + gson + 2.2 + + + + javax.inject + javax.inject + 1 + + + + org.codehaus.jackson + jackson-mapper-asl + ${org.codehaus.jackson.version} + + + + org.codehaus.jackson + jackson-jaxrs + ${org.codehaus.jackson.version} + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${org.apache.cxf.version} + + + org.apache.ws.xmlschema + xmlschema-core + + + + + + org.codehaus.jackson + jackson-core-lgpl + ${org.codehaus.jackson.version} + + + + org.codehaus.jackson + jackson-mapper-lgpl + ${org.codehaus.jackson.version} + + + + org.apache.cxf + cxf-rt-rs-security-cors + ${org.apache.cxf.version} + + + diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/CoffeeConfig.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/CoffeeConfig.java new file mode 100644 index 0000000000..d8563d175d --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/CoffeeConfig.java @@ -0,0 +1,66 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.coffeesample; + +import org.apache.cxf.bus.spring.SpringBus; +import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; +import org.codehaus.jackson.jaxrs.JacksonJsonProvider; +import org.springframework.context.annotation.Bean; + +import javax.ws.rs.ext.RuntimeDelegate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class CoffeeConfig { + @Bean(destroyMethod = "shutdown") + public SpringBus cxf() { + return new SpringBus(); + } + + @Bean + public org.apache.cxf.endpoint.Server jaxRsServer() { + JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance() + .createEndpoint(jaxRsApiApplication(), + JAXRSServerFactoryBean.class); + factory.setServiceBeans(Arrays.asList(starbucksOutletService())); + factory.setAddress("/" + factory.getAddress()); + List providers = new ArrayList(); + providers.add(jsonProvider()); + providers.add(new OrderReader()); + factory.setProviders(providers); + //factory.setProviders( Arrays.< Object >asList( jsonProvider() ) ); + return factory.create(); + } + + @Bean + public JaxRsApiApplication jaxRsApiApplication() { + return new JaxRsApiApplication(); + } + + @Bean + public StarbucksOutletService starbucksOutletService() { + return new StarbucksOutletServiceImpl(); + } + + @Bean + public JacksonJsonProvider jsonProvider() { + return new JacksonJsonProvider(); + } +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/JaxRsApiApplication.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/JaxRsApiApplication.java new file mode 100644 index 0000000000..14052068ed --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/JaxRsApiApplication.java @@ -0,0 +1,26 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.coffeesample; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("api") +public class JaxRsApiApplication extends Application { +} \ No newline at end of file diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/OrderReader.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/OrderReader.java new file mode 100644 index 0000000000..a2f576eae7 --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/OrderReader.java @@ -0,0 +1,78 @@ +/* +* Copyright 2004,2005 The Apache Software Foundation. +* +* 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 org.wso2.am.integration.services.jaxrs.coffeesample; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.wso2.am.integration.services.jaxrs.coffeesample.bean.Order; + +import javax.ws.rs.Consumes; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyReader; +import javax.ws.rs.ext.Provider; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +@Provider +@Consumes(MediaType.APPLICATION_JSON) +public class OrderReader implements MessageBodyReader { + + @Override + public Order readFrom(Class type, + Type type1, + Annotation[] antns, + MediaType mt, MultivaluedMap mm, + InputStream in) throws IOException, WebApplicationException { + + Order order = new Order(); + InputStreamReader reader = new InputStreamReader(in); + + JsonElement json = new JsonParser().parse(reader); + JsonObject jsonObject = json.getAsJsonObject(); + if (jsonObject.get("additions") != null) { + order.setAdditions(jsonObject.get("additions").getAsString()); + } else { + order.setAdditions(""); + } + if (jsonObject.get("drinkName") != null) { + order.setDrinkName(jsonObject.get("drinkName").getAsString()); + } else { + order.setDrinkName(""); + } + if (jsonObject.get("cost") != null) { + order.setCost(jsonObject.get("cost").getAsDouble()); + } + if (jsonObject.get("orderId") != null) { + order.setOrderId(jsonObject.get("orderId").getAsString()); + } + order.setLocked(false); + + return order; + } + + @Override + public boolean isReadable(Class type, Type type1, Annotation[] antns, MediaType mt) { + return Order.class.isAssignableFrom(type); + } + +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/StarbucksOutletService.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/StarbucksOutletService.java new file mode 100644 index 0000000000..82e4954dce --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/StarbucksOutletService.java @@ -0,0 +1,79 @@ +/* +* Copyright 2004,2005 The Apache Software Foundation. +* +* 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 org.wso2.am.integration.services.jaxrs.coffeesample; + +import org.wso2.am.integration.services.jaxrs.coffeesample.bean.Order; +import org.wso2.am.integration.services.jaxrs.coffeesample.bean.Payment; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +@Path("/") +public interface StarbucksOutletService { + + @POST + @Path("/orders/") + // @Produces(MediaType.TEXT_PLAIN) + @Produces(MediaType.APPLICATION_JSON) // produces application/json + @Consumes({ MediaType.TEXT_XML, MediaType.APPLICATION_XML }) // consumes text/xml + public Response addOrder(Order orderBean); + + /** + * Read the following article on ATOM data binding in CXF + * http://goo.gl/UKJdM + * + * @param id order id + * @return the order + */ + @GET + @Path("/orders/{orderId}") + @Produces({ "application/json", "application/xml" }) // produces atom and json as relevant + public Order getOrder(@PathParam("orderId") String id); + + @PUT + @Path("/orders/") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public Response updateOrder(Order orderBean); + + @GET + @Path("/orders/pending/") + @Produces({ "application/json", "application/atom+xml;type=feed", "application/xml" }) + // application/atom+xml and json + public Response getPendingOrders(); //todo add a atom feader + + @PUT + @Path("/orders/lock/{orderId}/") + @Produces({ MediaType.APPLICATION_XML }) // application/xml + public Response lockOrder(@PathParam("orderId") String id); + + @DELETE + @Path("/orders/{orderId}/") + @Produces({ MediaType.TEXT_PLAIN }) + public Response removeOrder(@PathParam("orderId") String id); + + @POST + @Path("/payment/{orderId}/") + @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_HTML }) + public Response doPayment(@PathParam("orderId") String id, Payment payment); + + @GET + @Path("/payment/{orderId}/") + @Produces(MediaType.APPLICATION_JSON) + public Payment getPayment(@PathParam("orderId") String id); + +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/StarbucksOutletServiceImpl.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/StarbucksOutletServiceImpl.java new file mode 100755 index 0000000000..3df1962e66 --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/StarbucksOutletServiceImpl.java @@ -0,0 +1,201 @@ +/* + * Copyright 2011-2012 WSO2, Inc. (http://wso2.com) + * + * 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 org.wso2.am.integration.services.jaxrs.coffeesample; + +import org.wso2.am.integration.services.jaxrs.coffeesample.bean.Order; +import org.wso2.am.integration.services.jaxrs.coffeesample.bean.Payment; +import org.wso2.am.integration.services.jaxrs.coffeesample.bean.PaymentStatus; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.ConcurrentHashMap; + +/** + * + */ + +public class StarbucksOutletServiceImpl implements StarbucksOutletService { + private Map ordersList = new ConcurrentHashMap(); + + private Map paymentRegister = new ConcurrentHashMap(); + + private final Map priceList = new ConcurrentHashMap(); + + private static final Random rand = new Random(); + + // long currentId = 123; + // Map customers = new HashMap(); + // Map orders = new HashMap(); + + public StarbucksOutletServiceImpl() { + init(); + } + + public Response addOrder(Order orderBean) { + String drinkName = orderBean.getDrinkName(); + String additions = orderBean.getAdditions(); + orderBean.setCost(calculateCost(drinkName, additions)); + ordersList.put(orderBean.getOrderId(), orderBean); + return Response.ok().entity(orderBean).type(MediaType.APPLICATION_JSON).build(); + } + + public Order getOrder(String id) { + return ordersList.get(id); + } + + public Response updateOrder(Order orderBean) { + String orderId = orderBean.getOrderId(); + String drinkName = orderBean.getDrinkName(); + String additions = orderBean.getAdditions(); + + Order order = ordersList.get(orderId); + if (order != null) { + if (order.isLocked()) { + return Response.notModified().type(MediaType.APPLICATION_JSON_TYPE).build(); + } else { + if (drinkName != null && !"".equals(drinkName)) { + order.setDrinkName(drinkName); + } else { + drinkName = order.getDrinkName(); //used to calculate the cost + } + order.setAdditions(additions); + order.setCost(calculateCost(drinkName, additions)); + return Response.ok(order).type(MediaType.APPLICATION_JSON_TYPE).build(); + } + } + return null; + } + + public Response getPendingOrders() { //todo write the client + List orders = new ArrayList(); + for (Order order : ordersList.values()) { + if (!order.isLocked()) { + orders.add(order); + } + } + return Response.ok(orders).type("application/atom+xml;type=feed").build(); + } + + public Response lockOrder(String id) { //@PathParam("orderId") + Order order = ordersList.get(id); + if (order != null) { + order.setLocked(true); + return Response.ok(order).type(MediaType.APPLICATION_XML).build(); + } + return Response.notModified().entity(id).type(MediaType.APPLICATION_XML).build(); + } + + public Response removeOrder(String id) { // @PathParam("orderId") + Boolean removed = ordersList.remove(id) != null; + paymentRegister.remove(id); + String status = removed.toString(); + return removed ? Response.ok(status).build() : Response.notModified().build(); + } + + public Response doPayment(String id, Payment payment) { // @PathParam("orderId") + String name = payment.getName(); + Double amount = payment.getAmount(); + String cardNumber = payment.getCardNumber(); + String expiryDate = payment.getExpiryDate(); + + PaymentStatus paymentStatus; + Payment registeredPayment = paymentRegister.get(id); + if (registeredPayment != null) { + paymentStatus = new PaymentStatus("Duplicate Payment", registeredPayment); + return Response.notModified().entity(paymentStatus).type(MediaType.APPLICATION_JSON) + .build(); + } + + Order order = ordersList.get(id); + if (order == null) { + paymentStatus = new PaymentStatus("Invalid Order ID", null); + return Response.notModified().entity(paymentStatus).type(MediaType.APPLICATION_JSON) + .build(); + } + + if (!order.isAmountAcceptable(amount)) { + paymentStatus = new PaymentStatus("Insufficient Funds", null); + return Response.notModified().entity(paymentStatus).type(MediaType.APPLICATION_JSON) + .build(); + } + + registeredPayment = new Payment(id); + registeredPayment.setAmount(amount); + registeredPayment.setCardNumber(cardNumber); + registeredPayment.setExpiryDate(expiryDate); + registeredPayment.setName(name); + paymentRegister.put(id, registeredPayment); + paymentStatus = new PaymentStatus("Payment Accepted", registeredPayment); + return Response.ok().entity(paymentStatus).type(MediaType.APPLICATION_JSON).build(); + + } + + public Payment getPayment(String id) { // @PathParam("orderId") + return paymentRegister.get(id); + } + + private double calculateCost(String drinkName, String additions) { + double cost = getPrice(drinkName, false); + if (additions != null && !"".equals(additions)) { + String[] additionalItems = additions.split(" "); + for (String item : additionalItems) { + cost += getPrice(item, true); + } + } + return Double.parseDouble(Order.currencyFormat.format(cost)); + } + + private double getPrice(String item, boolean addition) { + synchronized (priceList) { + Double price = priceList.get(item); + if (price == null) { + if (addition) { + price = rand.nextDouble() * 5; + } else { + price = rand.nextInt(8) + 2 - 0.01; + } + priceList.put(item, price); + } + return price; + } + } + + private void init() { + String drinkName = "Vanilla Flavored Coffee"; + String additions = "Milk"; + Order order = new Order(); + order.setOrderId("123"); + order.setDrinkName(drinkName); + order.setAdditions(additions); + order.setCost(calculateCost(drinkName, additions)); + + ordersList.put(order.getOrderId(), order); + + //following order is used by the Client class to show the HTTP DELETE + drinkName = "Chocolate Flavored Coffee"; + order = new Order(); + order.setOrderId("444"); + order.setDrinkName(drinkName); + order.setCost(calculateCost(drinkName, null)); //no additions + + ordersList.put(order.getOrderId(), order); + } +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Customer.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Customer.java new file mode 100755 index 0000000000..0f3ba11f55 --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Customer.java @@ -0,0 +1,41 @@ +/* + * Copyright 2011-2012 WSO2, Inc. (http://wso2.com) + * + * 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 org.wso2.am.integration.services.jaxrs.coffeesample.bean; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "Customer") +public class Customer { + private long id; + private String name; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Order.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Order.java new file mode 100755 index 0000000000..0880363fb6 --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Order.java @@ -0,0 +1,105 @@ +/* + * Copyright 2011-2012 WSO2, Inc. (http://wso2.com) + * + * 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 org.wso2.am.integration.services.jaxrs.coffeesample.bean; + +import javax.xml.bind.annotation.XmlRootElement; +import java.text.DateFormat; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +@XmlRootElement(name = "Order") +public class Order { + + private String orderId; + + private String drinkName; + + private String additions; + + private double cost; + + private boolean locked; //false by default + + private long timestamp; + + public static final NumberFormat currencyFormat = new DecimalFormat("#.##"); + private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'"); + + public Order() { + this.orderId = UUID.randomUUID().toString(); + this.timestamp = System.currentTimeMillis(); + } + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public String getDrinkName() { + return drinkName; + } + + public void setDrinkName(String drinkName) { + this.drinkName = drinkName; + // this.setCost(calculateCost()); + this.timestamp = System.currentTimeMillis(); + } + + public String getAdditions() { + return additions; + } + + public void setAdditions(String additions) { + this.additions = additions; + // this.setCost(calculateCost()); + this.timestamp = System.currentTimeMillis(); + } + + public String getCost() { + return currencyFormat.format(cost); + } + + public void setCost(double cost) { + this.cost = cost; + } + + public boolean isLocked() { + return locked; + } + + public void setLocked(boolean locked) { + this.locked = locked; + } + + public String getTimestamp() { + return dateFormat.format(new Date(timestamp)); + } + + public void setTimestamp(Long timestamp) { + this.timestamp = timestamp; + } + + public boolean isAmountAcceptable(double amount) { + return amount >= cost; + } +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Payment.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Payment.java new file mode 100644 index 0000000000..bf6fac248c --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/Payment.java @@ -0,0 +1,78 @@ +/* +* Copyright 2004,2005 The Apache Software Foundation. +* +* 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 org.wso2.am.integration.services.jaxrs.coffeesample.bean; + +import javax.xml.bind.annotation.XmlRootElement; +import java.text.DecimalFormat; +import java.text.NumberFormat; + +@XmlRootElement(name = "Payment") +public class Payment { + + private static final NumberFormat currencyFormat = new DecimalFormat("#.##"); + + private String orderId; + private String name; + private String cardNumber; + private String expiryDate; + private Double amount; + + public Payment(String orderId) { + this.orderId = orderId; + } + + public Payment() { + + } + + public String getOrderId() { + return orderId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCardNumber() { + return cardNumber; + } + + public void setCardNumber(String cardNumber) { + this.cardNumber = cardNumber; + } + + public String getExpiryDate() { + return expiryDate; + } + + public void setExpiryDate(String expiryDate) { + this.expiryDate = expiryDate; + } + + public Double getAmount() { + return Double.valueOf(currencyFormat.format(amount)); + } + + public void setAmount(Double amount) { + this.amount = amount; + } + +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/PaymentStatus.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/PaymentStatus.java new file mode 100644 index 0000000000..dd2bb974df --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/coffeesample/bean/PaymentStatus.java @@ -0,0 +1,78 @@ +/* +* Copyright 2004,2005 The Apache Software Foundation. +* +* 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 org.wso2.am.integration.services.jaxrs.coffeesample.bean; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "PaymentStatus") +public class PaymentStatus { + + /** + * If XmlElement wasn't there, the generated element name will be simple letters, 'status' + * Here, we modified it to 'Status' + *

    + * name is of type String, and required is of type boolean + *

    + * Since the required attribute is set to true, no get method for this variable + */ + @XmlElement(name = "Status", required = true) + private String status; + + /** + * Since Payment class is also a bean, the JSON content generated by this bean + * will be wrapped in to PaymentStatus bean + * ex. + * { + * "PaymentStatus": + * { + * "Payment":{"amount":50,"cardNumber":"1234 2345 3456 4567","expiryDate":"01-01-2015","name":"Kasun Gajasinghe"}, + * "Status":"Payment Accepted" + * } + * } + */ + @XmlElement(name = "Payment", required = true) + private Payment payment; + + public PaymentStatus(String status, Payment payment) { + this.setStatus(status); + this.setPayment(payment); + } + + /** + * A no-arg default constructor is needed for proper operation of JAX-RS + */ + public PaymentStatus() { + + } + + // public String getStatus() { + // return status; + // } + // + // public Payment getPayment() { + // return payment; + // } + + public void setStatus(String status) { + this.status = status; + } + + public void setPayment(Payment payment) { + this.payment = payment; + } +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/CustomerConfig.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/CustomerConfig.java new file mode 100644 index 0000000000..6312918c21 --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/CustomerConfig.java @@ -0,0 +1,60 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.customersample; + +import org.apache.cxf.bus.spring.SpringBus; +import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; +import org.codehaus.jackson.jaxrs.JacksonJsonProvider; +import org.springframework.context.annotation.Bean; + +import javax.ws.rs.ext.RuntimeDelegate; +import java.util.Arrays; + +public class CustomerConfig { + @Bean(destroyMethod = "shutdown") + public SpringBus cxf() { + return new SpringBus(); + } + + @Bean + public org.apache.cxf.endpoint.Server jaxRsServer() { + JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance() + .createEndpoint(jaxRsApiApplication(), + JAXRSServerFactoryBean.class); + factory.setServiceBeans(Arrays.asList(customerService())); + factory.setAddress("/" + factory.getAddress()); + factory.setProviders(Arrays.asList(jsonProvider())); + return factory.create(); + } + + @Bean + public JaxRsApiApplication jaxRsApiApplication() { + return new JaxRsApiApplication(); + } + + @Bean + public CustomerService customerService() { + return new CustomerService(); + } + + @Bean + public JacksonJsonProvider jsonProvider() { + return new JacksonJsonProvider(); + } +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/CustomerService.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/CustomerService.java new file mode 100755 index 0000000000..940e60a319 --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/CustomerService.java @@ -0,0 +1,122 @@ +/* + * Copyright 2011-2012 WSO2, Inc. (http://wso2.com) + * + * 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 org.wso2.am.integration.services.jaxrs.customersample; + +import org.wso2.am.integration.services.jaxrs.customersample.bean.Customer; +import org.wso2.am.integration.services.jaxrs.customersample.bean.Order; + +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import java.util.HashMap; +import java.util.Map; + +@Path("/customerservice/") +public class CustomerService { + long currentId = 123; + Map customers = new HashMap(); + Map orders = new HashMap(); + + public CustomerService() { + init(); + } + + @GET + @Path("/customers/{id}/") + public Customer getCustomer(@PathParam("id") String id) { + System.out.println("----invoking getCustomer, Customer id is: " + id); + long idNumber = Long.parseLong(id); + Customer c = customers.get(idNumber); + return c; + } + + @PUT + @Path("/customers/") + public Response updateCustomer(Customer customer) { + System.out.println("----invoking updateCustomer, Customer name is: " + customer.getName()); + Customer c = customers.get(customer.getId()); + Response r; + if (c != null) { + customers.put(customer.getId(), customer); + r = Response.ok().build(); + } else { + r = Response.notModified().build(); + } + + return r; + } + + @POST + @Path("/customers/") + public Response addCustomer(Customer customer) { + System.out.println("----invoking addCustomer, Customer name is: " + customer.getName()); + customer.setId(++currentId); + + customers.put(customer.getId(), customer); + + return Response.ok(customer).build(); + } + + // Adding a new method to demonstrate Consuming and Producing text/plain + + @POST + @Path("/customers/name/") + @Consumes("text/plain") + @Produces("text/plain") + public String getCustomerName(String id) { + System.out.println("----invoking getCustomerName, Customer id is: " + id); + return "Isuru Suriarachchi"; + } + + @DELETE + @Path("/customers/{id}/") + public Response deleteCustomer(@PathParam("id") String id) { + System.out.println("----invoking deleteCustomer, Customer id is: " + id); + long idNumber = Long.parseLong(id); + Customer c = customers.get(idNumber); + + Response r; + if (c != null) { + r = Response.ok().build(); + customers.remove(idNumber); + } else { + r = Response.notModified().build(); + } + + return r; + } + + @Path("/orders/{orderId}/") + public Order getOrder(@PathParam("orderId") String orderId) { + System.out.println("----invoking getOrder, Order id is: " + orderId); + long idNumber = Long.parseLong(orderId); + Order c = orders.get(idNumber); + return c; + } + + final void init() { + Customer c = new Customer(); + c.setName("John"); + c.setId(123); + customers.put(c.getId(), c); + + Order o = new Order(); + o.setDescription("order 223"); + o.setId(223); + orders.put(o.getId(), o); + } + +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/JaxRsApiApplication.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/JaxRsApiApplication.java new file mode 100644 index 0000000000..5fbe623366 --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/JaxRsApiApplication.java @@ -0,0 +1,26 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.customersample; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("api") +public class JaxRsApiApplication extends Application { +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Customer.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Customer.java new file mode 100755 index 0000000000..34b887e722 --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Customer.java @@ -0,0 +1,41 @@ +/* + * Copyright 2011-2012 WSO2, Inc. (http://wso2.com) + * + * 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 org.wso2.am.integration.services.jaxrs.customersample.bean; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "Customer") +public class Customer { + private long id; + private String name; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Order.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Order.java new file mode 100755 index 0000000000..cba184a7d8 --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Order.java @@ -0,0 +1,66 @@ +/* + * Copyright 2011-2012 WSO2, Inc. (http://wso2.com) + * + * 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 org.wso2.am.integration.services.jaxrs.customersample.bean; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.HashMap; +import java.util.Map; + +@XmlRootElement(name = "Order") +public class Order { + private long id; + private String description; + private Map products = new HashMap(); + + public Order() { + init(); + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String d) { + this.description = d; + } + + @GET + @Path("products/{productId}/") + public Product getProduct(@PathParam("productId") int productId) { + System.out.println("----invoking getProduct with id: " + productId); + Product p = products.get(new Long(productId)); + return p; + } + + final void init() { + Product p = new Product(); + p.setId(323); + p.setDescription("product 323"); + products.put(p.getId(), p); + } +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Product.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Product.java new file mode 100755 index 0000000000..328774662f --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/customersample/bean/Product.java @@ -0,0 +1,41 @@ +/* + * Copyright 2011-2012 WSO2, Inc. (http://wso2.com) + * + * 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 org.wso2.am.integration.services.jaxrs.customersample.bean; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "Product") +public class Product { + private long id; + private String description; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String d) { + this.description = d; + } +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/AppConfig.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/AppConfig.java new file mode 100644 index 0000000000..830d3dade9 --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/AppConfig.java @@ -0,0 +1,68 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.peoplesample; + +import org.apache.cxf.bus.spring.SpringBus; +import org.apache.cxf.endpoint.Server; +import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; +import org.codehaus.jackson.jaxrs.JacksonJsonProvider; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.ws.rs.ext.RuntimeDelegate; +import java.util.Arrays; + +@Configuration +public class AppConfig { + @Bean(destroyMethod = "shutdown") + public SpringBus cxf() { + return new SpringBus(); + } + + @Bean + public Server jaxRsServer() { + JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance() + .createEndpoint(jaxRsApiApplication(), + JAXRSServerFactoryBean.class); + factory.setServiceBeans(Arrays.asList(peopleRestService())); + factory.setAddress("/" + factory.getAddress()); + factory.setProviders(Arrays.asList(jsonProvider())); + return factory.create(); + } + + @Bean + public JaxRsApiApplication jaxRsApiApplication() { + return new JaxRsApiApplication(); + } + + @Bean + public PeopleRestService peopleRestService() { + return new PeopleRestService(); + } + + @Bean + public PeopleService peopleService() { + return new PeopleService(); + } + + @Bean + public JacksonJsonProvider jsonProvider() { + return new JacksonJsonProvider(); + } +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/JaxRsApiApplication.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/JaxRsApiApplication.java new file mode 100644 index 0000000000..4915c59628 --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/JaxRsApiApplication.java @@ -0,0 +1,26 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.peoplesample; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("api") +public class JaxRsApiApplication extends Application { +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/PeopleRestService.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/PeopleRestService.java new file mode 100644 index 0000000000..0d7f34484f --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/PeopleRestService.java @@ -0,0 +1,150 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.peoplesample; + +import org.apache.cxf.rs.security.cors.CorsHeaderConstants; +import org.wso2.am.integration.services.jaxrs.peoplesample.bean.Person; + +import javax.inject.Inject; +import javax.ws.rs.*; +import javax.ws.rs.core.*; +import java.util.Collection; + +@Path("/people") +public class PeopleRestService { + @Inject + private PeopleService peopleService; + + public void PeopleRestService() { + peopleService.setInitPeople(); + } + + @Produces({ MediaType.APPLICATION_JSON }) + @GET + public Collection getPeople(@QueryParam("page") @DefaultValue("1") final int page) { + return peopleService.getPeople(page, 5); + } + + @Produces({ MediaType.APPLICATION_JSON }) + @PUT + public Person addPerson(@FormParam("email") final String email) { + return peopleService.addPerson(email); + } + + @Produces({ MediaType.APPLICATION_JSON }) + @Path("/{email}") + @GET + public Person getPeople(@PathParam("email") final String email) { + return peopleService.getByEmail(email); + } + +/* + @Produces( { MediaType.APPLICATION_FORM_URLENCODED } ) + @POST + public Response addPerson( @Context final UriInfo uriInfo, + @FormParam( "email" ) final String email, + @FormParam( "firstName" ) final String firstName, + @FormParam( "lastName" ) final String lastName ) { + peopleService.addPerson( email, firstName, lastName ); + return Response.created( uriInfo.getRequestUriBuilder().path( email ).build() ).build(); + } + +*/ + + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED }) + @POST + public Response addPersonQueryParam(@Context final UriInfo uriInfo, + @QueryParam("email") final String email, + @QueryParam("firstName") final String firstName, + @QueryParam("lastName") final String lastName) { + peopleService.addPerson(email, firstName, lastName); + return Response.created(uriInfo.getRequestUriBuilder().path(email).build()).build(); + } + + /* @Produces({MediaType.APPLICATION_JSON}) + @Path("/{email}") + @PUT + public Person updatePerson(@PathParam("email") final String email, + @FormParam("firstName") final String firstName, + @FormParam("lastName") final String lastName) { + + final Person person = peopleService.getByEmail(email); + if (firstName != null) { + person.setFirstName(firstName); + } + + if (lastName != null) { + person.setLastName(lastName); + } + + return person; + } + */ + @Produces({ MediaType.APPLICATION_JSON }) + @Path("/{email}") + @HEAD + public Response checkPerson(@PathParam("email") final String email) { + if (peopleService.checkPersonByEmail(email)) { + return Response.ok().build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + + } + + @Produces({ MediaType.APPLICATION_JSON }) + @Path("/{email}") + @PUT + public Person updatePersonQueryParam(@PathParam("email") final String email, + @QueryParam("firstName") final String firstName, + @QueryParam("lastName") final String lastName) { + + final Person person = peopleService.getByEmail(email); + if (firstName != null) { + person.setFirstName(firstName); + } + + if (lastName != null) { + person.setLastName(lastName); + } + + return person; + } + + @Path("/{email}") + @DELETE + public Response deletePerson(@PathParam("email") final String email) { + peopleService.removePerson(email); + return Response.ok().build(); + } + + @Produces({ MediaType.APPLICATION_JSON }) + @Path("/options") + @OPTIONS + public Response getOptions(@Context HttpHeaders headers, + @Context Request request) { + return Response.ok() + .header(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS, + "GET POST DELETE PUT OPTIONS") + .header(CorsHeaderConstants.HEADER_AC_ALLOW_CREDENTIALS, "false") + .header(CorsHeaderConstants.HEADER_AC_REQUEST_HEADERS, + MediaType.APPLICATION_JSON) + .build(); + } +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/PeopleService.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/PeopleService.java new file mode 100644 index 0000000000..ce1ec360e5 --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/PeopleService.java @@ -0,0 +1,98 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.peoplesample; + +import org.springframework.stereotype.Service; +import org.wso2.am.integration.services.jaxrs.peoplesample.bean.Person; +import org.wso2.am.integration.services.jaxrs.peoplesample.exceptions.PersonAlreadyExistsException; +import org.wso2.am.integration.services.jaxrs.peoplesample.exceptions.PersonNotFoundException; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +@Service +public class PeopleService { + private ConcurrentMap persons = new ConcurrentHashMap(); + + public void setInitPeople() { + + for (int count = 1; count <= 10; count++) { + Person newPerson = new Person(); + newPerson.setEmail(String.format("test-%d@wso2.com", count)); + newPerson.setFirstName(String.format("testUser%d", count)); + newPerson.setLastName(String.format("testLasrName%d", count)); + persons.putIfAbsent(String.format("test-%d@wso2.com", count), newPerson); + } + } + + public Collection getPeople(int page, int pageSize) { + Collection person = new ArrayList(pageSize); + + for (int index = 0; index < pageSize; ++index) { + person.add(new Person( + String.format("person+%d@at.com", (pageSize * (page - 1) + index + 1)))); + } + setInitPeople(); + return person; + } + + public Person addPerson(String email) { + + return new Person(email); + } + + public Person getByEmail(final String email) { + final Person person = persons.get(email); + if (person == null) { + throw new PersonNotFoundException(email); + } + + return person; + } + + public boolean checkPersonByEmail(final String email) { + boolean personExists = true; + final Person person = persons.get(email); + if (person == null) { + personExists = false; + } + return personExists; + } + + public Person addPerson(final String email, final String firstName, final String lastName) { + final Person person = new Person(email); + person.setFirstName(firstName); + person.setLastName(lastName); + + if (persons.putIfAbsent(email, person) != null) { + throw new PersonAlreadyExistsException(email); + } + + return person; + } + + public void removePerson(final String email) { + if (persons.remove(email) == null) { + throw new PersonNotFoundException(email); + } + } + +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/Starter.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/Starter.java new file mode 100644 index 0000000000..880309fea4 --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/Starter.java @@ -0,0 +1,71 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.peoplesample; + +import org.apache.catalina.Context; +import org.apache.catalina.loader.WebappLoader; +import org.apache.catalina.startup.Tomcat; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.cxf.transport.servlet.CXFServlet; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; + +import java.io.File; +import java.io.IOException; + +public class Starter { + private final static Log log = LogFactory.getLog(Starter.class); + + public void startPeopleService() throws Exception { + final File base = createBaseDirectory(); + log.info("Using base folder: " + base.getAbsolutePath()); + + final Tomcat tomcat = new Tomcat(); + tomcat.setPort(8080); + tomcat.setBaseDir(base.getAbsolutePath()); + + Context context = tomcat.addContext("/", base.getAbsolutePath()); + Tomcat.addServlet(context, "CXFServlet", new CXFServlet()); + + context.addServletMapping("/rest/*", "CXFServlet"); + context.addApplicationListener(ContextLoaderListener.class.getName()); + context.setLoader(new WebappLoader(Thread.currentThread().getContextClassLoader())); + + context.addParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName()); + context.addParameter("contextConfigLocation", AppConfig.class.getName()); + + tomcat.start(); + tomcat.getServer().await(); + } + + private static File createBaseDirectory() throws IOException { + final File base = File.createTempFile("tmp-", "", new File( + "/home/dharshana/reaserch/jetty/jetty2/src/main/resources")); + + if (!base.delete()) { + throw new IOException("Cannot (re)create base folder: " + base.getAbsolutePath()); + } + + if (!base.mkdir()) { + throw new IOException("Cannot create base folder: " + base.getAbsolutePath()); + } + return base; + } +} \ No newline at end of file diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/bean/Person.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/bean/Person.java new file mode 100644 index 0000000000..51a2a7e591 --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/bean/Person.java @@ -0,0 +1,56 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.peoplesample.bean; + +public class Person { + private String email; + private String firstName; + private String lastName; + + public Person() { + } + + public Person(final String email) { + this.email = email; + } + + public String getEmail() { + return email; + } + + public void setEmail(final String email) { + this.email = email; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + + public void setLastName(final String lastName) { + this.lastName = lastName; + } +} \ No newline at end of file diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/exceptions/PersonAlreadyExistsException.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/exceptions/PersonAlreadyExistsException.java new file mode 100644 index 0000000000..5371dc26bf --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/exceptions/PersonAlreadyExistsException.java @@ -0,0 +1,36 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.peoplesample.exceptions; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +public class PersonAlreadyExistsException extends WebApplicationException { + private static final long serialVersionUID = 6817489620338221395L; + + public PersonAlreadyExistsException(final String email) { + super( + Response + .status(Status.CONFLICT) + .entity("Person already exists: " + email) + .build() + ); + } +} diff --git a/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/exceptions/PersonNotFoundException.java b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/exceptions/PersonNotFoundException.java new file mode 100644 index 0000000000..5a031919db --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/src/main/java/org/wso2/am/integration.services/jaxrs/peoplesample/exceptions/PersonNotFoundException.java @@ -0,0 +1,36 @@ +/* +*Copyright (c) 2005-2010, 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.am.integration.services.jaxrs.peoplesample.exceptions; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +public class PersonNotFoundException extends WebApplicationException { + private static final long serialVersionUID = -2894269137259898072L; + + public PersonNotFoundException(final String email) { + super( + Response + .status(Status.NOT_FOUND) + .entity("Person not found: " + email) + .build() + ); + } +} diff --git a/modules/integration/tests-common/test-artifacts/target/maven-archiver/pom.properties b/modules/integration/tests-common/test-artifacts/target/maven-archiver/pom.properties new file mode 100644 index 0000000000..9a7739a37d --- /dev/null +++ b/modules/integration/tests-common/test-artifacts/target/maven-archiver/pom.properties @@ -0,0 +1,5 @@ +#Generated by Maven +#Mon Jan 26 14:52:35 IST 2015 +version=1.7.0-SNAPSHOT +groupId=org.wso2.am +artifactId=test-artifacts diff --git a/modules/integration/tests-integration/tests-jmeter/pom.xml b/modules/integration/tests-integration/tests-jmeter/pom.xml new file mode 100644 index 0000000000..98a18b449d --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/pom.xml @@ -0,0 +1,244 @@ + + + + org.wso2.am + integration + 1.7.0-SNAPSHOT + ../../pom.xml + + + 1.7.0-SNAPSHOT + 4.0.0 + org.wso2.carbon.am.jmeter + WSO2 API Manager - Integration Tests - Jmeter + jar + + + + + maven-surefire-plugin + 2.12.4 + false + + + -Xms512m -Xmx1024m -XX:MaxPermSize=128m + true + false + false + + src/test/resources/testng.xml + + + + framework.resource.location + + ${basedir}/src/test/resources/ + + + + server.list + + AM + + + + usedefaultlisteners + false + + ${basedir}/target/security-verifier/ + false + + ${basedir}/../../../distribution/product/target/wso2am-${project.version}.zip + + ${basedir}/target/emma + ${basedir}/src/test/resources/instrumentation.txt + ${basedir}/src/test/resources/filters.txt + ${basedir}/target/emma + + ${basedir}/target + + + + maven-dependency-plugin + + + copy-emma-dependencies + compile + + copy-dependencies + + + ${project.build.directory}/emma + jar + emma,org.wso2.carbon.automation.core + + + + + copy-secVerifier + compile + + copy-dependencies + + + ${basedir}/target/security-verifier + aar + SecVerifier + true + + + + unpack-mar-jks + compile + + unpack + + + + + org.wso2.am + wso2am + ${project.version} + zip + true + ${basedir}/target/tobeCopied/ + **/*.jks,**/*.mar,**/synapse_sample*.xml + + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + + test-jar + + + + + + + maven-resources-plugin + 2.6 + + + copy-resources-jks + compile + + copy-resources + + + ${basedir}/src/test/resources/keystores/products + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/resources/security/ + + + **/*.jks + + + + + + + copy-stratos-jks + compile + + copy-resources + + + ${basedir}/src/test/resources/keystores/stratos + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/resources/security/ + + + **/*.jks + + + + + + + copy-sample-jks + compile + + copy-resources + + + ${basedir}/src/test/resources/keystores/products + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/samples/resources/security/ + + + **/*.jks + + + + + + + copy-resources-mar + compile + + copy-resources + + + ${basedir}/src/test/resources/client/modules + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/deployment/client/modules + + + **/*.mar + + + + + + + + + + + + org.wso2.am + admin-clients + ${project.version} + + + org.wso2.am + integration-test-utils + ${project.version} + + + org.wso2.carbon.automation + org.wso2.carbon.automation.tools.jmeter + ${test-automation-framework-version} + + + + 4.2.5 + + + diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/JmeterDomainRestrictionTestCase.java b/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/JmeterDomainRestrictionTestCase.java new file mode 100644 index 0000000000..e6a8707abc --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/JmeterDomainRestrictionTestCase.java @@ -0,0 +1,49 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.jmeter; + +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.carbon.automation.extensions.jmeter.JMeterTest; +import org.wso2.carbon.automation.extensions.jmeter.JMeterTestManager; + +import java.io.File; + +/** + * This jmeter based test case added to automate test for issue + * https://wso2.org/jira/browse/APIMANAGER-850 + */ +public class JmeterDomainRestrictionTestCase extends APIManagerIntegrationTest { + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(); + } + + @Test(groups = "wso2.am", description = "Login to api manager as user2") + public void testListServices() throws Exception { + JMeterTest script = + new JMeterTest(new File(getAMResourceLocation() + File.separator + "scripts" + + File.separator + "DomainRestrictionTest.jmx")); + + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(script); + } +} diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/JmeterLoginTestCase.java b/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/JmeterLoginTestCase.java new file mode 100644 index 0000000000..94a3a8bea2 --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/JmeterLoginTestCase.java @@ -0,0 +1,45 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.jmeter; + +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.carbon.automation.extensions.jmeter.JMeterTest; +import org.wso2.carbon.automation.extensions.jmeter.JMeterTestManager; + +import java.io.File; + +public class JmeterLoginTestCase extends APIManagerIntegrationTest { + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(); + } + + @Test(groups = "wso2.am", description = "Login to api manager as user2") + public void testListServices() throws Exception { + JMeterTest script = + new JMeterTest(new File(getAMResourceLocation() + File.separator + "scripts" + + File.separator + "API_Manager_Login_Test.jmx")); + + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(script); + } +} diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/JmeterSuperTenantTestCase.java b/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/JmeterSuperTenantTestCase.java new file mode 100644 index 0000000000..5407926bbc --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/JmeterSuperTenantTestCase.java @@ -0,0 +1,48 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.jmeter; + +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.carbon.automation.extensions.jmeter.JMeterTest; +import org.wso2.carbon.automation.extensions.jmeter.JMeterTestManager; + +import java.io.File; + +public class JmeterSuperTenantTestCase extends APIManagerIntegrationTest { + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(); + } + + @Test(groups = "wso2.am", description = "Covers API creation, publish api get default app id," + + " subscribe users to default app, invoke api - On a" + + " super tenant setup") + public void testListServices() throws Exception { + JMeterTest script = + new JMeterTest(new File(getAMResourceLocation() + File.separator + "scripts" + + File.separator + "basic_functionality_test.jmx")); + + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(script); + } +} + diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/JmeterTestCases.java b/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/JmeterTestCases.java new file mode 100644 index 0000000000..1af4f5ddb7 --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/JmeterTestCases.java @@ -0,0 +1,81 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.jmeter; + +import org.apache.axis2.AxisFault; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment; +import org.wso2.carbon.automation.engine.annotations.SetEnvironment; +import org.wso2.carbon.automation.extensions.jmeter.JMeterTest; +import org.wso2.carbon.automation.extensions.jmeter.JMeterTestManager; +import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; +import org.wso2.carbon.utils.ServerConstants; + +import java.io.File; +import java.io.IOException; + +public class JmeterTestCases extends APIManagerIntegrationTest { + + private ServerConfigurationManager serverConfigurationManager; + + @SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL }) + @BeforeClass(alwaysRun = true) + public void testChangeTransportMechanism() throws Exception, AxisFault { + super.init(); + serverConfigurationManager = new ServerConfigurationManager(context); + String carbonHome = System.getProperty(ServerConstants.CARBON_HOME); + + File axis2xmlFile = + new File(carbonHome + File.separator + "repository" + File.separator + "conf" + + File.separator + "axis2" + File.separator + "axis2.xml"); + + File sourceAxis2xmlFile = + new File(carbonHome + File.separator + "repository" + File.separator + + "conf" + File.separator + "axis2" + File.separator + "axis2.xml_NHTTP"); + + if (!axis2xmlFile.exists() || !sourceAxis2xmlFile.exists()) { + throw new IOException("File not found in given location"); + } + + serverConfigurationManager.applyConfiguration(sourceAxis2xmlFile, axis2xmlFile); + } + + @SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL }) + @Test(groups = "wso2.am", + description = "Covers tenant creation, role creation, API creation, publish api," + + "get default app id, subscribe users to default app, invoke api") + public void testListServices() throws Exception { + JMeterTest script = + new JMeterTest(new File(getAMResourceLocation() + File.separator + "scripts" + + File.separator + + "API_Manager_functionality_and_loadTest.jmx")); + + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(script); + } + + @SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL }) + @AfterClass(alwaysRun = true) + public void testCleanup() throws Exception { + serverConfigurationManager.restoreToLastConfiguration(); + serverConfigurationManager = null; + } +} diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/JmeterTransportRestrictionTestCase.java b/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/JmeterTransportRestrictionTestCase.java new file mode 100644 index 0000000000..0ed72164b9 --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/JmeterTransportRestrictionTestCase.java @@ -0,0 +1,42 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.jmeter; + +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.carbon.automation.extensions.jmeter.JMeterTest; +import org.wso2.carbon.automation.extensions.jmeter.JMeterTestManager; + +import java.io.File; + +public class JmeterTransportRestrictionTestCase extends APIManagerIntegrationTest { + + @Test(groups = "wso2.am", description = "Covers API creation, publish api get default app id," + + " subscribe users to default app, invoke api - On a" + + " super tenant setup") + public void testListServices() throws Exception { + JMeterTest script = + new JMeterTest(new File(getAMResourceLocation() + File.separator + "scripts" + + File.separator + "transport_restriction_check.jmx")); + + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(script); + } +} + diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/PassthroughTestCase.java b/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/PassthroughTestCase.java new file mode 100644 index 0000000000..eafe16e21f --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/java/org.wso2.carbon.am.jmeter/PassthroughTestCase.java @@ -0,0 +1,127 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.jmeter; + +import org.apache.axis2.AxisFault; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.am.integration.test.utils.WireMonitorServer; +import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment; +import org.wso2.carbon.automation.engine.annotations.SetEnvironment; +import org.wso2.carbon.automation.extensions.jmeter.JMeterTest; +import org.wso2.carbon.automation.extensions.jmeter.JMeterTestManager; +import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; + +import java.io.File; + +public class PassthroughTestCase extends APIManagerIntegrationTest { + + private ServerConfigurationManager serverConfigurationManager; + + @SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL }) + @BeforeClass(alwaysRun = true) + public void init() throws Exception, AxisFault { + super.init(); + } + + @SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL }) + @Test(groups = "wso2.am", + description = "Covers tenant creation, role creation, API creation, publish api," + + "get default app id, subscribe users to default app, invoke api") + public void testListServices() throws Exception { + JMeterTest script = + new JMeterTest(new File(getAMResourceLocation() + File.separator + "scripts" + + File.separator + + "API_Manager_functionality_and_loadTest_new_tenant.jmx")); + + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(script); + } + + @SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL }) + @Test(groups = "wso2.am", description = + "creates and API, subscribe to it and send GET and DELETE requests without " + + "Content-Type header and checks for if the Content-Type header is forcefully added by APIM, " + + "which should not happen") + public void JIRA_APIMANAGER_1397_testContentTypeHeaderInsertionCheck() throws Exception { + JMeterTest publishScript = + new JMeterTest(new File(getAMResourceLocation() + File.separator + "scripts" + + File.separator + + "content_type_check_publish_and_subscribe_script.jmx")); + + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(publishScript); + + WireMonitorServer wireMonitorServer = new WireMonitorServer(6789); + + wireMonitorServer.start(); + + Thread.sleep(1000); + + JMeterTest scriptGET = + new JMeterTest(new File(getAMResourceLocation() + File.separator + "scripts" + + File.separator + + "content_type_check_for_GET_script.jmx")); + + manager.runTest(scriptGET); + + while (true) { + String reply = wireMonitorServer.getCapturedMessage(); + if (reply.length() > 1) { + if (reply.contains("ThisParamIsRequiredForTest_GET")) { + /** + * Assert for the Content-Type header + */ + Assert.assertTrue(!reply.contains("Content-Type"), + "Content-Type header has been added to GET request forcefully!!"); + } + } + break; + } + + wireMonitorServer = new WireMonitorServer(6789); + + wireMonitorServer.start(); + + Thread.sleep(1000); + + JMeterTest scriptDELETE = + new JMeterTest(new File(getAMResourceLocation() + File.separator + "scripts" + + File.separator + + "content_type_check_for_DELETE_script.jmx")); + + manager.runTest(scriptDELETE); + + while (true) { + String reply = wireMonitorServer.getCapturedMessage(); + if (reply.length() > 1) { + if (reply.contains("ThisParamIsRequiredForTest_DELETE")) { + /** + * Assert for the Content-Type header + */ + Assert.assertTrue(!reply.contains("Content-Type"), + "Content-Type header has been added to DELETE request forcefully!!"); + } + } + break; + } + + } +} diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/API_Manager_Login_Test.jmx b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/API_Manager_Login_Test.jmx new file mode 100644 index 0000000000..6e46aeeaee --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/API_Manager_Login_Test.jmx @@ -0,0 +1,356 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + Youtube + = + + + context + /youtube + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + Tester_Acc2 + = + + + publisherName + admin + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://localhost:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + 200 + + Assertion.response_code + false + 2 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/aggregate_report.jtl + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + + + + diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest.jmx b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest.jmx new file mode 100644 index 0000000000..9a51a78289 --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest.jmx @@ -0,0 +1,2888 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + GOOG_Stock_API + = + + + context + /GStock + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + userPrefix + tenant + = + + + resourceMethods + POST + = + + + authTypes + Application & Application User + = + + + throttlingTiers + Unlimited + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_number + # + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <ser:getTenant> + <!--Optional:--> + <ser:tenantDomain>domain${tenant_number}.com</ser:tenantDomain> + </ser:getTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:getTenant + true + false + + + + undefined + tenant_exists + //*[local-name()='active']/text() + false + false + true + tenant_exists + + + + false + true + true + false + + + + + ${tenant_exists}==false + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org" xmlns:xsd="http://beans.common.stratos.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <ser:addTenant> + <!--Optional:--> + <ser:tenantInfoBean> + <!--Optional:--> + <xsd:active>1</xsd:active> + <!--Optional:--> + <xsd:admin>${userPrefix}${tenant_number}</xsd:admin> + <!--Optional:--> + <xsd:adminPassword>1qaz2wsx@</xsd:adminPassword> + <!--Optional:--> + <xsd:createdDate>2013-02-22T08:22:54</xsd:createdDate> + <!--Optional:--> + <xsd:email>ruwany@wso2.com</xsd:email> + <!--Optional:--> + <xsd:firstname>User1</xsd:firstname> + <!--Optional:--> + <xsd:lastname>LastName1</xsd:lastname> + <!--Optional:--> + <xsd:tenantDomain>domain${tenant_number}.com</xsd:tenantDomain> + <!--Optional:--> + <xsd:tenantId>0</xsd:tenantId> + <!--Optional:--> + <xsd:usagePlan>Demo</xsd:usagePlan> + </ser:tenantInfoBean> + </ser:addTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:addTenant + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + 202 + + Assertion.response_code + false + 1 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + + 1363957740000 + 1363957740000 + false + + + + + + + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_counter + # + false + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>${userPrefix}${tenant_counter}@domain${tenant_counter}.com</aut:username> + <!--Optional:--> + <aut:password>1qaz2wsx@</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <xsd:getAllRolesNames> + <!--Optional:--> + <xsd:filter>*</xsd:filter> + <!--Optional:--> + <xsd:limit>100</xsd:limit> + </xsd:getAllRolesNames> + </soapenv:Body> +</soapenv:Envelope> + + urn:getAllRolesNames + true + false + + + + undefined + role_exists + //*[local-name()='itemName']/text()='subscriber_role' + false + false + true + + + + false + true + true + false + + + + + ${role_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addRole> + <!--Optional:--> + <mgt:roleName>subscriber_role</mgt:roleName> + <mgt:permissions>/permission/admin/login</mgt:permissions> + <mgt:permissions>/permission/admin/manage/api/subscribe</mgt:permissions> + <mgt:isSharedRole>false</mgt:isSharedRole> + </mgt:addRole> + </soapenv:Body> +</soapenv:Envelope> + + urn:addRole + true + false + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + user_ref + # + false + + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:listUsers> + <!--Optional:--> + <mgt:filter>${userPrefix}${tenant_counter}_user${user_ref}</mgt:filter> + <mgt:limit>10</mgt:limit> + </mgt:listUsers> + </soapenv:Body> +</soapenv:Envelope> + + urn:listUsers + true + false + + + + false + user_exists + //*[local-name()='return']/text()='${userPrefix}${tenant_counter}_user${user_ref}' + false + false + true + + + + false + true + true + false + + + + + ${user_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd" xmlns:xsd="http://common.mgt.user.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addUser> + <!--Optional:--> + <mgt:userName>${userPrefix}${tenant_counter}_user${user_ref}</mgt:userName> + <!--Optional:--> + <mgt:password>1qaz2wsx@</mgt:password> + <mgt:roles>subscriber_role</mgt:roles> + </mgt:addUser> + </soapenv:Body> +</soapenv:Envelope> + + urn:addUser + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy_report.jtl + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + String currentDir = System.getProperty("user.dir"); +FileOutputStream f = new FileOutputStream(currentDir + "/results.csv"); + + + false + + + + + + false + rfc2109 + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}@domain${input_value}.com + = + true + username + + + false + ${publisherPass} + = + true + password + + + false + null + = + true + tenant + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${numberOfAPIs} + + + + 1 + ${numberOfAPIs} + 1 + api_id + # + false + + + + + + + false + addAPI + = + true + action + + + false + ${apinm}${api_id} + = + true + name + + + false + ${context}${api_id} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + /* + = + true + uriTemplate-0 + + + false + ${resourceMethods} + = + true + resourceMethod-0 + + + false + ${authTypes} + = + true + resourceMethodAuthType-0 + + + false + ${throttlingTiers} + = + true + resourceMethodThrottlingTier-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + http + = + true + http_checked + + + false + https + = + true + https_checked + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm}${api_id} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + false + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${numberOfAPIs} + + + + 1 + ${numberOfAPIs} + 1 + api_id + # + false + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm}${api_id} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + Unlimited + = + true + tier + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + null + = + true + callbackUrl + + + false + ALL + = + true + authorizedDomains + + + false + 3600 + = + true + validityTime + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com&password=1qaz2wsx@&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + +String tenant_count = vars.get("input_value"); +String user_count = vars.get("subsCount"); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + +String currentDir = System.getProperty("user.dir"); + +vars.put("current_directory" , currentDir); + +String context = vars.get("context"); +String apiID = vars.get("api_id"); + +f = new FileOutputStream(currentDir + "/results.csv", true); + +p = new PrintStream(f); + +this.interpreter.setOut(p); + +print("domain"+ tenant_count+".com" + "@@@" + accessToken +"@@@" + context+apiID); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + /t/domain${input_value}.com${context}${api_id}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getAllPublishedAPIs + = + true + action + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/api/listing/ajax/list.jag + POST + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + true + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getRecentlyAddedAPIs + = + true + action + + + false + 2000 + = + true + limit + + + false + domain1.com + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + store/site/blocks/api/recently-added/ajax/list.jag + POST + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getAllTags + = + true + action + + + + ${storeIP} + ${storePort} + + + + + store/site/blocks/tag/tag-cloud/ajax/list.jag + POST + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 10 + 1 + 1365001797000 + 1365001797000 + false + + + + + + + + import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.LineNumberReader; + +String currentDir = System.getProperty("user.dir"); + +LineNumberReader lnr = new LineNumberReader(new FileReader(new File(currentDir + "/results.csv"))); +lnr.skip(Long.MAX_VALUE); + +int min = 1; +int max = lnr.getLineNumber(); + +Random r = new Random(); +int i1 = r.nextInt(max - min + 1) + min; + +vars.put("random_value",""+i1); + +String lineConcerened = ""; + +BufferedReader br = new BufferedReader(new FileReader(new File(currentDir + "/results.csv"))); + +String strLine =""; + +for(int i=0; i<max; i++){ + strLine = br.readLine(); + if(i==i1-1){ + System.out.println(strLine); + lineConcerened = strLine; + } +} + +String[] splitVals = lineConcerened.split("@@@"); +String userName = splitVals[0]; +String token = splitVals[1]; +String contextAndAPIId = splitVals[2]; + +vars.put("line_count",""+i1); +vars.put("domain",userName); +vars.put("token",token); +vars.put("contextAndAPIId",contextAndAPIId); + + + false + + + + false + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + /t/${domain}${contextAndAPIId}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${token} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + false + true + true + false + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/aggregate_report.jtl + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + + + + diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest_new_tenant.jmx b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest_new_tenant.jmx new file mode 100644 index 0000000000..f020021503 --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest_new_tenant.jmx @@ -0,0 +1,2657 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + GOOG_Stock_API_New + = + + + context + /GStocknew + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + userPrefix + tenant + = + + + resourceMethods + POST + = + + + authTypes + Application & Application User + = + + + throttlingTiers + Unlimited + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_number + # + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <ser:getTenant> + <!--Optional:--> + <ser:tenantDomain>domain${tenant_number}.com</ser:tenantDomain> + </ser:getTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:getTenant + true + false + + + + undefined + tenant_exists + //*[local-name()='active']/text() + false + false + true + tenant_exists + + + + false + true + true + false + + + + + ${tenant_exists}==false + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org" xmlns:xsd="http://beans.common.stratos.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <ser:addTenant> + <!--Optional:--> + <ser:tenantInfoBean> + <!--Optional:--> + <xsd:active>1</xsd:active> + <!--Optional:--> + <xsd:admin>${userPrefix}${tenant_number}</xsd:admin> + <!--Optional:--> + <xsd:adminPassword>1qaz2wsx@</xsd:adminPassword> + <!--Optional:--> + <xsd:createdDate>2013-02-22T08:22:54</xsd:createdDate> + <!--Optional:--> + <xsd:email>ruwany@wso2.com</xsd:email> + <!--Optional:--> + <xsd:firstname>User1</xsd:firstname> + <!--Optional:--> + <xsd:lastname>LastName1</xsd:lastname> + <!--Optional:--> + <xsd:tenantDomain>domain${tenant_number}.com</xsd:tenantDomain> + <!--Optional:--> + <xsd:tenantId>0</xsd:tenantId> + <!--Optional:--> + <xsd:usagePlan>Demo</xsd:usagePlan> + </ser:tenantInfoBean> + </ser:addTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:addTenant + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + 202 + + Assertion.response_code + false + 1 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + + 1363957740000 + 1363957740000 + false + + + + + + + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_counter + # + false + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>${userPrefix}${tenant_counter}@domain${tenant_counter}.com</aut:username> + <!--Optional:--> + <aut:password>1qaz2wsx@</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <xsd:getAllRolesNames> + <!--Optional:--> + <xsd:filter>*</xsd:filter> + <!--Optional:--> + <xsd:limit>100</xsd:limit> + </xsd:getAllRolesNames> + </soapenv:Body> +</soapenv:Envelope> + + urn:getAllRolesNames + true + false + + + + undefined + role_exists + //*[local-name()='itemName']/text()='subscriber_role_new' + false + false + true + + + + false + true + true + false + + + + + ${role_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addRole> + <!--Optional:--> + <mgt:roleName>subscriber_role_new</mgt:roleName> + <mgt:permissions>/permission/admin/login</mgt:permissions> + <mgt:permissions>/permission/admin/manage/api/subscribe</mgt:permissions> + <mgt:isSharedRole>false</mgt:isSharedRole> + </mgt:addRole> + </soapenv:Body> +</soapenv:Envelope> + + urn:addRole + true + false + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + user_ref + # + false + + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:listUsers> + <!--Optional:--> + <mgt:filter>${userPrefix}${tenant_counter}_user${user_ref}</mgt:filter> + <mgt:limit>10</mgt:limit> + </mgt:listUsers> + </soapenv:Body> +</soapenv:Envelope> + + urn:listUsers + true + false + + + + false + user_exists + //*[local-name()='return']/text()='${userPrefix}${tenant_counter}_user${user_ref}' + false + false + true + + + + false + true + true + false + + + + + ${user_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd" xmlns:xsd="http://common.mgt.user.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addUser> + <!--Optional:--> + <mgt:userName>${userPrefix}${tenant_counter}_user${user_ref}</mgt:userName> + <!--Optional:--> + <mgt:password>1qaz2wsx@</mgt:password> + <mgt:roles>subscriber_role_new</mgt:roles> + </mgt:addUser> + </soapenv:Body> +</soapenv:Envelope> + + urn:addUser + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy_report.jtl + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + String currentDir = System.getProperty("user.dir"); +FileOutputStream f = new FileOutputStream(currentDir + "/results.csv"); + + + false + + + + + + false + rfc2109 + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}@domain${input_value}.com + = + true + username + + + false + ${publisherPass} + = + true + password + + + false + null + = + true + tenant + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${numberOfAPIs} + + + + 1 + ${numberOfAPIs} + 1 + api_id + # + false + + + + + + + false + addAPI + = + true + action + + + false + ${apinm}${api_id} + = + true + name + + + false + ${context}${api_id} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + /* + = + true + uriTemplate-0 + + + false + ${resourceMethods} + = + true + resourceMethod-0 + + + false + ${authTypes} + = + true + resourceMethodAuthType-0 + + + false + ${throttlingTiers} + = + true + resourceMethodThrottlingTier-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + http + = + true + http_checked + + + false + https + = + true + https_checked + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm}${api_id} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + false + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${numberOfAPIs} + + + + 1 + ${numberOfAPIs} + 1 + api_id + # + false + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm}${api_id} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + Unlimited + = + true + tier + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + null + = + true + callbackUrl + + + false + ALL + = + true + authorizedDomains + + + false + 3600 + = + true + validityTime + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com&password=1qaz2wsx@&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + +String tenant_count = vars.get("input_value"); +String user_count = vars.get("subsCount"); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + +String currentDir = System.getProperty("user.dir"); + +vars.put("current_directory" , currentDir); + +String context = vars.get("context"); +String apiID = vars.get("api_id"); + +f = new FileOutputStream(currentDir + "/results.csv", true); + +p = new PrintStream(f); + +this.interpreter.setOut(p); + +print("domain"+ tenant_count+".com" + "@@@" + accessToken +"@@@" + context+apiID); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + /t/domain${input_value}.com${context}${api_id}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getAllPublishedAPIs + = + true + action + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/api/listing/ajax/list.jag + POST + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + true + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getRecentlyAddedAPIs + = + true + action + + + false + 2000 + = + true + limit + + + false + domain1.com + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + store/site/blocks/api/recently-added/ajax/list.jag + POST + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getAllTags + = + true + action + + + + ${storeIP} + ${storePort} + + + + + store/site/blocks/tag/tag-cloud/ajax/list.jag + POST + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 10 + 1 + 1365001797000 + 1365001797000 + false + + + + + + + + import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.LineNumberReader; + +String currentDir = System.getProperty("user.dir"); + +LineNumberReader lnr = new LineNumberReader(new FileReader(new File(currentDir + "/results.csv"))); +lnr.skip(Long.MAX_VALUE); + +int min = 1; +int max = lnr.getLineNumber(); + +Random r = new Random(); +int i1 = r.nextInt(max - min + 1) + min; + +vars.put("random_value",""+i1); + +String lineConcerened = ""; + +BufferedReader br = new BufferedReader(new FileReader(new File(currentDir + "/results.csv"))); + +String strLine =""; + +for(int i=0; i<max; i++){ + strLine = br.readLine(); + if(i==i1-1){ + System.out.println(strLine); + lineConcerened = strLine; + } +} + +String[] splitVals = lineConcerened.split("@@@"); +String userName = splitVals[0]; +String token = splitVals[1]; +String contextAndAPIId = splitVals[2]; + +vars.put("line_count",""+i1); +vars.put("domain",userName); +vars.put("token",token); +vars.put("contextAndAPIId",contextAndAPIId); + + + false + + + + false + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + /t/${domain}${contextAndAPIId}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${token} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + false + true + true + false + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/DomainRestrictionTest.jmx b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/DomainRestrictionTest.jmx new file mode 100644 index 0000000000..e7d00e1f28 --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/DomainRestrictionTest.jmx @@ -0,0 +1,1188 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + basic_functions_api_domain + = + + + context + /basic_functions_api_domain + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + super_tenant_user + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + https://lh6.ggpht.com/RNc8dD2hXG_rWGzlj09ZwAe1sXVvLWkeYT3ePx7zePCy4ZVV2XMGIxAzup4cKM85NFtL=w124 + = + true + apiThumb + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + POST + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Unlimited, Unlimited, Unlimited, Unlimited, Unlimited + = + true + resourceMethodThrottlingTier-0 + + + false + http + = + true + http_checked + + + false + https + = + true + https_checked + + + false + Application User + = + true + resourceMethodAuthType-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${noOfSubscribers} + + + + 1 + 10000 + 1 + subsCount + # + false + + + + + + + false + addUser + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + false + ${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}@test.com|| + = + true + allFieldsValues + + + false + + = + true + + + false + + = + true + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/sign-up/ajax/user-add.jag + POST + true + false + true + false + Java + false + + + + + 50 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//int eq = resp.indexOf("=", def - 8); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println("APP ID : " + appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + true + true + true + false + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + true + true + true + false + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + null + = + true + callbackUrl + + + false + wso2.org + = + true + authorizedDomains + + + false + 3600 + = + true + validityTime + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + refreshToken + = + true + action + + + false + application + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${token} + = + true + oldAccessToken + + + false + ${consumerKey} + = + true + clientId + + + false + ${consumerSecret} + = + true + clientSecret + + + false + 5000 + = + true + validityTime + + + false + wso2.org + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${subsPrefix}_${subsCount}&password=subscriber@123&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + referer + wso2.org + + + + + + + 200 + + Assertion.response_data + false + 6 + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + + diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/basic_functionality_test.jmx b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/basic_functionality_test.jmx new file mode 100644 index 0000000000..9e6ed8e691 --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/basic_functionality_test.jmx @@ -0,0 +1,1184 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + basic_functions_api + = + + + context + /basic_functions_api + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + super_tenant_user + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + https://lh6.ggpht.com/RNc8dD2hXG_rWGzlj09ZwAe1sXVvLWkeYT3ePx7zePCy4ZVV2XMGIxAzup4cKM85NFtL=w124 + = + true + apiThumb + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + POST + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Unlimited, Unlimited, Unlimited, Unlimited, Unlimited + = + true + resourceMethodThrottlingTier-0 + + + false + http + = + true + http_checked + + + false + https + = + true + https_checked + + + false + Application User + = + true + resourceMethodAuthType-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${noOfSubscribers} + + + + 1 + 10000 + 1 + subsCount + # + false + + + + + + + false + addUser + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + false + ${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}@test.com|| + = + true + allFieldsValues + + + false + + = + true + + + false + + = + true + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/sign-up/ajax/user-add.jag + POST + true + false + true + false + Java + false + + + + + 50 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//int eq = resp.indexOf("=", def - 8); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println("APP ID : " + appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + true + true + true + false + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + true + true + true + false + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + null + = + true + callbackUrl + + + false + ALL + = + true + authorizedDomains + + + false + 3600 + = + true + validityTime + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + refreshToken + = + true + action + + + false + application + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${token} + = + true + oldAccessToken + + + false + ${consumerKey} + = + true + clientId + + + false + ${consumerSecret} + = + true + clientSecret + + + false + 5000 + = + true + validityTime + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${subsPrefix}_${subsCount}&password=subscriber@123&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + No data found + + Assertion.response_data + false + 6 + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + + diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/content_type_check_for_DELETE_script.jmx b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/content_type_check_for_DELETE_script.jmx new file mode 100644 index 0000000000..8d9d4513fc --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/content_type_check_for_DELETE_script.jmx @@ -0,0 +1,477 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + testContentTypeHeaderAPI + = + + + context + /testContentTypeHeaderAPI + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + + + + + false + rfc2109 + + + + + + + false + login + = + true + action + + + false + admin + = + true + username + + + false + admin + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + null + = + true + callbackUrl + + + false + ALL + = + true + authorizedDomains + + + false + 3600 + = + true + validityTime + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + +System.out.println("####################################################################### Access Token Response: " + jsonResponse); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=admin&password=admin&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + false + ThisParamIsRequiredForTest_DELETE + = + true + param + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version}/ + DELETE + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/content_type_check_for_GET_script.jmx b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/content_type_check_for_GET_script.jmx new file mode 100644 index 0000000000..a8bafcae62 --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/content_type_check_for_GET_script.jmx @@ -0,0 +1,477 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + testContentTypeHeaderAPI + = + + + context + /testContentTypeHeaderAPI + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + + + + + false + rfc2109 + + + + + + + false + login + = + true + action + + + false + admin + = + true + username + + + false + admin + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + null + = + true + callbackUrl + + + false + ALL + = + true + authorizedDomains + + + false + 5600 + = + true + validityTime + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + +System.out.println("####################################################################### Access Token Response: " + jsonResponse); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=admin&password=admin&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + false + ThisParamIsRequiredForTest_GET + = + true + param + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version}/ + GET + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/content_type_check_publish_and_subscribe_script.jmx b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/content_type_check_publish_and_subscribe_script.jmx new file mode 100644 index 0000000000..cbeec25075 --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/content_type_check_publish_and_subscribe_script.jmx @@ -0,0 +1,665 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + testContentTypeHeaderAPI + = + + + context + /testContentTypeHeaderAPI + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + + + + + false + rfc2109 + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + 127.0.0.1:6789 + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + DELETE,GET + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + Application User,Application User + = + true + resourceMethodAuthType-0 + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Unlimited, Unlimited, Unlimited, Unlimited, Unlimited + = + true + resourceMethodThrottlingTier-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + admin + = + true + username + + + false + admin + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + admin + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//String appid = resp.substring(def+6, resp.indexOf("," )); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println("AppId: " + appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + 1.0.0 + = + true + version + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/transport_restriction_check.jmx b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/transport_restriction_check.jmx new file mode 100644 index 0000000000..8d4c843263 --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/resources/artifacts/AM/scripts/transport_restriction_check.jmx @@ -0,0 +1,1121 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + restricted_api + = + + + context + restricted_api + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + transport_users + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + https://lh6.ggpht.com/RNc8dD2hXG_rWGzlj09ZwAe1sXVvLWkeYT3ePx7zePCy4ZVV2XMGIxAzup4cKM85NFtL=w124 + = + true + apiThumb + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + POST + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Unlimited, Unlimited, Unlimited, Unlimited, Unlimited + = + true + resourceMethodThrottlingTier-0 + + + false + + = + true + http_checked + + + false + https + = + true + https_checked + + + false + Application User + = + true + resourceMethodAuthType-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${noOfSubscribers} + + + + 1 + 10000 + 1 + subsCount + # + false + + + + + + + false + addUser + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + false + ${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}@test.com|| + = + true + allFieldsValues + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/sign-up/ajax/user-add.jag + POST + true + false + true + false + Java + false + + + + + 50 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//int eq = resp.indexOf("=", def - 8); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + 1.0.0 + = + true + version + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + null + = + true + callbackUrl + + + false + ALL + = + true + authorizedDomains + + + false + 3600 + = + true + validityTime + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${subsPrefix}_${subsCount}&password=subscriber@123&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + http + + ${context}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + Unsupported Transport + + Assertion.response_data + true + 2 + + + + + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + ${context}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/automation.xml b/modules/integration/tests-integration/tests-jmeter/src/test/resources/automation.xml new file mode 100644 index 0000000000..75ff50a12d --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/resources/automation.xml @@ -0,0 +1,301 @@ + + + + + + + + 60000 + + standalone + + false + + false + + + + + + + http://10.100.2.51:4444/wd/hub/ + + + + firefox + + /home/test/name/webDriver + + + + + + + jdbc:h2:testDB + wso2carbon + wso2carbon + org.h2.Driver + + + jdbc:h2:testDB + wso2carbon + wso2carbon + org.h2.Driver + + + jdbc:mysql://localhost:3306/ + root + admin + com.mysql.jdbc.Driver + + + + + + + keystores/products/wso2carbon.jks + + JKS + + wso2carbon + + wso2carbon + + wso2carbon + + + + + keystores/products/client-truststore.jks + + JKS + + wso2carbon + + + + + + https://wso2.org/repo + file:///home/krishantha/test + + + + + + + + + + admin + admin + + + + + testuser11 + testuser11 + + + testuser21 + testuser21 + + + + + + + + + admin + admin + + + + + testuser11 + testuser11 + + + testuser21 + testuser21 + + + + + + + admin + admin + + + + + testuser11 + testuser11 + + + testuser21 + testuser21 + + + + + + + admin + admin + + + + + testuse11 + testuse11 + + + testuse21 + testuse21 + + + + + + + + + + + + + am.wso2con.com + mgt.am.wso2con.com + + + 8243 + 8280 + + + + + + + + localhost + + + 9764 + 9444 + 9446 + 8280 + + + + + + + + localhost + + + 9763 + 9443 + 8243 + 8280 + + + + + + + + localhost + + + 9765 + 9445 + 9446 + 8280 + + + + + + + + + + + + org.wso2.carbon.integration.common.extensions.carbonserver.CarbonServerExtension + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/automationXMLSchema.xsd b/modules/integration/tests-integration/tests-jmeter/src/test/resources/automationXMLSchema.xsd new file mode 100644 index 0000000000..42c5fe8c16 --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/resources/automationXMLSchema.xsd @@ -0,0 +1,498 @@ + + + + + + + ================================================= + Parameters ================================================= + Browser type with used by framework to execute UI test, supported types + - chrome|firefox|opera|ie|htmlUnit + + + + + + + Change this to edit wait time for test + artifact deployment + + + + + + Change this to product|platform/cloud to + execute test on specific environment + + + + + + + Change this to true if you want to generate + coverage statistics + + + + + + Change this to true if you want to enable + framework dashboard + + + + + + + + + + + + + + + Change to enable remote webDriver + URL of remote webDriver server + + + + + + + + + + + + + Type of the browser selenium tests + are running" + + + + + + + + path to webDriver + executable - required only for + chrome + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + KeyStore which will be used for + encrypting/decrypting passwords + and other sensitive information. + + + + + + + Keystore file location + + + + + + Keystore type (JKS/PKCS12 etc.) + + + + + + Keystore password + + + + + + Private Key alias + + + + + + Private Key password + + + + + + + + + + System wide trust-store which is used to + maintain the certificates of all + the trusted parties. + + + + + + + trust-store file location + + + + + + trust-store type (JKS/PKCS12 + etc.) + + + + + + trust-store password + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/axis2config/axis2_client.xml b/modules/integration/tests-integration/tests-jmeter/src/test/resources/axis2config/axis2_client.xml new file mode 100644 index 0000000000..db07954a47 --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/resources/axis2config/axis2_client.xml @@ -0,0 +1,299 @@ + + + + + + + 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/integration/tests-integration/tests-jmeter/src/test/resources/client/modules/addressing-1.6.1-wso2v11-20140804.232441-526.mar b/modules/integration/tests-integration/tests-jmeter/src/test/resources/client/modules/addressing-1.6.1-wso2v11-20140804.232441-526.mar new file mode 100644 index 0000000000..a42c058499 Binary files /dev/null and b/modules/integration/tests-integration/tests-jmeter/src/test/resources/client/modules/addressing-1.6.1-wso2v11-20140804.232441-526.mar differ diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/client/modules/addressing-1.6.1-wso2v9.mar b/modules/integration/tests-integration/tests-jmeter/src/test/resources/client/modules/addressing-1.6.1-wso2v9.mar new file mode 100644 index 0000000000..d3871a1586 Binary files /dev/null and b/modules/integration/tests-integration/tests-jmeter/src/test/resources/client/modules/addressing-1.6.1-wso2v9.mar differ diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/emma.properties b/modules/integration/tests-integration/tests-jmeter/src/test/resources/emma.properties new file mode 100644 index 0000000000..b39fffdb8e --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/resources/emma.properties @@ -0,0 +1,103 @@ +# ------------------------------------------------------------- +# +# for user-editable property overrides use one of these options: +# +# (1) option-specific command line overrides, e.g. +# -Dreport.txt.out.file=coverage.txt +# +# (2) '-p ' command line option, +# +# (3) 'emma.properties' resource placed somewhere in the classpath +# (e.g., in \classes directory -- note that it does +# not exist by default), +# +# (4) '-Demma.*' JVM options, e.g. +# -Demma.report.txt.out.file=coverage.txt +# +# (5) 'emma.properties' JVM option pointing to a properties file +# -Demma.properties=./myproperties.txt +# ------------------------------------------------------------- + +# ------------------------------------------------------------- +# logging properties: + +verbosity.level: none + +# classloading properties: + +#clsload.forced_delegation_filter: +#clsload.through_delegation_filter: -* + +# ------------------------------------------------------------- + +# instrumentation properties: + +instr.exclude_empty_classes: true +instr.exclude_synthetic_methods: true +instr.exclude_bridge_methods: true +instr.do_suid_compensation: true + +# ------------------------------------------------------------- + +# runtime properties: + +rt.control: false +rt.control.host: localhost +rt.control.port: 44444 + +rt.filelock: true +rt.filelock.portbase: 59141 +rt.filelock.maxtime: 120000 +rt.filelock.retries: 11 + +# ------------------------------------------------------------- + +# apprunner session data output properties: + +session.out.file: coverage.es +session.out.merge: true + +# ------------------------------------------------------------- + +# runtime coverage data output properties: + +coverage.out.file: coverage.ec +coverage.out.merge: true + +# ------------------------------------------------------------- + +# instr metadata output properties: + +metadata.out.file: coverage.em +metadata.out.merge: true + +# ------------------------------------------------------------- + +# common report defaults: + +report.units: instr +report.depth: method +report.columns: name, line, block, method, class +report.sort: -line,-block,-method,-class,+name +report.metrics: method:40,block:80,line:40,class:100 + +# ------------------------------------------------------------- +# txt report properties: + +report.txt.depth: all +report.txt.columns: class,method,block,line,name +report.txt.out.file: coverage.txt + +# ------------------------------------------------------------- +# html report properties: + +#report.html.out.dir: coverage +report.html.out.encoding: ISO-8859-1 + +# ------------------------------------------------------------- +# xml report properties: + +report.xml.out.file: coverage.xml +report.xml.out.encoding: UTF-8 +# ------------------------------------------------------------- +# end of file diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/keystores/products/client-truststore.jks b/modules/integration/tests-integration/tests-jmeter/src/test/resources/keystores/products/client-truststore.jks new file mode 100644 index 0000000000..9e3a51db3e Binary files /dev/null and b/modules/integration/tests-integration/tests-jmeter/src/test/resources/keystores/products/client-truststore.jks differ diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/keystores/products/wso2carbon.jks b/modules/integration/tests-integration/tests-jmeter/src/test/resources/keystores/products/wso2carbon.jks new file mode 100644 index 0000000000..7942c53cf9 Binary files /dev/null and b/modules/integration/tests-integration/tests-jmeter/src/test/resources/keystores/products/wso2carbon.jks differ diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/keystores/stratos/client-truststore.jks b/modules/integration/tests-integration/tests-jmeter/src/test/resources/keystores/stratos/client-truststore.jks new file mode 100644 index 0000000000..9e3a51db3e Binary files /dev/null and b/modules/integration/tests-integration/tests-jmeter/src/test/resources/keystores/stratos/client-truststore.jks differ diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/keystores/stratos/wso2carbon.jks b/modules/integration/tests-integration/tests-jmeter/src/test/resources/keystores/stratos/wso2carbon.jks new file mode 100644 index 0000000000..7942c53cf9 Binary files /dev/null and b/modules/integration/tests-integration/tests-jmeter/src/test/resources/keystores/stratos/wso2carbon.jks differ diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/log4j.properties b/modules/integration/tests-integration/tests-jmeter/src/test/resources/log4j.properties new file mode 100644 index 0000000000..693babfefe --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/resources/log4j.properties @@ -0,0 +1,43 @@ +# +# Copyright 2009 WSO2, Inc. (http://wso2.com) +# +# 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 Carbon +# +# 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 Carbon Management Console, and those +# settings will override the settings in this file. +# + +log4j.rootLogger=INFO, console, Default + +log4j.logger.org.wso2=INFO + +#Automation file apender +log4j.appender.Default=org.apache.log4j.RollingFileAppender +log4j.appender.Default.File=logs/automation.log +log4j.appender.Default.Append=true +log4j.appender.Default.MaxFileSize=10MB +log4j.appender.Default.MaxBackupIndex=10 +log4j.appender.Default.layout=org.apache.log4j.PatternLayout +log4j.appender.Default.layout.ConversionPattern=%d{ISO8601} %-5p [%c] - %m%n + + +#Automation console apender +log4j.appender.console=org.apache.log4j.ConsoleAppender +log4j.appender.console.layout=org.apache.log4j.PatternLayout +log4j.appender.console.layout.ConversionPattern=%-5p [%c] - %m%n diff --git a/modules/integration/tests-integration/tests-jmeter/src/test/resources/testng.xml b/modules/integration/tests-integration/tests-jmeter/src/test/resources/testng.xml new file mode 100644 index 0000000000..b93185f7e6 --- /dev/null +++ b/modules/integration/tests-integration/tests-jmeter/src/test/resources/testng.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/pom.xml b/modules/integration/tests-integration/tests-scenario/pom.xml new file mode 100644 index 0000000000..0e21172c8f --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/pom.xml @@ -0,0 +1,248 @@ + + + + org.wso2.am + integration + 1.7.0-SNAPSHOT + ../../pom.xml + + + 1.7.0-SNAPSHOT + 4.0.0 + org.wso2.carbon.am.tests + WSO2 API Manager - Integration Tests - Scenarios + jar + + + + + maven-surefire-plugin + 2.12.4 + false + + + -Xms512m -Xmx1024m -XX:MaxPermSize=128m + true + false + false + + src/test/resources/testng.xml + + + + framework.resource.location + + ${basedir}/src/test/resources/ + + + + server.list + + AM + + + + usedefaultlisteners + false + + ${basedir}/target/security-verifier/ + false + + ${basedir}/../../../distribution/product/target/wso2am-${project.version}.zip + + ${basedir}/target/emma + ${basedir}/src/test/resources/instrumentation.txt + ${basedir}/src/test/resources/filters.txt + ${basedir}/target/emma + + ${basedir}/target + + + + maven-dependency-plugin + + + copy-emma-dependencies + compile + + copy-dependencies + + + ${project.build.directory}/emma + jar + emma,org.wso2.carbon.automation.core + + + + + copy-secVerifier + compile + + copy-dependencies + + + ${basedir}/target/security-verifier + aar + SecVerifier + true + + + + unpack-mar-jks + compile + + unpack + + + + + org.wso2.am + wso2am + ${project.version} + zip + true + ${basedir}/target/tobeCopied/ + **/*.jks,**/*.mar,**/synapse_sample*.xml + + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + + test-jar + + + + + + + maven-resources-plugin + 2.6 + + + copy-resources-jks + compile + + copy-resources + + + ${basedir}/src/test/resources/keystores/products + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/resources/security/ + + + **/*.jks + + + + + + + copy-stratos-jks + compile + + copy-resources + + + ${basedir}/src/test/resources/keystores/stratos + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/resources/security/ + + + **/*.jks + + + + + + + copy-sample-jks + compile + + copy-resources + + + ${basedir}/src/test/resources/keystores/products + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/samples/resources/security/ + + + **/*.jks + + + + + + + copy-resources-mar + compile + + copy-resources + + + ${basedir}/src/test/resources/client/modules + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/deployment/client/modules + + + **/*.mar + + + + + + + + + + + + org.wso2.am + admin-clients + ${project.version} + + + org.wso2.am + integration-test-utils + ${project.version} + + + org.wso2.carbon.automation + org.wso2.carbon.automation.tools.jmeter + ${test-automation-framework-version} + + + org.wso2.carbon + org.wso2.carbon.apimgt.hostobjects + 1.2.0 + + + + 4.2.5 + + diff --git a/modules/integration/tests-integration/tests-scenario/src/test/java/org/testlink/HOTestCase.java b/modules/integration/tests-integration/tests-scenario/src/test/java/org/testlink/HOTestCase.java new file mode 100644 index 0000000000..8fb5f8c3bd --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/java/org/testlink/HOTestCase.java @@ -0,0 +1,429 @@ +/* + * + * Copyright (c) 2005-2010, 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.testlink; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.am.integration.test.utils.APIMgtTestUtil; +import org.wso2.am.integration.test.utils.bean.*; +import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; +import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; +import org.wso2.carbon.automation.extensions.jmeter.JMeterTest; +import org.wso2.carbon.automation.extensions.jmeter.JMeterTestManager; +import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; +import org.wso2.carbon.utils.FileManipulator; +import org.wso2.carbon.utils.ServerConstants; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.util.HashMap; +import java.util.Map; + +import static org.testng.Assert.assertNotNull; + +public class HOTestCase extends APIManagerIntegrationTest { + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private ServerConfigurationManager serverConfigurationManager; + private String publisherURLHttp; + private String storeURLHttp; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(); + if (isBuilderEnabled()) { + /* + If test run in external distributed deployment you need to copy following resources accordingly. + configFiles/hostobjecttest/api-manager.xml + configFiles/tokenTest/log4j.properties + Also need to copy the content of /resources/artifacts/AM/jaggery to servers following folder folder + repository/deployment/server/jaggeryapps/testapp + */ + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + serverConfigurationManager = new ServerConfigurationManager(context); + serverConfigurationManager.applyConfiguration(new File(getAMResourceLocation() + + File.separator + + "configFiles/hostobjecttest/" + + "api-manager.xml")); + serverConfigurationManager.applyConfiguration(new File(getAMResourceLocation() + + File.separator + + "configFiles/tokenTest/" + + "log4j.properties")); + super.init(); + } else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + apiPublisher = new APIPublisherRestClient(publisherURLHttp); + apiStore = new APIStoreRestClient(storeURLHttp); + + apiPublisher.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + apiStore.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + } + + private void copySampleFile(String sourcePath, String destPath) { + File sourceFile = new File(sourcePath); + File destFile = new File(destPath); + try { + FileManipulator.copyFile(sourceFile, destFile); + } catch (IOException e) { + log.error("Error while copying the sample into Jaggery server", e); + } + } + + private String computeDestPath(String fileName) { + String serverRoot = System.getProperty(ServerConstants.CARBON_HOME); + String deploymentPath = serverRoot + "/repository/deployment/server/jaggeryapps/testapp"; + File depFile = new File(deploymentPath); + if (!depFile.exists() && !depFile.mkdir()) { + log.error("Error while creating the deployment folder : " + + deploymentPath); + } + return deploymentPath + File.separator + fileName; + } + + private String computeSourcePath(String fileName) { + + String sourcePath = getAMResourceLocation() + + File.separator + "jaggery/" + fileName; + return sourcePath; + } + + @Test(groups = { "wso2.am" }, description = "API Life cycle test case") + public void testHostObjectTestCase() throws Exception { + //Tenant Create test cases - This will create new tenant in the system + JMeterTest script = + new JMeterTest(new File(getAMResourceLocation() + File.separator + "scripts" + + File.separator + "tenant_create.jmx")); + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(script); + //End of tenant creation + + String APIName = "HostObjectTestAPI"; + String APIContext = "HostObjectTestAPIAPIContext"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiPublisher.addAPI(apiRequest); + apiPublisher.deleteApi(APIName, APIVersion, providerName); + apiPublisher.addAPI(apiRequest); + APIBean apiBean = APIMgtTestUtil + .getAPIBeanFromHttpResponse(apiPublisher.getApi(APIName, providerName)); + APILifeCycleStateRequest updateRequest = + new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + //Test API properties + Assert.assertEquals(apiBean.getId().getApiName(), APIName, "API Name mismatch"); + Assert.assertEquals( + apiBean.getContext().trim().substring(apiBean.getContext().indexOf("/") + 1), + APIContext, "API context mismatch"); + Assert.assertEquals(apiBean.getId().getVersion(), APIVersion, "API version mismatch"); + Assert.assertEquals(apiBean.getId().getProviderName(), providerName, + "Provider Name mismatch"); + for (String tag : apiBean.getTags()) { + Assert.assertTrue(tags.contains(tag), "API tag data mismatched"); + } + Assert.assertEquals(apiBean.getDescription(), description, "API description mismatch"); + apiStore.addApplication("HostObjectTestAPI-Application", "Gold", "", "this-is-test"); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, + context.getContextTenant() + .getContextUser() + .getUserName()); + subscriptionRequest.setApplicationName("HostObjectTestAPI-Application"); + apiStore.subscribe(subscriptionRequest); + apiPublisher.addDocument(APIName, APIVersion, providerName, "Doc-Name", "How To", "In-line", + "url-no-need", "summary", ""); + GenerateAppKeyRequest generateAppKeyRequest = + new GenerateAppKeyRequest("HostObjectTestAPI-Application"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = + response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + + //host object tests + String fileName = "testPublisher.jag"; + String sourcePath = computeSourcePath(fileName); + String destinationPath = computeDestPath(fileName); + copySampleFile(sourcePath, destinationPath); + + fileName = "testStore.jag"; + sourcePath = computeSourcePath(fileName); + destinationPath = computeDestPath(fileName); + copySampleFile(sourcePath, destinationPath); + + Thread.sleep(20000); + String finalOutputPublisher = null; + //ClientConnectionUtil.waitForPort(9763, ""); + try { + URL jaggeryURL = new URL(getTestApplicationPublisherServerURLHttp()); + URLConnection jaggeryServerConnection = jaggeryURL.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader( + jaggeryServerConnection.getInputStream())); + + String inputLine; + while ((inputLine = in.readLine()) != null) { + finalOutputPublisher = inputLine; + } + String[] arr = finalOutputPublisher.split("=="); + System.out.println(finalOutputPublisher); + validatePublisherResponseArray(arr); + in.close(); + } catch (IOException e) { + log.error("Error while invoking test application to test publisher host object"); + } finally { + assertNotNull(finalOutputPublisher, "Result cannot be null"); + } + + String finalOutputStore = null; + Thread.sleep(20000); + //ClientConnectionUtil.waitForPort(9763, ""); + try { + URL jaggeryURL = new URL(getTestApplicationStoreServerURLHttp()); + URLConnection jaggeryServerConnection = jaggeryURL.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader( + jaggeryServerConnection.getInputStream())); + + String inputLine; + while ((inputLine = in.readLine()) != null) { + finalOutputStore = inputLine; + } + String[] arr = finalOutputStore.split("=="); + validateStoreResponseArray(arr); + System.out.println(finalOutputStore); + in.close(); + } catch (IOException e) { + log.error("Error while invoking test application to test publisher host object"); + } finally { + assertNotNull(finalOutputStore, "Result cannot be null"); + } + } + + @Test(groups = { "wso2.am" }, description = "Test application object") + public void testApplication() { + } + + @Test(groups = { "wso2.am" }, description = "Test application operations") + public void testApplicationOperations() { + } + + @Test(groups = { "wso2.am" }, description = "Test application operations") + public void testAPIProvider() { + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + apiStore.removeApplication("HostObjectTestAPI-Application"); + super.cleanup(); + } + + public static boolean validateStoreResponseArray(String[] array) { + //This order is based on the operations of jaggery file operation order + //If we edit jaggery file we need to modify this as well + Assert.assertTrue(array[1].contains("true"), + "Error while getting status of billing system from API store host object (isBillingEnabled)"); + Assert.assertTrue(array[2].contains("https"), + "Error while getting https url from API store host object (getHTTPsURL)"); + Assert.assertTrue(array[4].contains("http"), + "Error while getting http url from API store host object (getHTTPURL)"); + Assert.assertTrue(array[3].contains("services"), + "Error while getting auth service url from API store host object (getAuthServerURL)"); + Assert.assertTrue(array[5].contains("[{\"tierName\" : \"Gold\"}]"), + "Error while getting denied tiers from API store host object (getDeniedTiers)"); + Assert.assertTrue(array[6].contains("tenantdomain1.com"), + "Error while getting active tenant domains from API store host object (getActiveTenantDomains)"); + Assert.assertTrue(array[7].contains("true"), + "Error while getting status of self sign in from API store host object (isSelfSignupEnabled)"); + Assert.assertTrue(array[8].contains("fieldName"), + "Error while getting user fields from API store host object (getUserFields)"); + Assert.assertTrue(array[9].contains("HostObjectTestAPI"), + "Error while search Paginated APIs By Type from API store host object (searchPaginatedAPIsByType)"); + Assert.assertTrue(array[10].contains("HostObjectTestAPI"), + "Error while search Paginated APIs By Type with pattern * from API store host object (searchPaginatedAPIsByType)"); + Assert.assertTrue(array[11].contains("HostObjectTestAPI"), + "Error while search API by Type with pattern * from API store host object (searchAPIbyType)"); + Assert.assertTrue(array[12].contains("HostObjectTestAPI"), + "Error while search API by type from API store host object (searchAPIbyType)"); + Assert.assertTrue(array[13].contains("HostObjectTestAPI"), + "Error while getting paginated APIs with tag from API store host object (getPaginatedAPIsWithTag)"); + //14 getPublishedAPIsByProvider + //15 getAllSubscriptions + Assert.assertTrue(array[16].contains("HostObjectTestAPI"), + "Error while rating API from API store host object (rateAPI)"); + Assert.assertTrue(array[17].contains("[{\"newRating\" : \"0.0\"}]"), + "Error while removing rating from API store host object (removeAPIRating)"); + Assert.assertTrue(array[18].contains("apis"), + "Error while getting Paginated , published APIs from API store host object (getAllPaginatedPublishedAPIs)"); + Assert.assertTrue(array[19].contains("HostObjectTestAPI"), + "Error while getting APIs With Tag from API store host object (getAPIsWithTag)"); + Assert.assertTrue(array[20].contains("HostObjectTestAPI"), + "Error while getting all published APIs from API store host object (getAllPublishedAPIs)"); + //21 getComments + Assert.assertTrue(array[22].contains("true"), + "Error while checking user in the system from API store host object (isUserExists)"); + Assert.assertTrue(array[23].contains("HostObjectTestAPI"), + "Error while getting API from API store host object (getAPI)"); + Assert.assertTrue(array[24].contains("true"), + "Error while checking subscription state from API store host object (isSubscribed)"); + Assert.assertTrue(array[25].contains("application"), + "Error while getting subscriptions from API store host object (getSubscriptions)"); + //26 getSubscribedAPIs + Assert.assertTrue(array[27].contains("true"), + "Error while checking user permission from API store host object (hasUserPermissions)"); + //28 getTiers + //29 getAPIUsageforSubscriber + //30 getDeniedTiers + //31 getRecentlyAddedAPIs + //32 getTopRatedAPIs + Assert.assertTrue(array[33].contains("true"), + "Error while getting billing status from API store host object (isBillingEnabled)"); + Assert.assertTrue(array[34].contains("true"), + "Error while checking Subscribe Permission from API store host object (hasSubscribePermission)"); + Assert.assertTrue(array[35].contains("false"), + "Error while getting state of Email Username from API store host object (isEnableEmailUsername)"); + Assert.assertTrue(array[36].contains("true"), + "Error while update Application Tier from API store host object (updateApplicationTier)"); + Assert.assertTrue(array[37].contains("true"), + "Error while update Application from API store host object (updateApplication)"); + Assert.assertTrue(array[38].contains("200"), + "Error while validate WF Permission from API store host object (validateWFPermission)"); + Assert.assertTrue(array[38].contains("200"), + "Error while validate WF Permission from API store host object (validateWFPermission)"); + System.out.println("\n\n\n\n\n\n40 : "+array[40]); + Assert.assertTrue(array[40].contains("HostObjectTestAPI"), + "Error while getting all published APIs from API store host object search by context(search)"); + Assert.assertTrue(array[41].contains("HostObjectTestAPI"), + "Error while getting all published APIs from API store host object search by version(search)"); + Assert.assertTrue(!array[42].contains("HostObjectTestAPI"), + "Error while getting all published APIs from API store host object search by non-existing context (search)"); + Assert.assertTrue(!array[43].contains("HostObjectTestAPI"), + "Error while getting all published APIs from API store host object search by non-existing version(search)"); + + return true; + } + + public static boolean validatePublisherResponseArray(String[] array) { + //This order is based on the operations of jaggery file operation order + //If we edit jaggary file we need to modify this as well + /*Assert.assertNotNull(array[1], + "Error while getting external api stores from API store host object (getExternalAPIStores)");*/ + Assert.assertTrue(array[1].contains("true"), + "Error while validating roles from API store host object (validateRoles)"); + Assert.assertTrue(array[2].contains("success"), + "Error while checking url validity from API store host object (isURLValid)"); + Assert.assertTrue(array[3].contains("HostObjectTestAPI"), + "Error while getting APIs by provider from API store host object (getAPIsByProvider)"); + Assert.assertTrue(array[4].contains("HostObjectTestAPI"), + "Error while getting subscribed APIs from API store host object (getSubscribedAPIs)"); + Assert.assertTrue(array[5].contains("HostObjectTestAPI"), + "Error while getting API from API store host object (getAPI)"); + Assert.assertTrue(array[6].contains("Bronze"), + "Error while getting tier permission from API store host object (getTierPermissions)"); + Assert.assertTrue(array[7].contains("Bronze"), + "Error while getting tiers from API store host object (getTiers)"); + Assert.assertTrue(array[8].contains("HostObjectTestAPI"), + "Error while getting all APIs By Type from API store host object (getAllAPIs)"); + Assert.assertTrue(array[9].contains("HostObjectTestAPI"), + "Error while getting APIs By provider with pattern * from API store host object (getAPIsByProvider)"); + Assert.assertTrue(array[10].contains("subscribedDate"), + "Error while getting subscribers of API from API store host object (getSubscribersOfAPI)"); + Assert.assertTrue(array[11].contains("false"), + "Error while checking contexts from API store host object (isContextExist)"); + Assert.assertTrue(array[12].contains("HostObjectTestAPI"), + "Error while searching APIs from API store host object (searchAPIs)"); + Assert.assertTrue(array[13].contains("true"), + "Error while checking create permission from API store host object (hasCreatePermission)"); + Assert.assertTrue(array[14].contains("true"), + "Error while checking manage tier permission from API store host object (hasManageTierPermission)"); + Assert.assertTrue(array[15].contains("true"), + "Error while checking user permission from API store host object (hasUserPermissions)"); + Assert.assertTrue(array[16].contains("true"), + "Error while checking publisher permissions (hasPublishPermission)"); + Assert.assertTrue(array[17].contains("services"), + "Error while getting auth server url from API store host object (getAuthServerURL)"); + Assert.assertTrue(array[18].contains("[\"log_in_message\"]"), + "Error while getting in sequences from API store host object (getCustomInSequences)"); + Assert.assertTrue(array[19].contains("[\"log_out_message\"]"), + "Error while getting out sequences from API store host object (getCustomOutSequences)"); + Assert.assertTrue(array[20].contains("https"), + "Error while getting https url from API store host object (getHTTPsURL)"); + Assert.assertTrue(array[21].contains("true"), + "Error while checking gateway type from API store host object (isSynapseGateway)"); + Assert.assertTrue(array[22].contains("null"), + "Error while load Registry Of Tenant API store host object (loadRegistryOfTenant)"); + /*Assert.assertTrue(array[23].contains("true"), + "Error while update Documentation from API store host object (updateDocumentation)");*/ + /*Assert.assertTrue(array[23].contains("null"), + "Error while adding Inline Content from API store host object (addInlineContent)");*/ + Assert.assertTrue(array[23].contains("providerName"), + "Error while getting Inline Content from API store host object (getInlineContent)"); + /*Assert.assertTrue(array[24].contains("docName"), + "Error while getting All Documentation from API store host object (getAllDocumentation)");*/ + Assert.assertTrue(array[25].contains("token"), + "Error while search Access Tokens from API store host object (searchAccessTokens)"); + //Assert.assertTrue(array[29].contains("true"), "Error while checking user permission from API store host object (getSubscriberCountByAPIs)"); + //Assert.assertTrue(array[30].contains("true"), "Error while checking user permission from API store host object (getSubscriberCountByAPIVersions)"); + //Assert.assertTrue(array[31].contains("null"), "Error while getting External API Stores from API store host object (getExternalAPIStores)"); + Assert.assertTrue(array[28].contains("false"), + "Error while checking API Older Versions from API store host object (isAPIOlderVersionExist)"); + Assert.assertTrue(array[29].contains("true"), + "Error while update Subscription Status from API store host object (updateSubscriptionStatus)"); + Assert.assertTrue(array[30].contains("true"), + "Error while update Tier Permissions from API store host object (updateTierPermissions)"); + Assert.assertTrue(array[31].contains("HostObjectTestAPI"), + "Error while search API by provider (searchAPIs)"); + Assert.assertTrue(array[32].contains("HostObjectTestAPI"), + "Error while search API by context (searchAPIs)"); + Assert.assertTrue(array[33].contains("HostObjectTestAPI"), + "Error while search API by uppercase name (searchAPIs)"); + Assert.assertTrue(array[34].contains("HostObjectTestAPI"), + "Error while search API by lower case name (searchAPIs)"); + Assert.assertTrue(array[35].contains("HostObjectTestAPI"), + "Error while search API by part of the API name (searchAPIs)"); + Assert.assertTrue(array[36].contains("HostObjectTestAPI"), + "Error while search API by part of the provider (searchAPIs)"); + Assert.assertTrue(array[37].contains("HostObjectTestAPI"), + "Error while search API by part of the context (searchAPIs)"); + Assert.assertTrue(!array[38].contains("HostObjectTestAPI"), + "Error while search API by invalid search key (searchAPIs)"); + + return true; + } +} diff --git a/modules/integration/tests-integration/tests-scenario/src/test/java/org/testlink/JWTTestCase.java b/modules/integration/tests-integration/tests-scenario/src/test/java/org/testlink/JWTTestCase.java new file mode 100644 index 0000000000..b3a474d768 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/java/org/testlink/JWTTestCase.java @@ -0,0 +1,393 @@ +/* + * + * Copyright (c) 2005-2010, 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.testlink; + +import org.json.JSONException; +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.am.integration.test.utils.APIMgtTestUtil; +import org.wso2.am.integration.test.utils.bean.*; +import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; +import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; +import org.wso2.carbon.automation.engine.context.AutomationContext; +import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.carbon.automation.test.utils.common.WireMonitorServer; +import org.wso2.carbon.integration.common.admin.client.TenantManagementServiceClient; +import org.wso2.carbon.integration.common.admin.client.UserManagementClient; +import org.wso2.carbon.integration.common.utils.LoginLogoutClient; +import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; + +import java.io.File; +import java.net.URL; + +import static junit.framework.Assert.assertTrue; + +public class JWTTestCase extends APIManagerIntegrationTest{ + + private ServerConfigurationManager serverConfigurationManager; + private UserManagementClient userManagementClient; + private TenantManagementServiceClient tenantManagementServiceClient; + + private String publisherURLHttp; + private String storeURLHttp; + private WireMonitorServer server; + private int hostPort = 9988; + + private String APIName = "JWTTokenTestAPI"; + private String APIContext = "tokenTest"; + private String tags = "token, jwt"; + private String url = "http://localhost:9988"; + private String description = "This is test API create by API manager integration test"; + private String providerName = "admin"; + private String APIVersion = "1.0.0"; + private String ApplicationName = "APILifeCycleTestAPI-application"; + private String APITier = "Gold"; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(); + + if (isBuilderEnabled()) { + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + + serverConfigurationManager = new ServerConfigurationManager(context); + serverConfigurationManager.applyConfigurationWithoutRestart(new File(getAMResourceLocation() + + File.separator + + "configFiles/tokenTest/" + + "api-manager.xml")); + serverConfigurationManager.applyConfiguration(new File(getAMResourceLocation() + + File.separator + + "configFiles/tokenTest/" + + "log4j.properties")); + + } else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + + + userManagementClient = new UserManagementClient( + context.getContextUrls().getBackEndUrl(), context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + AutomationContext automationContext = new AutomationContext("AM", TestUserMode.SUPER_TENANT_ADMIN); + LoginLogoutClient loginLogoutClient = new LoginLogoutClient(automationContext); + + tenantManagementServiceClient = new TenantManagementServiceClient( + context.getContextUrls().getBackEndUrl(), loginLogoutClient.login()); + + + server = new WireMonitorServer(hostPort); + server.setReadTimeOut(300); + server.start(); + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + super.cleanup(); + serverConfigurationManager.restoreToLastConfiguration(); + } + + private void addAPI() throws Exception { + + APIPublisherRestClient apiPublisher = new APIPublisherRestClient(publisherURLHttp); + + apiPublisher.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiRequest.setWsdl("https://svn.wso2.org/repos/wso2/carbon/platform/trunk/products" + + "/bps/modules/samples/product/src/main/resources/bpel/2.0/MyRoleMexTestProcess/echo.wsdl"); + apiRequest.setVisibility("public"); + apiPublisher.addAPI(apiRequest); + + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName, + APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + + } + + @Test(groups = {"wso2.am"}, description = "Enabling JWT Token generation, admin user claims", enabled = true) + public void testEnableJWTAndClaims() throws Exception { + +// RemoteUserStoreManagerServiceClient remoteUserStoreManagerServiceClient = new RemoteUserStoreManagerServiceClient( +// context.getContextUrls().getBackEndUrl(), context.getContextTenant().getContextUser().getUserName(), +// context.getContextTenant().getContextUser().getPassword()); + + String username = context.getContextTenant().getContextUser().getUserName(); + String profile = "default"; + +// remoteUserStoreManagerServiceClient.setUserClaimValue( +// username, "http://wso2.org/claims/givenname", +// "first name", profile); +// +// remoteUserStoreManagerServiceClient.setUserClaimValue( +// username, "http://wso2.org/claims/lastname", +// "last name", profile); +// +// remoteUserStoreManagerServiceClient.setUserClaimValue( +// username, "http://wso2.org/claims/wrongclaim", +// "wrongclaim", profile); + + // restart the server since updated claims not picked unless cache expired + serverConfigurationManager.restartGracefully(); + super.init(); + + addAPI(); + + APIStoreRestClient apiStoreRestClient = new APIStoreRestClient(storeURLHttp); + apiStoreRestClient.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + apiStoreRestClient.addApplication(ApplicationName, APITier, "", "this-is-test"); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, + context.getContextTenant().getContextUser().getUserName()); + subscriptionRequest.setApplicationName(ApplicationName); + apiStoreRestClient.subscribe(subscriptionRequest); + + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest(ApplicationName); + String responseString = apiStoreRestClient.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + + String url = getApiInvocationURLHttp("tokenTest/1.0.0/"); + APIMgtTestUtil.sendGetRequest(url, accessToken); + String serverMessage = server.getCapturedMessage(); + + String decodedJWTString = APIMgtTestUtil.getDecodedJWT(serverMessage); + + System.out.println("\n\n\n\n\ndecodedJWTString = " + decodedJWTString); + + JSONObject jsonObject = new JSONObject(decodedJWTString); + + // check default claims + checkDefaultUserClaims(jsonObject); + + // check user profile info claims + String claim = jsonObject.getString("http://wso2.org/claims/givenname"); + assertTrue( "JWT claim givenname not received" + claim , claim.contains("first name")); + + claim = jsonObject.getString("http://wso2.org/claims/lastname"); + assertTrue( "JWT claim lastname not received" + claim , claim.contains("last name")); + + boolean bExceptionOccured = false; + try { + claim = jsonObject.getString("http://wso2.org/claims/wrongclaim"); + } + catch (JSONException e) { + bExceptionOccured = true; + } + + assertTrue( "JWT claim invalid claim received", bExceptionOccured); + } + + private void checkDefaultUserClaims(JSONObject jsonObject) throws JSONException { + String claim = jsonObject.getString("iss"); + assertTrue( "JWT assertion is invalid", claim.contains("wso2.org/products/am")); + + claim = jsonObject.getString("http://wso2.org/claims/subscriber"); + assertTrue( "JWT claim subscriber invalid. Received " + claim , claim.contains("admin")); + + claim = jsonObject.getString("http://wso2.org/claims/applicationname"); + assertTrue( "JWT claim applicationname invalid. Received " + claim , + claim.contains("APILifeCycleTestAPI-application")); + + claim = jsonObject.getString("http://wso2.org/claims/applicationtier"); + assertTrue( "JWT claim applicationtier invalid. Received " + claim , claim.contains("Gold")); + + claim = jsonObject.getString("http://wso2.org/claims/apicontext"); + assertTrue( "JWT claim apicontext invalid. Received " + claim , claim.contains("/tokenTest")); + + claim = jsonObject.getString("http://wso2.org/claims/version"); + assertTrue( "JWT claim version invalid. Received " + claim , claim.contains("1.0.0")); + + claim = jsonObject.getString("http://wso2.org/claims/tier"); + assertTrue( "JWT claim tier invalid. Received " + claim , claim.contains("Gold")); + + claim = jsonObject.getString("http://wso2.org/claims/keytype"); + assertTrue( "JWT claim keytype invalid. Received " + claim , claim.contains("PRODUCTION")); + + claim = jsonObject.getString("http://wso2.org/claims/usertype"); + assertTrue( "JWT claim usertype invalid. Received " + claim , claim.contains("APPLICATION")); + + claim = jsonObject.getString("http://wso2.org/claims/enduserTenantId"); + assertTrue( "JWT claim enduserTenantId invalid. Received " + claim , claim.contains("-1234")); + + claim = jsonObject.getString("http://wso2.org/claims/role"); + assertTrue( "JWT claim role invalid. Received " + claim , + claim.contains("admin,Internal/subscriber,Internal/everyone")); + } + + @Test(groups = {"wso2.am"}, description = "Enabling JWT Token generation, specific user claims", enabled = true) + public void testSpecificUserJWTClaims() throws Exception { + + //server.setFinished(false); + server.start(); + + String subscriberUser = "subscriberUser"; + String password = "password@123"; + String accessToken; + + if ((userManagementClient != null) && + !userManagementClient.userNameExists("Internal/subscriber", subscriberUser)) { + userManagementClient.addUser(subscriberUser, password, + new String[]{"Internal/subscriber"}, null); + } + +// RemoteUserStoreManagerServiceClient remoteUserStoreManagerServiceClient = new RemoteUserStoreManagerServiceClient( +// context.getContextUrls().getBackEndUrl(), context.getContextTenant().getContextUser().getUserName(), +// context.getContextTenant().getContextUser().getPassword()); +// +// String username = subscriberUser; +// String profile = "default"; +// +// remoteUserStoreManagerServiceClient.setUserClaimValue( +// username, "http://wso2.org/claims/givenname", +// "subscriberUser name", profile); +// +// remoteUserStoreManagerServiceClient.setUserClaimValue( +// username, "http://wso2.org/claims/lastname", +// "subscriberUser name", profile); + + // restart the server since updated claims not picked unless cache expired + serverConfigurationManager.restartGracefully(); + super.init(); + + APIStoreRestClient apiStoreRestClient = new APIStoreRestClient(storeURLHttp); + apiStoreRestClient.login(subscriberUser, password); + + apiStoreRestClient.addApplication(ApplicationName, APITier, "", "this-is-test"); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, + providerName); + subscriptionRequest.setApplicationName(ApplicationName); + apiStoreRestClient.subscribe(subscriptionRequest); + + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest(ApplicationName); + String responseString = apiStoreRestClient.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + + String url = getApiInvocationURLHttp("tokenTest/1.0.0/"); + + APIMgtTestUtil.sendGetRequest(url, accessToken); + String serverMessage = server.getCapturedMessage(); + + Assert.assertTrue(serverMessage.contains("X-JWT-Assertion"), "JWT assertion not in the header"); + + String decodedJWTString = APIMgtTestUtil.getDecodedJWT(serverMessage); + + System.out.println("\n\n\n\n\ndecodedJWTString = " + decodedJWTString); + + JSONObject jsonObject = new JSONObject(decodedJWTString); + + // check claims + String claim = jsonObject.getString("iss"); + assertTrue( "JWT assertion is invalid", claim.contains("wso2.org/products/am")); + + claim = jsonObject.getString("http://wso2.org/claims/subscriber"); + assertTrue( "JWT claim subscriber invalid. Received " + claim , claim.contains("subscriberUser")); + + claim = jsonObject.getString("http://wso2.org/claims/applicationname"); + assertTrue( "JWT claim applicationname invalid. Received " + claim , + claim.contains("APILifeCycleTestAPI-application1")); + + } + + + @Test(groups = {"wso2.am"}, description = "Enabling JWT Token generation, tenant user claims" , enabled = false) + public void testTenantUserJWTClaims() throws Exception { + + //server.setFinished(false); + server.start(); + + tenantManagementServiceClient.addTenant("wso2.com", "wso2@123", "admin", "Gold"); + + serverConfigurationManager.restartGracefully(); + super.init(); + + String provider = "admin-AT-wso2.com"; + String tenantUser = "admin@wso2.com"; + String password = "wso2@123"; + String accessToken; + + APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp); + + apiPublisherRestClient.login(tenantUser, password); + + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiRequest.setWsdl("https://svn.wso2.org/repos/wso2/carbon/platform/trunk/products" + + "/bps/modules/samples/product/src/main/resources/bpel/2.0/MyRoleMexTestProcess/echo.wsdl"); + apiRequest.setVisibility("public"); + + apiRequest.setProvider(provider); + apiPublisherRestClient.addAPI(apiRequest); + + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, provider, + APILifeCycleState.PUBLISHED); + apiPublisherRestClient.changeAPILifeCycleStatusTo(updateRequest); + + APIStoreRestClient apiStoreRestClient = new APIStoreRestClient(storeURLHttp); + apiStoreRestClient.login(tenantUser, password); + + apiStoreRestClient.addApplication(ApplicationName, APITier, "", "this-is-test"); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, + provider); + subscriptionRequest.setApplicationName(ApplicationName); + apiStoreRestClient.subscribe(subscriptionRequest); + + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest(ApplicationName); + String responseString = apiStoreRestClient.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + + String url = getApiInvocationURLHttp("t/wso2.com/tokenTest/1.0.0/"); + APIMgtTestUtil.sendGetRequest(url, accessToken); + String serverMessage = server.getCapturedMessage(); + + String decodedJWTString = APIMgtTestUtil.getDecodedJWT(serverMessage); + + JSONObject jsonObject = new JSONObject(decodedJWTString); + + System.out.println("\n\n\n\n\ndecodedJWTString = " + decodedJWTString); + // check claims + String claim = jsonObject.getString("iss"); + assertTrue( "JWT assertion is invalid", claim.contains("wso2.org/products/am")); + + claim = jsonObject.getString("http://wso2.org/claims/subscriber"); + assertTrue( "JWT claim subscriber invalid. Received " + claim , claim.contains("admin@wso2.com")); + + claim = jsonObject.getString("http://wso2.org/claims/apicontext"); + assertTrue( "JWT claim apicontext invalid. Received " + claim , claim.contains("/t/wso2.com/tokenTest")); + + } + +} diff --git a/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/header/ContentLengthHeaderTestCase.java b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/header/ContentLengthHeaderTestCase.java new file mode 100644 index 0000000000..e6be0949ff --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/header/ContentLengthHeaderTestCase.java @@ -0,0 +1,103 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF 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.carbon.am.tests.header; + +import org.apache.axiom.om.OMElement; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.am.integration.test.utils.WireMonitorServer; +import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment; +import org.wso2.carbon.automation.engine.annotations.SetEnvironment; +import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; +import org.wso2.carbon.integration.common.admin.client.AuthenticatorClient; +import org.wso2.carbon.integration.common.admin.client.TenantManagementServiceClient; + +import java.io.*; +import java.net.URL; + +/** + * Property Mediator FORCE_HTTP_CONTENT_LENGTH Property Test + * https://wso2.org/jira/browse/ESBJAVA-2686 + */ + +public class ContentLengthHeaderTestCase extends APIManagerIntegrationTest { + + public WireMonitorServer wireServer; + + @BeforeClass(alwaysRun = true) + public void setEnvironment() throws Exception { + super.init(); + + // Create tenant + TenantManagementServiceClient tenantManagementServiceClient = + new TenantManagementServiceClient(contextUrls.getBackEndUrl(), sessionCookie); + tenantManagementServiceClient.addTenant("abc.com", "abc123", "abc", "demo"); + + // Upload the synapse + String file = "artifacts" + File.separator + "AM" + File.separator + "synapseconfigs" + + File.separator + "property" + File.separator + + "FORCE_HTTP_CONTENT_LENGTH.xml"; + + OMElement synapseConfig = esbUtils.loadResource(file); + + AuthenticatorClient login = new AuthenticatorClient(contextUrls.getBackEndUrl()); + String session = login.login("abc@abc.com", "abc123", "localhost"); + + esbUtils.updateESBConfiguration(setEndpoints(synapseConfig), contextUrls.getBackEndUrl(), + session); + Thread.sleep(5000); + + // Start wireserver + wireServer = new WireMonitorServer(8991); + } + + @SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL }) + @org.testng.annotations.Test(groups = "wso2.am", + description = "Test for reading the Content-Length header in the request") + public void testFORCE_HTTP_CONTENT_LENGTHPropertyTest() throws Exception { + + wireServer.start(); + + FileInputStream fis = new FileInputStream( + getAMResourceLocation() + File.separator + "synapseconfigs" + File.separator + + "property" + File.separator + "placeOrder.xml" + ); + InputStreamReader isr = new InputStreamReader(fis, "UTF8"); + Reader inputReader = new BufferedReader(isr); + + URL postEndpoint = new URL("http://localhost:8280/t/abc.com/stock/1.0.0"); + + PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out"))); + + HttpRequestUtil.sendPostRequest(inputReader, postEndpoint, out); + + String response = wireServer.getCapturedMessage(); + Assert.assertTrue(response.contains("Content-Length"), + "Content-Length not found in out going message"); + + } + + @AfterClass(alwaysRun = true) + public void stop() throws Exception { + cleanup(); + } +} + diff --git a/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/rest/URLMappingRESTTestCase.java b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/rest/URLMappingRESTTestCase.java new file mode 100644 index 0000000000..8b3515f046 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/rest/URLMappingRESTTestCase.java @@ -0,0 +1,63 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.rest; + +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; +import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; + +import java.io.File; + +/** + * Related to Patch Automation https://wso2.org/jira/browse/APIMANAGER-769 + * This test class test the Rest URI template patterns like uri-template="/view/*" + */ +public class URLMappingRESTTestCase extends APIManagerIntegrationTest { + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(); + loadESBConfigurationFromClasspath("artifacts" + File.separator + "AM" + + File.separator + "synapseconfigs" + File.separator + + "rest" + + File.separator + "url-mapping-synapse.xml"); + } + + @Test(groups = { "wso2.am" }, + description = "Sending a Message Via REST to test uri template fix") + public void testRESTURITemplate() throws Exception { + // Before apply this patch uri template not recognize localhost:8280/stockquote/test/ and localhost:8280/stockquote/test + //maps to same resource. It will return correct response only if request hits localhost:8280/stockquote/test + //after fixing issue both will work. + HttpResponse response = HttpRequestUtil + .sendGetRequest(getApiInvocationURLHttp("stockquote") + "/test/", null); + // HttpResponse response = HttpRequestUtil.sendGetRequest(getApiInvocationURLHttp("stockquote") + "/test/", null); + Assert.assertEquals(response.getResponseCode(), 200, "Response code mismatch"); + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + super.cleanup(); + } +} + diff --git a/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/APIApplicationLifeCycleTestCase.java b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/APIApplicationLifeCycleTestCase.java new file mode 100644 index 0000000000..03b432bbf2 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/APIApplicationLifeCycleTestCase.java @@ -0,0 +1,861 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.sample; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.am.integration.test.utils.APIMgtTestUtil; +import org.wso2.am.integration.test.utils.bean.*; +import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; +import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; +import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; +import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; +import org.wso2.carbon.integration.common.admin.client.TenantManagementServiceClient; +import org.wso2.carbon.integration.common.admin.client.UserManagementClient; + +import java.io.File; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class APIApplicationLifeCycleTestCase extends APIManagerIntegrationTest { + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private UserManagementClient userManagementClient; + private TenantManagementServiceClient tenantManagementServiceClient; + //move to base class + private String publisherURLHttp; + private String storeURLHttp; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(); + + if (isBuilderEnabled()) { + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + + } else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + apiPublisher = new APIPublisherRestClient(publisherURLHttp); + apiStore = new APIStoreRestClient(storeURLHttp); + + userManagementClient = new UserManagementClient( + context.getContextUrls().getBackEndUrl(), getSessionCookie()); + + tenantManagementServiceClient = new TenantManagementServiceClient( + context.getContextUrls().getBackEndUrl(), getSessionCookie()); + } + + @Test(groups = {"wso2.am"}, description = "API Life cycle test case", enabled = false) + public void testAPIApplicationLifeCycleITestCase() throws Exception { + + String apiData = ""; + String APIName = "APILifeCycleTestAPI"; + String APIContext = "testAPI"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + //add all option methods + apiPublisher.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiRequest.setWsdl("https://svn.wso2.org/repos/wso2/carbon/platform/trunk/products" + + "/bps/modules/samples/product/src/main/resources/bpel/2.0/MyRoleMexTestProcess/echo.wsdl"); + apiRequest.setVisibility("restricted"); + apiRequest.setRoles("admin"); + apiPublisher.addAPI(apiRequest); + apiPublisher.deleteApi(APIName, APIVersion, providerName); + //add assertion + apiPublisher.addAPI(apiRequest); + APIBean apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisher.getApi( + APIName, providerName)); + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName, + APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + //Test API properties + Assert.assertEquals(apiBean.getId().getApiName(), APIName, "API Name mismatch"); + Assert.assertEquals(apiBean.getContext().trim().substring(apiBean.getContext().indexOf("/") + 1), APIContext, "API context mismatch"); + Assert.assertEquals(apiBean.getId().getVersion(), APIVersion, "API version mismatch"); + Assert.assertEquals(apiBean.getId().getProviderName(), providerName, "Provider Name mismatch"); + for (String tag : apiBean.getTags()) { + Assert.assertTrue(tags.contains(tag), "API tag data mismatched"); + } + Assert.assertEquals(apiBean.getDescription(), description, "API description mismatch"); + apiStore.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + apiStore.addApplication("APILifeCycleTestAPI-application", "Gold", "", "this-is-test"); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, + context.getContextTenant().getContextUser().getUserName()); + subscriptionRequest.setApplicationName("APILifeCycleTestAPI-application"); + apiStore.subscribe(subscriptionRequest); + + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest("APILifeCycleTestAPI-application"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + //Here add API tags and check same have in response. + //Here check same tags are there + //Add some comment to API + //check comment is there + //Add rating + //check rating + Thread.sleep(60000); + // for (int i = 0; i < 19; i++) { + + HttpResponse youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("testAPI/1.0.0/most_popular"), requestHeaders); + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched"); + Assert.assertTrue(youTubeResponse.getData().contains(""), "Response data mismatched"); + + // } + //Do get,post,put,delete all here + //HttpResponse youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("commentRating/1.0.0/most_popular"), requestHeaders); + //Assert.assertEquals(youTubeResponse.getResponseCode(), 503, "Response code mismatched"); + //Thread.sleep(60000); + HttpResponse youTubeResponse1 = HttpRequestUtil.doGet(getApiInvocationURLHttp("testAPI/1.0.0/most_popular"), null); + Assert.assertEquals(youTubeResponse1.getResponseCode(), 401, "Response code mismatched"); + requestHeaders.clear(); + requestHeaders.put("Authorization", "Bearer " + "-wrong-tokent-text-"); + HttpResponse youTubeResponseError = HttpRequestUtil.doGet(getApiInvocationURLHttp("testAPI/1.0.0/most_popular"), null); + Assert.assertEquals(youTubeResponseError.getResponseCode(), 401, "Response code mismatched"); + + apiStore.getAllPublishedAPIs(); + apiStore.getAllApplications(); + apiStore.getPublishedAPIsByApplication("APILifeCycleTestAPI-application"); + apiStore.isRatingActivated(); + apiStore.addRatingToAPI(APIName, APIVersion, providerName, "4"); + apiStore.addRatingToAPI(APIName, APIVersion, providerName, "2"); + apiStore.addRatingToAPI(APIName, APIVersion, providerName, "1"); + apiStore.removeRatingFromAPI(APIName, APIVersion, providerName); + apiStore.getAllDocumentationOfApi(APIName, APIVersion, providerName); + //apiStore.getAllPaginatedPublishedAPIs("carbon.super","0","10"); + //Negative cases + apiStore.getPublishedAPIsByApplication("APILifeCycleTestAPI-application-wrong"); + apiStore.isRatingActivated(); + apiStore.addRatingToAPI("NoAPI", APIVersion, providerName, "4"); + apiStore.removeRatingFromAPI("NoAPI", APIVersion, providerName); + apiStore.getAllDocumentationOfApi("NoAPI", APIVersion, providerName); + apiRequest.setTags("updated"); + apiRequest.setProvider("admin"); + Thread.sleep(1000); + apiPublisher.updateAPI(apiRequest); + //TODO need to reformat this code after we finalize new APIs + apiPublisher.addDocument(APIName, APIVersion, providerName, "Doc Name", "How To", "In-line", + "url-no-need", "summary", ""); + apiPublisher.addDocument(APIName, APIVersion, providerName, "Doc Name", "How To", "URL", + "http://www.businesstoday.lk/article.php?article=3549", "summary", ""); + apiPublisher.addDocument(APIName, APIVersion, providerName, "Doc Name", "How To", " File", + "url-no-need", "summary", + getAMResourceLocation() + File.separator + "configFiles/tokenTest/" + "api-manager.xml"); + apiPublisher.removeDocumentation(APIName, APIVersion, providerName, "Doc Name", "How To"); + //create application + apiStore.addApplication("test-application", "Gold", "", "this-is-test"); + apiStore.addApplication("test-application2", "Gold", "", "this-is-test"); + apiStore.getAllApplications(); + + //Test case to create new application and make subscriptions to that application + SubscriptionRequest subscriptionRequest1 = new SubscriptionRequest(APIName, + context.getContextTenant().getContextUser().getUserName()); + subscriptionRequest1.setApplicationName("test-application"); + apiStore.subscribe(subscriptionRequest1); + GenerateAppKeyRequest generateAppKeyRequest1 = new GenerateAppKeyRequest("test-application"); + String responseString1 = apiStore.generateApplicationKey(generateAppKeyRequest1).getData(); + JSONObject response1 = new JSONObject(responseString1); + String accessToken1 = response1.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders1 = new HashMap(); + requestHeaders1.put("Authorization", "Bearer " + accessToken1); + HttpResponse youTubeResponseTestApp = HttpRequestUtil.doGet(getApiInvocationURLHttp("testAPI/1.0.0/most_popular"), requestHeaders1); + for (int i = 0; i < 40; i++) { + youTubeResponseTestApp = HttpRequestUtil.doGet(getApiInvocationURLHttp("testAPI/1.0.0/most_popular"), requestHeaders1); + } + Assert.assertEquals(youTubeResponseTestApp.getResponseCode(), 503, "Response code mismatched"); + + //Add comment + apiStore.isCommentActivated(); + apiStore.addComment(APIName, APIVersion, providerName, "this-is-comment"); + apiStore.getRecentlyAddedAPIs("carbon.super", "5"); + + apiStore.updateApplication("test-application", "test-updated-application", "test-url", "this-is-updated", "bronze"); + apiStore.getAllApplications(); + apiData = apiStore.removeApplication("test-updated-application").getData(); + Assert.assertTrue(!apiData.contains("false"), "Error while removing applications"); + + apiStore.getAllApplications(); + apiData = apiStore.getAllSubscriptions().getData(); + Assert.assertTrue(apiData.contains("test-application"), "Error while getting all the subscriptions"); + + apiStore.getAllTags(); + + //Update role permissions + HttpResponse updateTierPermissionResponse = apiPublisher.updatePermissions("Gold", "Deny", "admin"); + JSONObject jsonObject = new JSONObject(updateTierPermissionResponse.getData()); + Assert.assertTrue(!(Boolean) jsonObject.get("error"), "Error while updating tier permission"); + + apiData = apiStore.removeAPISubscription(APIName, APIVersion, providerName, "1").getData(); + Assert.assertTrue(apiData.contains("{\"error\" : false}"), "Error while unsubscribe from API"); + + apiPublisher.logout(); + apiStore.removeApplication("APILifeCycleTestAPI-application"); + + } + + @Test(groups = {"wso2.am"}, description = "API Life cycle test invalid scenario", enabled = false) + public void testInvalidLoginAsPublisherTestCase() { + + APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp); + //Try invalid login to publisher + try { + apiPublisherRestClient.login(context.getContextTenant().getContextUser().getUserName() + + "invalid", + context.getContextTenant().getContextUser().getPassword()); + } catch (Exception e) { + Assert.assertTrue(e.getMessage().toString().contains( + "Please recheck the username and password and try again"), + "Invalid user can login to the API publisher"); + } + + } + + @Test(groups = {"wso2.am"}, description = "API Life cycle test subscriber login", enabled = false) + public void testInvalidLoginAsSubscriberTestCase() + throws Exception { + + //Try login to publisher with subscriber user + APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp); + boolean loginFailed = false; + String error = ""; + + if ((userManagementClient != null) && + !userManagementClient.userNameExists("Internal/subscriber", "subscriberUser")) { + userManagementClient.addUser("subscriberUser", "password@123", + new String[]{"Internal/subscriber"}, null); + } + + try { + apiPublisherRestClient.login("subscriberUser", + "password@123"); + } catch (Exception e) { + loginFailed = true; + error = e.getMessage().toString(); + } + + Assert.assertTrue(loginFailed && error.contains("Login failed.Insufficient privileges"), + "Invalid subscriber can login to the API publisher"); + } + + + @Test(groups = {"wso2.am"}, description = "API Life cycle test subscriber login", enabled = false) + public void testInvalidLoginAsTenantSubscriberTestCase() + throws Exception { + + //Try login to publisher with tenant subscriber user + + APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp); + boolean loginFailed = false; + String error = ""; + + tenantManagementServiceClient.addTenant("wso2.com", "wso2@123", "wso2", "Gold"); + + if ((userManagementClient != null) && + !userManagementClient.userNameExists("Internal/subscriber", "subscriberUser@wso2.com")) { + userManagementClient.addUser("subscriberUser@wso2.com", "password@123", + new String[]{"Internal/subscriber"}, null); + } + + try { + apiPublisherRestClient.login("subscriberUser@wso2.com", + "password@123"); + } catch (Exception e) { + loginFailed = true; + error = e.getMessage().toString(); + } + + Assert.assertTrue(error.contains("Operation not successful: " + + "Login failed.Please recheck the username and password and try again"), + "Invalid tenant subscriber can login to the API publisher"); + + } + + @Test(groups = {"wso2.am"}, description = "API visibility", enabled = false) + public void testAPIVisibilityTestCase() + throws Exception { + + userManagementClient.addUser("subscriberUser1", "password@123", + new String[]{"Internal/everyone"}, null); + + APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp); + apiPublisherRestClient.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + addPublicAPI(apiPublisherRestClient); + addVisibleToDomainOnlyAPI(apiPublisherRestClient); + addVisibleToRolesAPI(apiPublisherRestClient); + //apiPublisherRestClient.logout(); + boolean bPublishedAPI = false; + String publishedAPIs; + /* publishedAPIs = apiStore.getAllPublishedAPIsAsAnonUser().getData(); + + if (publishedAPIs.contains("APILifeCycleTestAPIPublic") && + !publishedAPIs.contains("APILifeCycleTestAPIDomainOnly") && + !publishedAPIs.contains("APILifeCycleTestAPIRoles")) { + bPublishedAPI = true; + } + + Assert.assertTrue(bPublishedAPI, "Anonymous user can view other API's");*/ + + APIStoreRestClient apiStore1 = new APIStoreRestClient(storeURLHttp); + apiStore1.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + publishedAPIs = apiStore1.getAllPublishedAPIs().getData(); + bPublishedAPI = false; + + if (publishedAPIs.contains("APILifeCycleTestAPIPublic") && + publishedAPIs.contains("APILifeCycleTestAPIDomainOnly") && + publishedAPIs.contains("APILifeCycleTestAPIRoles")) { + bPublishedAPI = true; + } + + Assert.assertTrue(bPublishedAPI, "Admin user can not view all API's"); + + if ((userManagementClient != null) && + !userManagementClient.userNameExists("Internal/subscriber", "subscriberUser")) { + userManagementClient.addUser("subscriberUser", "password@123", + new String[]{"Internal/subscriber"}, null); + } + + APIStoreRestClient apiStore2 = new APIStoreRestClient(storeURLHttp); + apiStore2.login("subscriberUser","password@123"); + publishedAPIs = apiStore2.getAllPublishedAPIs().getData(); + bPublishedAPI = false; + + if (publishedAPIs.contains("APILifeCycleTestAPIPublic") && + publishedAPIs.contains("APILifeCycleTestAPIDomainOnly") && + !publishedAPIs.contains("APILifeCycleTestAPIRoles")) { + bPublishedAPI = true; + } + + } + + @Test(groups = {"wso2.am"}, description = "API visibility", enabled = false) + public void copyAPILifeCycleTestCase() throws Exception { + + String APIName = "APILifeCycleTestAPI"; + String APIContext = "testAPI"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersionOld = "1.0.0"; + String APIVersionNew = "2.0.0"; + String defaultVersion = "default_version"; + + //add all option methods + APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp); + apiPublisherRestClient.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersionOld); + apiRequest.setWsdl("https://svn.wso2.org/repos/wso2/carbon/platform/trunk/products" + + "/bps/modules/samples/product/src/main/resources/bpel/2.0/MyRoleMexTestProcess/echo.wsdl"); + apiRequest.setVisibility("restricted"); + apiRequest.setRoles("admin"); + apiPublisherRestClient.addAPI(apiRequest); + + APIBean apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisherRestClient.getApi( + APIName, providerName)); + APILifeCycleStateRequest updateRequest1 = new APILifeCycleStateRequest(APIName, providerName, + APILifeCycleState.PUBLISHED); + apiPublisherRestClient.changeAPILifeCycleStatusTo(updateRequest1); + + apiPublisherRestClient.copyAPI(providerName, APIName, APIVersionOld, APIVersionNew, ""); + //add assertion + apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisherRestClient.getApi(APIName, + providerName)); + APILifeCycleStateRequest updateRequest2 = new APILifeCycleStateRequest(APIName, + providerName, APILifeCycleState.PUBLISHED); + updateRequest2.setVersion(APIVersionNew); + apiPublisherRestClient.changeAPILifeCycleStatusTo(updateRequest2); + + APIStoreRestClient apiStore = new APIStoreRestClient(storeURLHttp); + apiStore.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + String apiData = apiStore.getAllPublishedAPIs().getData(); + + Assert.assertTrue(!apiData.contains(APIVersionOld), + "Old version available in the store"); + + Assert.assertTrue(apiData.contains(APIVersionNew), + "New version not available in the store"); + + //subscribe to the old API version + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, + context.getContextTenant().getContextUser().getUserName()); + apiData = apiStore.subscribe(subscriptionRequest).getData(); + + Assert.assertTrue(apiData.contains("{\"error\" : false, \"status\" : \"UNBLOCKED\"}"), + "Can subscribe to the old API version"); + + //subscribe to the new API version + subscriptionRequest.setVersion(APIVersionNew); + apiData = apiStore.subscribe(subscriptionRequest).getData(); + + Assert.assertTrue(apiData.contains("{\"error\" : false, \"status\" : \"UNBLOCKED\"}"), + "Can not subscribe to the old API version"); + + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest("DefaultApplication"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + //Here add API tags and check same have in response. + //Here check same tags are there + //Add some comment to API + //check comment is there + //Add rating + //check rating + Thread.sleep(60000); + + HttpResponse youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("testAPI/1.0.0/most_popular"), requestHeaders); + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched"); + Assert.assertTrue(youTubeResponse.getData().contains(""), "Response data mismatched"); + + youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("testAPI/2.0.0/most_popular"), requestHeaders); + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched"); + Assert.assertTrue(youTubeResponse.getData().contains(""), "Response data mismatched"); + + } + + @Test(groups = {"wso2.am"}, description = "API visibility", enabled = false) + public void otherAPILifeCycleStatesTestCase() throws Exception { + + String APIName = "APILifeCycleTestAPI"; + String APIContext = "testAPI"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersionOld = "1.0.0"; + String APIVersionNew = "2.0.0"; + String defaultVersion = "default_version"; + + //add all option methods + APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp); + apiPublisherRestClient.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersionOld); + apiRequest.setWsdl("https://svn.wso2.org/repos/wso2/carbon/platform/trunk/products" + + "/bps/modules/samples/product/src/main/resources/bpel/2.0/MyRoleMexTestProcess/echo.wsdl"); + apiRequest.setVisibility("restricted"); + apiRequest.setRoles("admin"); + apiPublisherRestClient.addAPI(apiRequest); + + APIBean apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisherRestClient.getApi( + APIName, providerName)); + APILifeCycleStateRequest updateRequest1 = new APILifeCycleStateRequest(APIName, providerName, + APILifeCycleState.PUBLISHED); + apiPublisherRestClient.changeAPILifeCycleStatusTo(updateRequest1); + + APIStoreRestClient apiStore = new APIStoreRestClient(storeURLHttp); + apiStore.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + String apiData = apiStore.getAllPublishedAPIs().getData(); + + Assert.assertTrue(apiData.contains(APIName), + "Added API not available in store"); + + APILifeCycleStateRequest updateRequest2 = new APILifeCycleStateRequest(APIName, providerName, + APILifeCycleState.RETIRED); + apiPublisherRestClient.changeAPILifeCycleStatusTo(updateRequest2); + + apiData = apiStore.getAllPublishedAPIs().getData(); + + Assert.assertTrue(!apiData.contains(APIName), + "Retired API available in store"); + + + APILifeCycleStateRequest updateRequest3 = new APILifeCycleStateRequest(APIName, providerName, + APILifeCycleState.BLOCKED); + apiPublisherRestClient.changeAPILifeCycleStatusTo(updateRequest3); + + apiData = apiStore.getAllPublishedAPIs().getData(); + + Assert.assertTrue(!apiData.contains(APIName), + "Blocked API available in store"); + + } + + @Test(groups = {"wso2.am"}, description = "API visibility", enabled = false) + public void copyAndDepricateAPILifeCycleTestCase() throws Exception { + + String APIName = "APILifeCycleTestAPI"; + String APIContext = "testAPI"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersionOld = "1.0.0"; + String APIVersionNew = "2.0.0"; + String defaultVersion = "default_version"; + + //add all option methods + APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp); + apiPublisherRestClient.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersionOld); + apiRequest.setWsdl("https://svn.wso2.org/repos/wso2/carbon/platform/trunk/products" + + "/bps/modules/samples/product/src/main/resources/bpel/2.0/MyRoleMexTestProcess/echo.wsdl"); + apiRequest.setVisibility("restricted"); + apiRequest.setRoles("admin"); + apiPublisherRestClient.addAPI(apiRequest); + + //publish initial version + APIBean apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisherRestClient.getApi( + APIName, providerName)); + APILifeCycleStateRequest updateRequest1 = new APILifeCycleStateRequest(APIName, providerName, + APILifeCycleState.PUBLISHED); + apiPublisherRestClient.changeAPILifeCycleStatusTo(updateRequest1); + + //publish new version + apiPublisherRestClient.copyAPI(providerName, APIName, APIVersionOld, APIVersionNew, ""); + //add assertion + apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisherRestClient.getApi(APIName, + providerName)); + APILifeCycleStateRequest updateRequest2 = new APILifeCycleStateRequest(APIName, + providerName, APILifeCycleState.PUBLISHED); + updateRequest2.setVersion(APIVersionNew); + apiPublisherRestClient.changeAPILifeCycleStatusTo(updateRequest2); + + //deprecate old version + apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisherRestClient.getApi(APIName, + providerName)); + APILifeCycleStateRequest updateRequest3 = new APILifeCycleStateRequest(APIName, + providerName, APILifeCycleState.DEPRECATED); + updateRequest3.setVersion(APIVersionOld); + apiPublisherRestClient.changeAPILifeCycleStatusTo(updateRequest3); + + APIStoreRestClient apiStore = new APIStoreRestClient(storeURLHttp); + apiStore.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + String apiData = apiStore.getAllPublishedAPIs().getData(); + + Assert.assertTrue(!apiData.contains(APIVersionOld), + "Old version available in the store"); + + Assert.assertTrue(apiData.contains(APIVersionNew), + "New version not available in the store"); + + //subscribe to the old API version + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, + context.getContextTenant().getContextUser().getUserName()); + apiData = apiStore.subscribe(subscriptionRequest).getData(); + + Assert.assertTrue(apiData.contains("{\"error\" : false, \"status\" : \"UNBLOCKED\"}"), + "Can subscribe to the old API version"); + + //subscribe to the new API version + subscriptionRequest.setVersion(APIVersionNew); + apiData = apiStore.subscribe(subscriptionRequest).getData(); + + Assert.assertTrue(apiData.contains("{\"error\" : false, \"status\" : \"UNBLOCKED\"}"), + "Can not subscribe to the old API version"); + + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest("DefaultApplication"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + //Here add API tags and check same have in response. + //Here check same tags are there + //Add some comment to API + //check comment is there + //Add rating + //check rating + Thread.sleep(60000); + + HttpResponse youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("testAPI/1.0.0/most_popular"), requestHeaders); + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched"); + Assert.assertTrue(youTubeResponse.getData().contains(""), "Response data mismatched"); + + youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("testAPI/2.0.0/most_popular"), requestHeaders); + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched"); + Assert.assertTrue(youTubeResponse.getData().contains(""), "Response data mismatched"); + + } + + public void addPublicAPI(APIPublisherRestClient apiPublisherRestClient) throws Exception { + + String APIName = "APILifeCycleTestAPIPublic"; + String APIContext = "testAPIPublic"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + //add all option methods + + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiRequest.setWsdl("https://svn.wso2.org/repos/wso2/carbon/platform/trunk/products" + + "/bps/modules/samples/product/src/main/resources/bpel/2.0/MyRoleMexTestProcess/echo.wsdl"); + apiRequest.setVisibility("public"); + apiPublisherRestClient.addAPI(apiRequest); + //add assertion + APIBean apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisherRestClient.getApi(APIName, providerName)); + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); + apiPublisherRestClient.changeAPILifeCycleStatusTo(updateRequest); + + } + + public void addVisibleToDomainOnlyAPI(APIPublisherRestClient apiPublisherRestClient) throws Exception { + + String APIName = "APILifeCycleTestAPIDomainOnly"; + String APIContext = "testAPIDomainOnly"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + //add all option methods + //apiPublisher.login(userInfo.getUserName(), userInfo.getPassword()); + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiRequest.setWsdl("https://svn.wso2.org/repos/wso2/carbon/platform/trunk/products/" + + "bps/modules/samples/product/src/main/resources/bpel/2.0/MyRoleMex" + + "TestProcess/echo.wsdl"); + apiRequest.setVisibility("private"); + apiPublisherRestClient.addAPI(apiRequest); + //add assertion; + APIBean apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisherRestClient.getApi( + APIName, providerName)); + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName, + APILifeCycleState.PUBLISHED); + apiPublisherRestClient.changeAPILifeCycleStatusTo(updateRequest); + } + + public void addVisibleToRolesAPI(APIPublisherRestClient apiPublisherRestClient) throws Exception { + + String APIName = "APILifeCycleTestAPIRoles"; + String APIContext = "testAPIRoles"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + //add all option methods + //apiPublisher.login(userInfo.getUserName(), userInfo.getPassword()); + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiRequest.setWsdl("https://svn.wso2.org/repos/wso2/carbon/platform/trunk" + + "/products/bps/modules/samples/product/src/main/resources/bpel" + + "/2.0/MyRoleMexTestProcess/echo.wsdl"); + apiRequest.setVisibility("restricted"); + apiRequest.setRoles("admin"); + apiPublisherRestClient.addAPI(apiRequest); + //add assertion + APIBean apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisherRestClient.getApi( + APIName, providerName)); + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest( + APIName, providerName, APILifeCycleState.PUBLISHED); + apiPublisherRestClient.changeAPILifeCycleStatusTo(updateRequest); + } + + + @Test(groups = {"wso2.am"}, description = "API Life cycle application related tests in store", enabled = false) + public void testApplicationsInStoreTestCase() + throws Exception { + + //Try login to publisher with tenant subscriber user + + APIStoreRestClient apiStoreRestClient1 = new APIStoreRestClient(storeURLHttp); + + apiStoreRestClient1.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + tenantManagementServiceClient.addTenant("wso2.com", "wso2@123", "wso2", "Gold"); + + if ((userManagementClient != null) && + !userManagementClient.userNameExists("Internal/subscriber", "subscriberUser@wso2.com")) { + userManagementClient.addUser("subscriberUser@wso2.com", "password@123", + new String[]{"Internal/subscriber"}, null); + } + + apiStoreRestClient1.addApplication("carbonSuperApp", "Gold", "", "super tenant app"); + String apiData = apiStoreRestClient1.addApplication("carbonSuperApp","Gold","", + "super tenant app").getData(); + Assert.assertTrue(apiData.contains("A duplicate application already exists"), + "application with duplicate name addition allowed"); + + APIStoreRestClient apiStoreRestClient2 = new APIStoreRestClient(storeURLHttp); + + apiStoreRestClient2.login("admin@wso2.com", + "wso2@123"); + apiData = apiStoreRestClient2.addApplication( + "carbonSuperApp", "Gold", "", "super tenant app").getData(); + Assert.assertTrue(apiData.contains("{\"error\" : false}"), + "application with same name addition not allowed in other tenant"); + + apiStoreRestClient1.addApplication("carbonSuperApp", "Gold", "", "super tenant app"); + apiData = apiStoreRestClient1.removeApplication("carbonSuperApp").getData(); + Assert.assertTrue(apiData.contains("{\"error\" : false}"), + "application deletion failed"); + + + + } + + @Test(groups = {"wso2.am"}, description = "API Life cycle login to store") + public void testLoginToStoreTestCase() + throws Exception { + + //Try login to publisher with tenant subscriber user + String APICreatorRole = "APICreatorRole"; + String APIPublisherRole = "APIPublisherRole"; + String APIPublisherUser = "APIPublisherUser"; + String APICreatorUser = "APICreatorUser"; + String password = "password@123"; + boolean loginFailed = false; + String errorString = ""; + + APIStoreRestClient apiStoreRestClient = new APIStoreRestClient(storeURLHttp); + + String[] createPermissions = { + "/permission/admin/login", + "/permission/admin/manage/api/create" }; + + if (!userManagementClient.roleNameExists(APICreatorRole)) { + userManagementClient.addRole(APICreatorRole, null, createPermissions); + } + + if ((userManagementClient != null) && + !userManagementClient.userNameExists(APICreatorRole, APICreatorUser)) { + userManagementClient.addUser(APICreatorUser, password, + new String[]{APICreatorRole}, null); + } + + String[] publishPermissions = { + "/permission/admin/login", + "/permission/admin/manage/api/publish" }; + + if (!userManagementClient.roleNameExists(APIPublisherRole)) { + userManagementClient.addRole(APIPublisherRole, null, publishPermissions); + } + + if ((userManagementClient != null) && + !userManagementClient.userNameExists(APIPublisherRole, APIPublisherUser)) { + userManagementClient.addUser(APIPublisherUser, password, + new String[]{APIPublisherRole}, null); + } + + try { + apiStoreRestClient.login("invaliduser", "invaliduser@123"); + } catch (Exception e) { + loginFailed = true; + errorString = e.getMessage().toString(); + } + + Assert.assertTrue(loginFailed && errorString.contains("Operation not successful: " + + "Login failed.Please recheck the username and password and try again"), + "Invalid user can login to the API store"); + loginFailed = false; + + try { + apiStoreRestClient.login(APICreatorUser, password); + } catch (Exception e) { + loginFailed = true; + errorString = e.getMessage().toString(); + } + + Assert.assertTrue(loginFailed && errorString.contains("Login failed.Insufficient Privileges"), + "API creator can login to the API store"); + loginFailed = false; + + try { + apiStoreRestClient.login(APIPublisherUser, password); + } catch (Exception e) { + loginFailed = true; + errorString = e.getMessage().toString(); + } + + Assert.assertTrue(loginFailed && errorString.contains("Login failed.Insufficient Privileges"), + "API publisher can login to the API store"); + + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + + APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp); + apiPublisherRestClient.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + /*apiPublisherRestClient.deleteApi("APILifeCycleTestAPIPublic", "1.0.0", "admin"); + apiPublisherRestClient.deleteApi("APILifeCycleTestAPIDomainOnly", "1.0.0", "admin"); + apiPublisherRestClient.deleteApi("APILifeCycleTestAPIRoles", "1.0.0", "admin");*/ + + Thread.sleep(5000); + super.cleanup(); + } +} diff --git a/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/APIUsageBAMIntegrationTestCase.java b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/APIUsageBAMIntegrationTestCase.java new file mode 100644 index 0000000000..772214f26c --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/APIUsageBAMIntegrationTestCase.java @@ -0,0 +1,331 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.sample; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.am.integration.test.utils.APIMgtTestUtil; +import org.wso2.am.integration.test.utils.bean.*; +import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; +import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; +import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; +import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; +import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; +import org.wso2.carbon.utils.FileManipulator; +import org.wso2.carbon.utils.ServerConstants; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.util.HashMap; +import java.util.Map; + +import static org.testng.Assert.assertNotNull; + +/* +This test case is not run with default API manager integration tests. To run this test we assume that BAM server +is running with port offset 1. If you have changed anything please update api-manager.xml file and master data source +properties file available in /resources/artifacts/AM/configFiles/usagemonitortest directory.For this test case we will +run API manager as a part of integration test and BAM server should up and run by user. In this test we will create API +and do basic API management related operations and usage data will push to BAM. User should deploy usage tool box inside +BAM server(ideally user should setup BAM as we described in statistics help document). And all API manager related +configurations listed on statistics help doc should apply to files available in above mentioned directory +(/resources/artifacts/AM/configFiles/usagemonitortest) + */ +public class APIUsageBAMIntegrationTestCase extends APIManagerIntegrationTest { + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private ServerConfigurationManager serverConfigurationManager; + private String publisherURLHttp; + private String storeURLHttp; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(); + + if (isBuilderEnabled()) { + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + //If test run in external distributed deployment you need to copy following resources accordingly. + //configFiles/usagemonitortest/api-manager.xml + //configFiles/usagemonitortest/master-datasources.xml + //configFiles/tokenTest/log4j.properties + //Also need to copy the content of /resources/artifacts/AM/jaggery to servers following folder folder + ///repository/deployment/server/jaggeryapps/testapp + serverConfigurationManager = new ServerConfigurationManager(context); + serverConfigurationManager.applyConfiguration(new File(getAMResourceLocation() + + File.separator + + "configFiles/usagemonitortest/" + + "api-manager.xml")); + String dataSourceDestinationPath = + computeDestinationPathForDataSource("master-datasources.xml"); + String dataSourceSourcePath = computeDataSourceResourcePath("master-datasources.xml"); + copyDataSourceFile(dataSourceSourcePath, dataSourceDestinationPath); + serverConfigurationManager.applyConfiguration(new File(getAMResourceLocation() + + File.separator + + "configFiles/tokenTest/" + + "log4j.properties")); + super.init(); + + } else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + apiPublisher = new APIPublisherRestClient(publisherURLHttp); + apiStore = new APIStoreRestClient(storeURLHttp); + } + + private void copySampleFile(String sourcePath, String destinationPath) { + File sourceFile = new File(sourcePath); + File destinationFile = new File(destinationPath); + try { + FileManipulator.copyFile(sourceFile, destinationFile); + } catch (IOException e) { + log.error("Error while copying the sample into Jaggery server", e); + } + } + + private void copyDataSourceFile(String sourcePath, String destPath) { + File sourceFile = new File(sourcePath); + File destFile = new File(destPath); + try { + FileManipulator.copyFile(sourceFile, destFile); + } catch (IOException e) { + log.error("Error while copying the sample into Jaggery server", e); + } + } + + private String computeDestinationPath(String fileName) { + String serverRoot = System.getProperty(ServerConstants.CARBON_HOME); + String deploymentPath = serverRoot + "/repository/deployment/server/jaggeryapps/testapp"; + File depFile = new File(deploymentPath); + if (!depFile.exists() && !depFile.mkdir()) { + log.error("Error while creating the deployment folder : " + + deploymentPath); + } + return deploymentPath + File.separator + fileName; + } + + private String computeDestinationPathForDataSource(String fileName) { + String serverRoot = System.getProperty(ServerConstants.CARBON_HOME); + String deploymentPath = serverRoot + "/repository/conf/datasources"; + File depFile = new File(deploymentPath); + if (!depFile.exists() && !depFile.mkdir()) { + log.error("Error while creating the deployment folder : " + + deploymentPath); + } + return deploymentPath + File.separator + fileName; + } + + private String computeJaggeryResourcePath(String fileName) { + + String sourcePath = getAMResourceLocation() + + File.separator + "jaggery/" + fileName; + return sourcePath; + } + + private String computeDataSourceResourcePath(String fileName) { + + String sourcePath = getAMResourceLocation() + + File.separator + "configFiles/usagemonitortest/" + fileName; + return sourcePath; + } + + @Test(groups = { "wso2.am" }, description = "API Life cycle test case") + public void usageDataTestCase() throws Exception { + apiPublisher.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + apiStore.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + String APIName = "UsageTestAPI"; + String APIContext = "UsageTestAPI"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager usage integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiPublisher.addAPI(apiRequest); + apiPublisher.deleteApi(APIName, APIVersion, providerName); + apiPublisher.addAPI(apiRequest); + APILifeCycleStateRequest updateRequest = + new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + + apiStore.addApplication("UsageTestAPI-Application", "Gold", "", "this-is-test"); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, + context.getContextTenant() + .getContextUser() + .getUserName()); + subscriptionRequest.setApplicationName("UsageTestAPI-Application"); + apiStore.subscribe(subscriptionRequest); + apiPublisher.addDocument(APIName, APIVersion, providerName, "Doc-Name", "How To", "In-line", + "url-no-need", "summary", ""); + GenerateAppKeyRequest generateAppKeyRequest = + new GenerateAppKeyRequest("UsageTestAPI-Application"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = + response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + HttpResponse youTubeResponse = HttpRequestUtil + .doGet(getApiInvocationURLHttp("UsageTestAPI/1.0.0/most_popular"), requestHeaders); + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched"); + //Here will do 20 successful invocations + for (int i = 0; i < 20; i++) { + youTubeResponse = HttpRequestUtil + .doGet(getApiInvocationURLHttp("UsageTestAPI/1.0.0/most_popular"), + requestHeaders); + } + Thread.sleep(60000); + + + //Here will do 20 faulty invocations + String APINameFaultyAPI = "UsageTestAPIFaultyAPI"; + String APIContextFaultyAPI = "UsageTestAPIFaultyAPI"; + String tagsFaultyAPI = "youtube, video, media"; + //this url should not exists and then it will return with API fault invocation + String urlFaultyAPI = "http://thisiswrong.com/feeds/api/standardfeeds"; + String descriptionFaultyAPI = + "This is test API create by API manager usage integration test"; + String APIVersionFaultyAPI = "1.0.0"; + APIRequest apiRequestFaultyAPI = + new APIRequest(APINameFaultyAPI, APIContextFaultyAPI, new URL(urlFaultyAPI)); + apiRequestFaultyAPI.setTags(tagsFaultyAPI); + apiRequestFaultyAPI.setDescription(descriptionFaultyAPI); + apiRequestFaultyAPI.setVersion(APIVersionFaultyAPI); + apiPublisher.addAPI(apiRequestFaultyAPI); + APIBean apiBeanFaultyAPI = APIMgtTestUtil + .getAPIBeanFromHttpResponse(apiPublisher.getApi(APINameFaultyAPI, providerName)); + APILifeCycleStateRequest updateRequestFaultyAPI = + new APILifeCycleStateRequest(APINameFaultyAPI, providerName, + APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequestFaultyAPI); + apiStore.addApplication("UsageTestAPIFaultyAPI-Application", "Gold", "", "this-is-test"); + SubscriptionRequest subscriptionRequestFaultyAPI = new SubscriptionRequest(APINameFaultyAPI, + context.getContextTenant() + .getContextUser() + .getUserName()); + subscriptionRequestFaultyAPI.setApplicationName("UsageTestAPIFaultyAPI-Application"); + apiStore.subscribe(subscriptionRequestFaultyAPI); + apiPublisher.addDocument(APINameFaultyAPI, APIVersionFaultyAPI, providerName, "Doc-Name", + "How To", "In-line", "url-no-need", "summary", ""); + + GenerateAppKeyRequest generateAppKeyRequestFaultyAPI = + new GenerateAppKeyRequest("UsageTestAPIFaultyAPI-Application"); + String responseStringFaultyAPI = + apiStore.generateApplicationKey(generateAppKeyRequestFaultyAPI).getData(); + JSONObject responseFaultyAPI = new JSONObject(responseStringFaultyAPI); + String accessTokenFaultyAPI = + responseFaultyAPI.getJSONObject("data").getJSONObject("key").get("accessToken") + .toString(); + Map requestHeadersFaultyAPI = new HashMap(); + requestHeadersFaultyAPI.put("Authorization", "Bearer " + accessTokenFaultyAPI); + HttpResponse youTubeResponseFaultyAPI = HttpRequestUtil + .doGet(getApiInvocationURLHttp("UsageTestAPIFaultyAPI/1.0.0/most_popular"), + requestHeadersFaultyAPI); + Assert.assertEquals(youTubeResponseFaultyAPI.getResponseCode(), 500, + "Response code mismatched"); + for (int i = 0; i < 20; i++) { + youTubeResponseFaultyAPI = HttpRequestUtil + .doGet(getApiInvocationURLHttp("UsageTestAPIFaultyAPI/1.0.0/incorrect"), + requestHeaders); + } + + //host object tests + String fileName = "testUsageWithBAM.jag"; + String sourcePath = computeJaggeryResourcePath(fileName); + String destinationPath = computeDestinationPath(fileName); + copySampleFile(sourcePath, destinationPath); + + Thread.sleep(240000); + String finalOutputUsageTest = null; + //ClientConnectionUtil.waitForPort(9763, ""); + try { + URL jaggeryURL = new URL(getTestApplicationUsagePublisherServerURLHttp()); + URLConnection jaggeryServerConnection = jaggeryURL.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader( + jaggeryServerConnection.getInputStream())); + + String inputLine; + while ((inputLine = in.readLine()) != null) { + finalOutputUsageTest = inputLine; + } + String[] arr = finalOutputUsageTest.split("=="); + System.out.println(finalOutputUsageTest); + validateUsageResponseArray(arr); + in.close(); + } catch (IOException e) { + log.error("Error while invoking test application to test publisher host object"); + } finally { + assertNotNull(finalOutputUsageTest, "Result cannot be null"); + } + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + apiStore.removeApplication("UsageTestAPI-Application"); + apiStore.removeApplication("UsageTestAPIFaultyAPI-Application"); + super.cleanup(); + } + + //take exact count + public static boolean validateUsageResponseArray(String[] array) { + //This order is based on the operations of jaggery file operation order + //If we edit jaggary file we need to modify this as well + Assert.assertNotNull(array[1], + "Error while getting API Usage for Subscriber from API publisher host object (getAPIUsageforSubscriber)"); + Assert.assertNotNull(array[2], + "Error while getting API Faulty Analyze By Time from API publisher host object (getAPIFaultyAnalyzeByTime)"); + Assert.assertNotNull(array[3], + "Error while getting API Response Fault Count from API publisher host object (getAPIResponseFaultCount)"); + Assert.assertNotNull(array[4], + "Error while getting external api stores from API publisher host object (getAPIUsageByResourcePath)"); + Assert.assertNotNull(array[5], + "Error while getting external api stores from API publisher host object (getAPIUsageByUser)"); + Assert.assertNotNull(array[6], + "Error while getting external api stores from API publisher host object (getAllAPIUsageByProvider)"); + Assert.assertNotNull(array[7], + "Error while getting external api stores from API publisher host object (getFirstAccessTime)"); + Assert.assertNotNull(array[8], + "Error while getting external api stores from API publisher host object (getProviderAPIServiceTime)"); + Assert.assertNotNull(array[9], + "Error while getting external api stores from API publisher host object (getProviderAPIUsage)"); + Assert.assertNotNull(array[10], + "Error while getting external api stores from API publisher host object (getProviderAPIVersionUsage)"); + Assert.assertNotNull(array[11], + "Error while getting external api stores from API publisher host object (getProviderAPIVersionUserUsage)"); + Assert.assertNotNull(array[12], + "Error while getting external api stores from API publisher host object (getProviderAPIVersionUserLastAccess)"); + return true; + } +} diff --git a/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/DAOTestCase.java b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/DAOTestCase.java new file mode 100644 index 0000000000..849a9607e5 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/DAOTestCase.java @@ -0,0 +1,207 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.sample; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.am.integration.test.utils.APIMgtTestUtil; +import org.wso2.am.integration.test.utils.bean.*; +import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; +import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; +import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; +import org.wso2.carbon.utils.FileManipulator; +import org.wso2.carbon.utils.ServerConstants; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.util.HashMap; +import java.util.Map; + +public class DAOTestCase extends APIManagerIntegrationTest { + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private ServerConfigurationManager serverConfigurationManager; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(); + apiPublisher = new APIPublisherRestClient(getServerURLHttp()); + apiStore = new APIStoreRestClient(getServerURLHttp()); + + apiPublisher.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + apiStore.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + } + + private void copySampleFile(String sourcePath, String destPath) { + File sourceFile = new File(sourcePath); + File destFile = new File(destPath); + try { + FileManipulator.copyFile(sourceFile, destFile); + } catch (IOException e) { + log.error("Error while copying the sample into Jaggery server", e); + } + } + + private String computeDestPath(String fileName) { + String serverRoot = System.getProperty(ServerConstants.CARBON_HOME); + String deploymentPath = serverRoot + "/repository/deployment/server/jaggeryapps/testapp"; + File depFile = new File(deploymentPath); + if (!depFile.exists() && !depFile.mkdir()) { + log.error("Error while creating the deployment folder : " + + deploymentPath); + } + return deploymentPath + File.separator + fileName; + } + + private String computeSourcePath(String fileName) { + + String sourcePath = getAMResourceLocation() + + File.separator + "jaggery/" + fileName; + return sourcePath; + } + + @Test(groups = { "wso2.am" }, description = "API Life cycle test case") + public void testDAOTestCase() throws Exception { + String APIName = "DAOTestAPI"; + String APIContext = "DAOTestAPI"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiPublisher.addAPI(apiRequest); + apiPublisher.deleteApi(APIName, APIVersion, providerName); + apiPublisher.addAPI(apiRequest); + APIBean apiBean = APIMgtTestUtil + .getAPIBeanFromHttpResponse(apiPublisher.getApi(APIName, providerName)); + APILifeCycleStateRequest updateRequest = + new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + //Test API properties + Assert.assertEquals(apiBean.getId().getApiName(), APIName, "API Name mismatch"); + Assert.assertEquals( + apiBean.getContext().trim().substring(apiBean.getContext().indexOf("/") + 1), + APIContext, "API context mismatch"); + Assert.assertEquals(apiBean.getId().getVersion(), APIVersion, "API version mismatch"); + Assert.assertEquals(apiBean.getId().getProviderName(), providerName, + "Provider Name mismatch"); + for (String tag : apiBean.getTags()) { + Assert.assertTrue(tags.contains(tag), "API tag data mismatched"); + } + Assert.assertEquals(apiBean.getDescription(), description, "API description mismatch"); + + apiStore.addApplication("DAOTestAPI-Application", "Gold", "", "this-is-test"); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, + context.getContextTenant() + .getContextUser() + .getUserName()); + subscriptionRequest.setApplicationName("DAOTestAPI-Application"); + apiStore.subscribe(subscriptionRequest); + + GenerateAppKeyRequest generateAppKeyRequest = + new GenerateAppKeyRequest("DAOTestAPI-Application"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = + response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + Thread.sleep(2000); + + } + + @Test(groups = { "wso2.am" }, description = "Test application object") + public void testApplication() { + String fileName = "testPublisher.jag"; + String sourcePath = computeSourcePath(fileName); + String destinationPath = computeDestPath(fileName); + copySampleFile(sourcePath, destinationPath); + //ClientConnectionUtil.waitForPort(9763, ""); + + String finalOutput = null; + + try { + URL jaggeryURL = new URL("http://localhost:9763/testapp/testPublisher.jag"); + URLConnection jaggeryServerConnection = jaggeryURL.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader( + jaggeryServerConnection.getInputStream())); + + String inputLine; + while ((inputLine = in.readLine()) != null) { + finalOutput = inputLine; + } + + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + // assertNotNull(finalOutput, "Result cannot be null"); + } + + } + + @Test(groups = { "wso2.am" }, description = "Test application operations") + public void testApplicationOperations() { + //ClientConnectionUtil.waitForPort(9763, ""); + + + String finalOutput = null; + + try { + URL jaggeryURL = new URL("http://localhost:9763/testapp/testPublisher.jag"); + URLConnection jaggeryServerConnection = jaggeryURL.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader( + jaggeryServerConnection.getInputStream())); + + String inputLine; + while ((inputLine = in.readLine()) != null) { + finalOutput = inputLine; + } + + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + // assertEquals(finalOutput, "test jaggery application value"); + } + + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + apiStore.removeApplication("DAOTestAPI-Application"); + super.cleanup(); + } +} diff --git a/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/HostObjectTestCase.java b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/HostObjectTestCase.java new file mode 100644 index 0000000000..8ca2d29fdd --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/HostObjectTestCase.java @@ -0,0 +1,427 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.sample; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.am.integration.test.utils.APIMgtTestUtil; +import org.wso2.am.integration.test.utils.bean.*; +import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; +import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; +import org.wso2.carbon.automation.extensions.jmeter.JMeterTest; +import org.wso2.carbon.automation.extensions.jmeter.JMeterTestManager; +import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; +import org.wso2.carbon.utils.FileManipulator; +import org.wso2.carbon.utils.ServerConstants; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.util.HashMap; +import java.util.Map; + +import static org.testng.Assert.assertNotNull; + +public class HostObjectTestCase extends APIManagerIntegrationTest { + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private ServerConfigurationManager serverConfigurationManager; + private String publisherURLHttp; + private String storeURLHttp; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(); + if (isBuilderEnabled()) { + /* + If test run in external distributed deployment you need to copy following resources accordingly. + configFiles/hostobjecttest/api-manager.xml + configFiles/tokenTest/log4j.properties + Also need to copy the content of /resources/artifacts/AM/jaggery to servers following folder folder + repository/deployment/server/jaggeryapps/testapp + */ + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + serverConfigurationManager = new ServerConfigurationManager(context); + serverConfigurationManager.applyConfiguration(new File(getAMResourceLocation() + + File.separator + + "configFiles/hostobjecttest/" + + "api-manager.xml")); + serverConfigurationManager.applyConfiguration(new File(getAMResourceLocation() + + File.separator + + "configFiles/tokenTest/" + + "log4j.properties")); + super.init(); + } else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + apiPublisher = new APIPublisherRestClient(publisherURLHttp); + apiStore = new APIStoreRestClient(storeURLHttp); + + apiPublisher.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + apiStore.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + } + + private void copySampleFile(String sourcePath, String destPath) { + File sourceFile = new File(sourcePath); + File destFile = new File(destPath); + try { + FileManipulator.copyFile(sourceFile, destFile); + } catch (IOException e) { + log.error("Error while copying the sample into Jaggery server", e); + } + } + + private String computeDestPath(String fileName) { + String serverRoot = System.getProperty(ServerConstants.CARBON_HOME); + String deploymentPath = serverRoot + "/repository/deployment/server/jaggeryapps/testapp"; + File depFile = new File(deploymentPath); + if (!depFile.exists() && !depFile.mkdir()) { + log.error("Error while creating the deployment folder : " + + deploymentPath); + } + return deploymentPath + File.separator + fileName; + } + + private String computeSourcePath(String fileName) { + + String sourcePath = getAMResourceLocation() + + File.separator + "jaggery/" + fileName; + return sourcePath; + } + + @Test(groups = { "wso2.am" }, description = "API Life cycle test case") + public void testHostObjectTestCase() throws Exception { + //Tenant Create test cases - This will create new tenant in the system + JMeterTest script = + new JMeterTest(new File(getAMResourceLocation() + File.separator + "scripts" + + File.separator + "tenant_create.jmx")); + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(script); + //End of tenant creation + + String APIName = "HostObjectTestAPI"; + String APIContext = "HostObjectTestAPIAPIContext"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiPublisher.addAPI(apiRequest); + apiPublisher.deleteApi(APIName, APIVersion, providerName); + apiPublisher.addAPI(apiRequest); + APIBean apiBean = APIMgtTestUtil + .getAPIBeanFromHttpResponse(apiPublisher.getApi(APIName, providerName)); + APILifeCycleStateRequest updateRequest = + new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + //Test API properties + Assert.assertEquals(apiBean.getId().getApiName(), APIName, "API Name mismatch"); + Assert.assertEquals( + apiBean.getContext().trim().substring(apiBean.getContext().indexOf("/") + 1), + APIContext, "API context mismatch"); + Assert.assertEquals(apiBean.getId().getVersion(), APIVersion, "API version mismatch"); + Assert.assertEquals(apiBean.getId().getProviderName(), providerName, + "Provider Name mismatch"); + for (String tag : apiBean.getTags()) { + Assert.assertTrue(tags.contains(tag), "API tag data mismatched"); + } + Assert.assertEquals(apiBean.getDescription(), description, "API description mismatch"); + apiStore.addApplication("HostObjectTestAPI-Application", "Gold", "", "this-is-test"); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, + context.getContextTenant() + .getContextUser() + .getUserName()); + subscriptionRequest.setApplicationName("HostObjectTestAPI-Application"); + apiStore.subscribe(subscriptionRequest); + apiPublisher.addDocument(APIName, APIVersion, providerName, "Doc-Name", "How To", "In-line", + "url-no-need", "summary", ""); + GenerateAppKeyRequest generateAppKeyRequest = + new GenerateAppKeyRequest("HostObjectTestAPI-Application"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = + response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + + //host object tests + String fileName = "testPublisher.jag"; + String sourcePath = computeSourcePath(fileName); + String destinationPath = computeDestPath(fileName); + copySampleFile(sourcePath, destinationPath); + + fileName = "testStore.jag"; + sourcePath = computeSourcePath(fileName); + destinationPath = computeDestPath(fileName); + copySampleFile(sourcePath, destinationPath); + + Thread.sleep(20000); + String finalOutputPublisher = null; + //ClientConnectionUtil.waitForPort(9763, ""); + try { + URL jaggeryURL = new URL(getTestApplicationPublisherServerURLHttp()); + URLConnection jaggeryServerConnection = jaggeryURL.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader( + jaggeryServerConnection.getInputStream())); + + String inputLine; + while ((inputLine = in.readLine()) != null) { + finalOutputPublisher = inputLine; + } + String[] arr = finalOutputPublisher.split("=="); + System.out.println(finalOutputPublisher); + validatePublisherResponseArray(arr); + in.close(); + } catch (IOException e) { + log.error("Error while invoking test application to test publisher host object"); + } finally { + assertNotNull(finalOutputPublisher, "Result cannot be null"); + } + + String finalOutputStore = null; + Thread.sleep(20000); + //ClientConnectionUtil.waitForPort(9763, ""); + try { + URL jaggeryURL = new URL(getTestApplicationStoreServerURLHttp()); + URLConnection jaggeryServerConnection = jaggeryURL.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader( + jaggeryServerConnection.getInputStream())); + + String inputLine; + while ((inputLine = in.readLine()) != null) { + finalOutputStore = inputLine; + } + String[] arr = finalOutputStore.split("=="); + validateStoreResponseArray(arr); + System.out.println(finalOutputStore); + in.close(); + } catch (IOException e) { + log.error("Error while invoking test application to test publisher host object"); + } finally { + assertNotNull(finalOutputStore, "Result cannot be null"); + } + } + + @Test(groups = { "wso2.am" }, description = "Test application object") + public void testApplication() { + } + + @Test(groups = { "wso2.am" }, description = "Test application operations") + public void testApplicationOperations() { + } + + @Test(groups = { "wso2.am" }, description = "Test application operations") + public void testAPIProvider() { + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + apiStore.removeApplication("HostObjectTestAPI-Application"); + super.cleanup(); + } + + public static boolean validateStoreResponseArray(String[] array) { + //This order is based on the operations of jaggery file operation order + //If we edit jaggery file we need to modify this as well + Assert.assertTrue(array[1].contains("true"), + "Error while getting status of billing system from API store host object (isBillingEnabled)"); + Assert.assertTrue(array[2].contains("https"), + "Error while getting https url from API store host object (getHTTPsURL)"); + Assert.assertTrue(array[4].contains("http"), + "Error while getting http url from API store host object (getHTTPURL)"); + Assert.assertTrue(array[3].contains("services"), + "Error while getting auth service url from API store host object (getAuthServerURL)"); + Assert.assertTrue(array[5].contains("[{\"tierName\" : \"Gold\"}]"), + "Error while getting denied tiers from API store host object (getDeniedTiers)"); + Assert.assertTrue(array[6].contains("tenantdomain1.com"), + "Error while getting active tenant domains from API store host object (getActiveTenantDomains)"); + Assert.assertTrue(array[7].contains("true"), + "Error while getting status of self sign in from API store host object (isSelfSignupEnabled)"); + Assert.assertTrue(array[8].contains("fieldName"), + "Error while getting user fields from API store host object (getUserFields)"); + Assert.assertTrue(array[9].contains("HostObjectTestAPI"), + "Error while search Paginated APIs By Type from API store host object (searchPaginatedAPIsByType)"); + Assert.assertTrue(array[10].contains("HostObjectTestAPI"), + "Error while search Paginated APIs By Type with pattern * from API store host object (searchPaginatedAPIsByType)"); + Assert.assertTrue(array[11].contains("HostObjectTestAPI"), + "Error while search API by Type with pattern * from API store host object (searchAPIbyType)"); + Assert.assertTrue(array[12].contains("HostObjectTestAPI"), + "Error while search API by type from API store host object (searchAPIbyType)"); + Assert.assertTrue(array[13].contains("HostObjectTestAPI"), + "Error while getting paginated APIs with tag from API store host object (getPaginatedAPIsWithTag)"); + //14 getPublishedAPIsByProvider + //15 getAllSubscriptions + Assert.assertTrue(array[16].contains("HostObjectTestAPI"), + "Error while rating API from API store host object (rateAPI)"); + Assert.assertTrue(array[17].contains("[{\"newRating\" : \"0.0\"}]"), + "Error while removing rating from API store host object (removeAPIRating)"); + Assert.assertTrue(array[18].contains("apis"), + "Error while getting Paginated , published APIs from API store host object (getAllPaginatedPublishedAPIs)"); + Assert.assertTrue(array[19].contains("HostObjectTestAPI"), + "Error while getting APIs With Tag from API store host object (getAPIsWithTag)"); + Assert.assertTrue(array[20].contains("HostObjectTestAPI"), + "Error while getting all published APIs from API store host object (getAllPublishedAPIs)"); + //21 getComments + Assert.assertTrue(array[22].contains("true"), + "Error while checking user in the system from API store host object (isUserExists)"); + Assert.assertTrue(array[23].contains("HostObjectTestAPI"), + "Error while getting API from API store host object (getAPI)"); + Assert.assertTrue(array[24].contains("true"), + "Error while checking subscription state from API store host object (isSubscribed)"); + Assert.assertTrue(array[25].contains("application"), + "Error while getting subscriptions from API store host object (getSubscriptions)"); + //26 getSubscribedAPIs + Assert.assertTrue(array[27].contains("true"), + "Error while checking user permission from API store host object (hasUserPermissions)"); + //28 getTiers + //29 getAPIUsageforSubscriber + //30 getDeniedTiers + //31 getRecentlyAddedAPIs + //32 getTopRatedAPIs + Assert.assertTrue(array[33].contains("true"), + "Error while getting billing status from API store host object (isBillingEnabled)"); + Assert.assertTrue(array[34].contains("true"), + "Error while checking Subscribe Permission from API store host object (hasSubscribePermission)"); + Assert.assertTrue(array[35].contains("false"), + "Error while getting state of Email Username from API store host object (isEnableEmailUsername)"); + Assert.assertTrue(array[36].contains("true"), + "Error while update Application Tier from API store host object (updateApplicationTier)"); + Assert.assertTrue(array[37].contains("true"), + "Error while update Application from API store host object (updateApplication)"); + Assert.assertTrue(array[38].contains("200"), + "Error while validate WF Permission from API store host object (validateWFPermission)"); + Assert.assertTrue(array[38].contains("200"), + "Error while validate WF Permission from API store host object (validateWFPermission)"); + System.out.println("\n\n\n\n\n\n40 : "+array[40]); + Assert.assertTrue(array[40].contains("HostObjectTestAPI"), + "Error while getting all published APIs from API store host object search by context(search)"); + Assert.assertTrue(array[41].contains("HostObjectTestAPI"), + "Error while getting all published APIs from API store host object search by version(search)"); + Assert.assertTrue(!array[42].contains("HostObjectTestAPI"), + "Error while getting all published APIs from API store host object search by non-existing context (search)"); + Assert.assertTrue(!array[43].contains("HostObjectTestAPI"), + "Error while getting all published APIs from API store host object search by non-existing version(search)"); + + return true; + } + + public static boolean validatePublisherResponseArray(String[] array) { + //This order is based on the operations of jaggery file operation order + //If we edit jaggary file we need to modify this as well + /*Assert.assertNotNull(array[1], + "Error while getting external api stores from API store host object (getExternalAPIStores)");*/ + Assert.assertTrue(array[1].contains("true"), + "Error while validating roles from API store host object (validateRoles)"); + Assert.assertTrue(array[2].contains("success"), + "Error while checking url validity from API store host object (isURLValid)"); + Assert.assertTrue(array[3].contains("HostObjectTestAPI"), + "Error while getting APIs by provider from API store host object (getAPIsByProvider)"); + Assert.assertTrue(array[4].contains("HostObjectTestAPI"), + "Error while getting subscribed APIs from API store host object (getSubscribedAPIs)"); + Assert.assertTrue(array[5].contains("HostObjectTestAPI"), + "Error while getting API from API store host object (getAPI)"); + Assert.assertTrue(array[6].contains("Bronze"), + "Error while getting tier permission from API store host object (getTierPermissions)"); + Assert.assertTrue(array[7].contains("Bronze"), + "Error while getting tiers from API store host object (getTiers)"); + Assert.assertTrue(array[8].contains("HostObjectTestAPI"), + "Error while getting all APIs By Type from API store host object (getAllAPIs)"); + Assert.assertTrue(array[9].contains("HostObjectTestAPI"), + "Error while getting APIs By provider with pattern * from API store host object (getAPIsByProvider)"); + Assert.assertTrue(array[10].contains("subscribedDate"), + "Error while getting subscribers of API from API store host object (getSubscribersOfAPI)"); + Assert.assertTrue(array[11].contains("false"), + "Error while checking contexts from API store host object (isContextExist)"); + Assert.assertTrue(array[12].contains("HostObjectTestAPI"), + "Error while searching APIs from API store host object (searchAPIs)"); + Assert.assertTrue(array[13].contains("true"), + "Error while checking create permission from API store host object (hasCreatePermission)"); + Assert.assertTrue(array[14].contains("true"), + "Error while checking manage tier permission from API store host object (hasManageTierPermission)"); + Assert.assertTrue(array[15].contains("true"), + "Error while checking user permission from API store host object (hasUserPermissions)"); + Assert.assertTrue(array[16].contains("true"), + "Error while checking publisher permissions (hasPublishPermission)"); + Assert.assertTrue(array[17].contains("services"), + "Error while getting auth server url from API store host object (getAuthServerURL)"); + Assert.assertTrue(array[18].contains("[\"log_in_message\"]"), + "Error while getting in sequences from API store host object (getCustomInSequences)"); + Assert.assertTrue(array[19].contains("[\"log_out_message\"]"), + "Error while getting out sequences from API store host object (getCustomOutSequences)"); + Assert.assertTrue(array[20].contains("https"), + "Error while getting https url from API store host object (getHTTPsURL)"); + Assert.assertTrue(array[21].contains("true"), + "Error while checking gateway type from API store host object (isSynapseGateway)"); + Assert.assertTrue(array[22].contains("null"), + "Error while load Registry Of Tenant API store host object (loadRegistryOfTenant)"); + /*Assert.assertTrue(array[23].contains("true"), + "Error while update Documentation from API store host object (updateDocumentation)");*/ + /*Assert.assertTrue(array[23].contains("null"), + "Error while adding Inline Content from API store host object (addInlineContent)");*/ + Assert.assertTrue(array[23].contains("providerName"), + "Error while getting Inline Content from API store host object (getInlineContent)"); + /*Assert.assertTrue(array[24].contains("docName"), + "Error while getting All Documentation from API store host object (getAllDocumentation)");*/ + Assert.assertTrue(array[25].contains("token"), + "Error while search Access Tokens from API store host object (searchAccessTokens)"); + //Assert.assertTrue(array[29].contains("true"), "Error while checking user permission from API store host object (getSubscriberCountByAPIs)"); + //Assert.assertTrue(array[30].contains("true"), "Error while checking user permission from API store host object (getSubscriberCountByAPIVersions)"); + //Assert.assertTrue(array[31].contains("null"), "Error while getting External API Stores from API store host object (getExternalAPIStores)"); + Assert.assertTrue(array[28].contains("false"), + "Error while checking API Older Versions from API store host object (isAPIOlderVersionExist)"); + Assert.assertTrue(array[29].contains("true"), + "Error while update Subscription Status from API store host object (updateSubscriptionStatus)"); + Assert.assertTrue(array[30].contains("true"), + "Error while update Tier Permissions from API store host object (updateTierPermissions)"); + Assert.assertTrue(array[31].contains("HostObjectTestAPI"), + "Error while search API by provider (searchAPIs)"); + Assert.assertTrue(array[32].contains("HostObjectTestAPI"), + "Error while search API by context (searchAPIs)"); + Assert.assertTrue(array[33].contains("HostObjectTestAPI"), + "Error while search API by uppercase name (searchAPIs)"); + Assert.assertTrue(array[34].contains("HostObjectTestAPI"), + "Error while search API by lower case name (searchAPIs)"); + Assert.assertTrue(array[35].contains("HostObjectTestAPI"), + "Error while search API by part of the API name (searchAPIs)"); + Assert.assertTrue(array[36].contains("HostObjectTestAPI"), + "Error while search API by part of the provider (searchAPIs)"); + Assert.assertTrue(array[37].contains("HostObjectTestAPI"), + "Error while search API by part of the context (searchAPIs)"); + Assert.assertTrue(!array[38].contains("HostObjectTestAPI"), + "Error while search API by invalid search key (searchAPIs)"); + + return true; + } +} diff --git a/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/JWTTestCase.java b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/JWTTestCase.java new file mode 100644 index 0000000000..8ea81fc901 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/JWTTestCase.java @@ -0,0 +1,373 @@ +package org.wso2.carbon.am.tests.sample; + +import org.json.JSONException; +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.am.integration.test.utils.APIMgtTestUtil; +import org.wso2.am.integration.test.utils.bean.*; +import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; +import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; +import org.wso2.carbon.automation.engine.context.AutomationContext; +import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.carbon.automation.test.utils.common.WireMonitorServer; +import org.wso2.carbon.integration.common.admin.client.TenantManagementServiceClient; +import org.wso2.carbon.integration.common.admin.client.UserManagementClient; +import org.wso2.carbon.integration.common.utils.LoginLogoutClient; +import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; + +import java.io.File; +import java.net.URL; + +import static junit.framework.Assert.assertTrue; + +public class JWTTestCase extends APIManagerIntegrationTest{ + + private ServerConfigurationManager serverConfigurationManager; + private UserManagementClient userManagementClient; + private TenantManagementServiceClient tenantManagementServiceClient; + + private String publisherURLHttp; + private String storeURLHttp; + private WireMonitorServer server; + private int hostPort = 9988; + + private String APIName = "JWTTokenTestAPI"; + private String APIContext = "tokenTest"; + private String tags = "token, jwt"; + private String url = "http://localhost:9988"; + private String description = "This is test API create by API manager integration test"; + private String providerName = "admin"; + private String APIVersion = "1.0.0"; + private String ApplicationName = "APILifeCycleTestAPI-application"; + private String APITier = "Gold"; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(); + + if (isBuilderEnabled()) { + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + + serverConfigurationManager = new ServerConfigurationManager(context); + serverConfigurationManager.applyConfigurationWithoutRestart(new File(getAMResourceLocation() + + File.separator + + "configFiles/tokenTest/" + + "api-manager.xml")); + serverConfigurationManager.applyConfiguration(new File(getAMResourceLocation() + + File.separator + + "configFiles/tokenTest/" + + "log4j.properties")); + + } else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + + + userManagementClient = new UserManagementClient( + context.getContextUrls().getBackEndUrl(), context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + AutomationContext automationContext = new AutomationContext("AM", TestUserMode.SUPER_TENANT_ADMIN); + LoginLogoutClient loginLogoutClient = new LoginLogoutClient(automationContext); + + tenantManagementServiceClient = new TenantManagementServiceClient( + context.getContextUrls().getBackEndUrl(), loginLogoutClient.login()); + + + server = new WireMonitorServer(hostPort); + server.setReadTimeOut(300); + server.start(); + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + super.cleanup(); + serverConfigurationManager.restoreToLastConfiguration(); + } + + private void addAPI() throws Exception { + + APIPublisherRestClient apiPublisher = new APIPublisherRestClient(publisherURLHttp); + + apiPublisher.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiRequest.setWsdl("https://svn.wso2.org/repos/wso2/carbon/platform/trunk/products" + + "/bps/modules/samples/product/src/main/resources/bpel/2.0/MyRoleMexTestProcess/echo.wsdl"); + apiRequest.setVisibility("public"); + apiPublisher.addAPI(apiRequest); + + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName, + APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + + } + + @Test(groups = {"wso2.am"}, description = "Enabling JWT Token generation, admin user claims", enabled = true) + public void testEnableJWTAndClaims() throws Exception { + +// RemoteUserStoreManagerServiceClient remoteUserStoreManagerServiceClient = new RemoteUserStoreManagerServiceClient( +// context.getContextUrls().getBackEndUrl(), context.getContextTenant().getContextUser().getUserName(), +// context.getContextTenant().getContextUser().getPassword()); + + String username = context.getContextTenant().getContextUser().getUserName(); + String profile = "default"; + +// remoteUserStoreManagerServiceClient.setUserClaimValue( +// username, "http://wso2.org/claims/givenname", +// "first name", profile); +// +// remoteUserStoreManagerServiceClient.setUserClaimValue( +// username, "http://wso2.org/claims/lastname", +// "last name", profile); +// +// remoteUserStoreManagerServiceClient.setUserClaimValue( +// username, "http://wso2.org/claims/wrongclaim", +// "wrongclaim", profile); + + // restart the server since updated claims not picked unless cache expired + serverConfigurationManager.restartGracefully(); + super.init(); + + addAPI(); + + APIStoreRestClient apiStoreRestClient = new APIStoreRestClient(storeURLHttp); + apiStoreRestClient.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + apiStoreRestClient.addApplication(ApplicationName, APITier, "", "this-is-test"); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, + context.getContextTenant().getContextUser().getUserName()); + subscriptionRequest.setApplicationName(ApplicationName); + apiStoreRestClient.subscribe(subscriptionRequest); + + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest(ApplicationName); + String responseString = apiStoreRestClient.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + + String url = getApiInvocationURLHttp("tokenTest/1.0.0/"); + APIMgtTestUtil.sendGetRequest(url, accessToken); + String serverMessage = server.getCapturedMessage(); + + String decodedJWTString = APIMgtTestUtil.getDecodedJWT(serverMessage); + + System.out.println("\n\n\n\n\ndecodedJWTString = " + decodedJWTString); + + JSONObject jsonObject = new JSONObject(decodedJWTString); + + // check default claims + checkDefaultUserClaims(jsonObject); + + // check user profile info claims + String claim = jsonObject.getString("http://wso2.org/claims/givenname"); + assertTrue( "JWT claim givenname not received" + claim , claim.contains("first name")); + + claim = jsonObject.getString("http://wso2.org/claims/lastname"); + assertTrue( "JWT claim lastname not received" + claim , claim.contains("last name")); + + boolean bExceptionOccured = false; + try { + claim = jsonObject.getString("http://wso2.org/claims/wrongclaim"); + } + catch (JSONException e) { + bExceptionOccured = true; + } + + assertTrue( "JWT claim invalid claim received", bExceptionOccured); + } + + private void checkDefaultUserClaims(JSONObject jsonObject) throws JSONException { + String claim = jsonObject.getString("iss"); + assertTrue( "JWT assertion is invalid", claim.contains("wso2.org/products/am")); + + claim = jsonObject.getString("http://wso2.org/claims/subscriber"); + assertTrue( "JWT claim subscriber invalid. Received " + claim , claim.contains("admin")); + + claim = jsonObject.getString("http://wso2.org/claims/applicationname"); + assertTrue( "JWT claim applicationname invalid. Received " + claim , + claim.contains("APILifeCycleTestAPI-application")); + + claim = jsonObject.getString("http://wso2.org/claims/applicationtier"); + assertTrue( "JWT claim applicationtier invalid. Received " + claim , claim.contains("Gold")); + + claim = jsonObject.getString("http://wso2.org/claims/apicontext"); + assertTrue( "JWT claim apicontext invalid. Received " + claim , claim.contains("/tokenTest")); + + claim = jsonObject.getString("http://wso2.org/claims/version"); + assertTrue( "JWT claim version invalid. Received " + claim , claim.contains("1.0.0")); + + claim = jsonObject.getString("http://wso2.org/claims/tier"); + assertTrue( "JWT claim tier invalid. Received " + claim , claim.contains("Gold")); + + claim = jsonObject.getString("http://wso2.org/claims/keytype"); + assertTrue( "JWT claim keytype invalid. Received " + claim , claim.contains("PRODUCTION")); + + claim = jsonObject.getString("http://wso2.org/claims/usertype"); + assertTrue( "JWT claim usertype invalid. Received " + claim , claim.contains("APPLICATION")); + + claim = jsonObject.getString("http://wso2.org/claims/enduserTenantId"); + assertTrue( "JWT claim enduserTenantId invalid. Received " + claim , claim.contains("-1234")); + + claim = jsonObject.getString("http://wso2.org/claims/role"); + assertTrue( "JWT claim role invalid. Received " + claim , + claim.contains("admin,Internal/subscriber,Internal/everyone")); + } + + @Test(groups = {"wso2.am"}, description = "Enabling JWT Token generation, specific user claims", enabled = true) + public void testSpecificUserJWTClaims() throws Exception { + + //server.setFinished(false); + server.start(); + + String subscriberUser = "subscriberUser"; + String password = "password@123"; + String accessToken; + + if ((userManagementClient != null) && + !userManagementClient.userNameExists("Internal/subscriber", subscriberUser)) { + userManagementClient.addUser(subscriberUser, password, + new String[]{"Internal/subscriber"}, null); + } + +// RemoteUserStoreManagerServiceClient remoteUserStoreManagerServiceClient = new RemoteUserStoreManagerServiceClient( +// context.getContextUrls().getBackEndUrl(), context.getContextTenant().getContextUser().getUserName(), +// context.getContextTenant().getContextUser().getPassword()); + + String username = subscriberUser; + String profile = "default"; + +// remoteUserStoreManagerServiceClient.setUserClaimValue( +// username, "http://wso2.org/claims/givenname", +// "subscriberUser name", profile); +// +// remoteUserStoreManagerServiceClient.setUserClaimValue( +// username, "http://wso2.org/claims/lastname", +// "subscriberUser name", profile); + + // restart the server since updated claims not picked unless cache expired + serverConfigurationManager.restartGracefully(); + super.init(); + + APIStoreRestClient apiStoreRestClient = new APIStoreRestClient(storeURLHttp); + apiStoreRestClient.login(subscriberUser, password); + + apiStoreRestClient.addApplication(ApplicationName, APITier, "", "this-is-test"); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, + providerName); + subscriptionRequest.setApplicationName(ApplicationName); + apiStoreRestClient.subscribe(subscriptionRequest); + + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest(ApplicationName); + String responseString = apiStoreRestClient.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + + String url = getApiInvocationURLHttp("tokenTest/1.0.0/"); + + APIMgtTestUtil.sendGetRequest(url, accessToken); + String serverMessage = server.getCapturedMessage(); + + Assert.assertTrue(serverMessage.contains("X-JWT-Assertion"), "JWT assertion not in the header"); + + String decodedJWTString = APIMgtTestUtil.getDecodedJWT(serverMessage); + + System.out.println("\n\n\n\n\ndecodedJWTString = " + decodedJWTString); + + JSONObject jsonObject = new JSONObject(decodedJWTString); + + // check claims + String claim = jsonObject.getString("iss"); + assertTrue( "JWT assertion is invalid", claim.contains("wso2.org/products/am")); + + claim = jsonObject.getString("http://wso2.org/claims/subscriber"); + assertTrue( "JWT claim subscriber invalid. Received " + claim , claim.contains("subscriberUser")); + + claim = jsonObject.getString("http://wso2.org/claims/applicationname"); + assertTrue( "JWT claim applicationname invalid. Received " + claim , + claim.contains("APILifeCycleTestAPI-application1")); + + } + + + @Test(groups = {"wso2.am"}, description = "Enabling JWT Token generation, tenant user claims" , enabled = false) + public void testTenantUserJWTClaims() throws Exception { + + //server.setFinished(false); + server.start(); + + tenantManagementServiceClient.addTenant("wso2.com", "wso2@123", "admin", "Gold"); + + serverConfigurationManager.restartGracefully(); + super.init(); + + String provider = "admin-AT-wso2.com"; + String tenantUser = "admin@wso2.com"; + String password = "wso2@123"; + String accessToken; + + APIPublisherRestClient apiPublisherRestClient = new APIPublisherRestClient(publisherURLHttp); + + apiPublisherRestClient.login(tenantUser, password); + + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiRequest.setWsdl("https://svn.wso2.org/repos/wso2/carbon/platform/trunk/products" + + "/bps/modules/samples/product/src/main/resources/bpel/2.0/MyRoleMexTestProcess/echo.wsdl"); + apiRequest.setVisibility("public"); + + apiRequest.setProvider(provider); + apiPublisherRestClient.addAPI(apiRequest); + + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, provider, + APILifeCycleState.PUBLISHED); + apiPublisherRestClient.changeAPILifeCycleStatusTo(updateRequest); + + APIStoreRestClient apiStoreRestClient = new APIStoreRestClient(storeURLHttp); + apiStoreRestClient.login(tenantUser, password); + + apiStoreRestClient.addApplication(ApplicationName, APITier, "", "this-is-test"); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, + provider); + subscriptionRequest.setApplicationName(ApplicationName); + apiStoreRestClient.subscribe(subscriptionRequest); + + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest(ApplicationName); + String responseString = apiStoreRestClient.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + + String url = getApiInvocationURLHttp("t/wso2.com/tokenTest/1.0.0/"); + APIMgtTestUtil.sendGetRequest(url, accessToken); + String serverMessage = server.getCapturedMessage(); + + String decodedJWTString = APIMgtTestUtil.getDecodedJWT(serverMessage); + + JSONObject jsonObject = new JSONObject(decodedJWTString); + + System.out.println("\n\n\n\n\ndecodedJWTString = " + decodedJWTString); + // check claims + String claim = jsonObject.getString("iss"); + assertTrue( "JWT assertion is invalid", claim.contains("wso2.org/products/am")); + + claim = jsonObject.getString("http://wso2.org/claims/subscriber"); + assertTrue( "JWT claim subscriber invalid. Received " + claim , claim.contains("admin@wso2.com")); + + claim = jsonObject.getString("http://wso2.org/claims/apicontext"); + assertTrue( "JWT claim apicontext invalid. Received " + claim , claim.contains("/t/wso2.com/tokenTest")); + + } + +} diff --git a/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/RefreshTokenTestCase.java b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/RefreshTokenTestCase.java new file mode 100644 index 0000000000..612f1db81b --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/RefreshTokenTestCase.java @@ -0,0 +1,184 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF 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.carbon.am.tests.sample; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.am.integration.test.utils.bean.*; +import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; +import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; +import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; +import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; +import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; + +import java.io.File; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class RefreshTokenTestCase extends APIManagerIntegrationTest { + + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private ServerConfigurationManager serverConfigurationManager; + private String publisherURLHttp; + private String storeURLHttp; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + + super.init(); + /* + If test run in external distributed deployment you need to copy following resources accordingly. + configFiles/hostobjecttest/api-manager.xml + configFiles/tokenTest/log4j.properties + */ + if (isBuilderEnabled()) { + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + serverConfigurationManager = new ServerConfigurationManager(context); + serverConfigurationManager.applyConfiguration(new File(getAMResourceLocation() + + File.separator + + "configFiles/tokenTest/" + + "api-manager.xml")); + serverConfigurationManager.applyConfiguration(new File(getAMResourceLocation() + + File.separator + + "configFiles/tokenTest/" + + "log4j.properties")); + super.init(); + } else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + apiPublisher = new APIPublisherRestClient(publisherURLHttp); + apiStore = new APIStoreRestClient(storeURLHttp); + + } + + @Test(groups = { "wso2.am" }, description = "Token API Test sample") + public void testTokenAPITestCase() throws Exception { + String APIName = "RefreshTokenTestAPI"; + String APIContext = "refreshTokenTestAPI"; + String tags = "youtube, token, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + apiPublisher.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiRequest.setSandbox(url); + apiPublisher.addAPI(apiRequest); + APILifeCycleStateRequest updateRequest = + new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + + apiStore.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + apiStore.addApplication("RefreshTokenTestAPI-Application", "Gold", "", "this-is-test"); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, + context.getContextTenant() + .getContextUser() + .getUserName()); + subscriptionRequest.setTier("Gold"); + subscriptionRequest.setApplicationName("RefreshTokenTestAPI-Application"); + apiStore.subscribe(subscriptionRequest); + + //Generate production token and invoke with that + GenerateAppKeyRequest generateAppKeyRequest = + new GenerateAppKeyRequest("RefreshTokenTestAPI-Application"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + + // get Consumer Key and Consumer Secret + String consumerKey = + response.getJSONObject("data").getJSONObject("key").getString("consumerKey"); + String consumerSecret = + response.getJSONObject("data").getJSONObject("key").getString("consumerSecret"); + + //Obtain user access token + Thread.sleep(2000); + String requestBody = "grant_type=password&username=admin&password=admin&scope=PRODUCTION"; + URL tokenEndpointURL = new URL("https://localhost:8243/token"); + JSONObject accessTokenGenerationResponse = new JSONObject( + apiStore.generateUserAccessKey(consumerKey, consumerSecret, requestBody, + tokenEndpointURL).getData()); + /* + Response would be like - + {"token_type":"bearer","expires_in":3600,"refresh_token":"736b6b5354e4cf24f217718b2f3f72b", + "access_token":"e06f12e3d6b1367d8471b093162f6729"} + */ + + // get Access Token and Refresh Token + String userAccessToken = accessTokenGenerationResponse.getString("access_token"); + String refreshToken = accessTokenGenerationResponse.getString("refresh_token"); + + Map requestHeaders = new HashMap(); + //Check Access Token + requestHeaders.put("Authorization", "Bearer " + userAccessToken); + Thread.sleep(2000); + HttpResponse youTubeResponse = HttpRequestUtil + .doGet(getApiInvocationURLHttp("refreshTokenTestAPI/1.0.0/most_popular"), requestHeaders); + //check JWT headers here + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched"); + Assert.assertTrue(youTubeResponse.getData().contains(""), + "Response data mismatched"); + + // get a new access token using refresh token + String getAccessTokenFromRefreshTokenRequestBody = + "grant_type=refresh_token&refresh_token=" + refreshToken + "&scope=PRODUCTION"; + accessTokenGenerationResponse = new JSONObject( + apiStore.generateUserAccessKey(consumerKey, consumerSecret, + getAccessTokenFromRefreshTokenRequestBody, + tokenEndpointURL).getData()); + userAccessToken = accessTokenGenerationResponse.getString("access_token"); + + requestHeaders = new HashMap(); + //Check with new Access Token + requestHeaders.put("Authorization", "Bearer " + userAccessToken); + Thread.sleep(2000); + youTubeResponse = HttpRequestUtil + .doGet(getApiInvocationURLHttp("refreshTokenTestAPI/1.0.0/most_popular"), requestHeaders); + //check JWT headers here + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched"); + Assert.assertTrue(youTubeResponse.getData().contains(""), + "Response data mismatched"); + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + apiStore.removeApplication("RefreshTokenTestAPI-Application"); + super.cleanup(); + serverConfigurationManager.restoreToLastConfiguration(); + } +} \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/TagsRatingCommentTestCase.java b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/TagsRatingCommentTestCase.java new file mode 100644 index 0000000000..8fe77ea6d7 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/TagsRatingCommentTestCase.java @@ -0,0 +1,173 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.sample; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.am.integration.test.utils.APIMgtTestUtil; +import org.wso2.am.integration.test.utils.bean.*; +import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; +import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; +import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; +import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class TagsRatingCommentTestCase extends APIManagerIntegrationTest { + + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private String publisherURLHttp; + private String storeURLHttp; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(); + /* + This test can point to external API manager deployment without adding any resources to system + */ + if (isBuilderEnabled()) { + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + } else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + apiPublisher = new APIPublisherRestClient(publisherURLHttp); + apiStore = new APIStoreRestClient(storeURLHttp); + + apiPublisher.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + apiStore.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + } + + @Test(groups = { "wso2.am" }, description = "Comment Rating Test case") + public void testTagsRatingCommentTestCase() throws Exception { + String APIName = "CommentRatingAPI"; + String APIContext = "commentRating"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiPublisher.addAPI(apiRequest); + APIBean apiBean = APIMgtTestUtil + .getAPIBeanFromHttpResponse(apiPublisher.getApi(APIName, providerName)); + APILifeCycleStateRequest updateRequest = + new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + //Test API properties + Assert.assertEquals(apiBean.getId().getApiName(), APIName, "API Name mismatch"); + Assert.assertEquals( + apiBean.getContext().trim().substring(apiBean.getContext().indexOf("/") + 1), + APIContext, "API context mismatch"); + Assert.assertEquals(apiBean.getId().getVersion(), APIVersion, "API version mismatch"); + Assert.assertEquals(apiBean.getId().getProviderName(), providerName, + "Provider Name mismatch"); + for (String tag : apiBean.getTags()) { + Assert.assertTrue(tags.contains(tag), "API tag data mismatched"); + } + Assert.assertEquals(apiBean.getDescription(), description, "API description mismatch"); + + apiStore.addApplication("CommentRatingAPI-Application", "Gold", "", "this-is-test"); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, + context.getContextTenant() + .getContextUser() + .getUserName()); + subscriptionRequest.setApplicationName("CommentRatingAPI-Application"); + apiStore.subscribe(subscriptionRequest); + + GenerateAppKeyRequest generateAppKeyRequest = + new GenerateAppKeyRequest("CommentRatingAPI-Application"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = + response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + //Here add API tags and check same have in response. + //Here check same tags are there + //Add some comment to API + //check comment is there + //Add rating + //check rating + Thread.sleep(2000); + for (int i = 0; i < 19; i++) { + + HttpResponse youTubeResponse = HttpRequestUtil + .doGet(getApiInvocationURLHttp("commentRating/1.0.0/most_popular"), + requestHeaders); + System.out.println( + "==================================================================================" + + i + "==========" + youTubeResponse.getResponseCode()); + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched"); + Assert.assertTrue(youTubeResponse.getData().contains(""), + "Response data mismatched"); + + } + //Do get,post,put,delete all here + //HttpResponse youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("commentRating/1.0.0/most_popular"), requestHeaders); + //Assert.assertEquals(youTubeResponse.getResponseCode(), 503, "Response code mismatched"); + Thread.sleep(60000); + HttpResponse youTubeResponse1 = HttpRequestUtil + .doGet(getApiInvocationURLHttp("commentRating/1.0.0/most_popular"), null); + Assert.assertEquals(youTubeResponse1.getResponseCode(), 401, "Response code mismatched"); + // URL url1 = new URL(url); + // HttpResponse youTubeResponse2 = HttpRequestUtil.doPost(url1,"-"); + //Remove subscription and then remove API + + apiStore.getAllPublishedAPIs(); + apiStore.getAllApplications(); + apiStore.getPublishedAPIsByApplication("CommentRatingAPI-Application"); + apiStore.isRatingActivated(); + apiStore.addRatingToAPI(APIName, APIVersion, providerName, "4"); + apiStore.removeRatingFromAPI(APIName, APIVersion, providerName); + apiStore.getAllDocumentationOfApi(APIName, APIVersion, providerName); + //apiStore.getAllPaginatedPublishedAPIs("carbon.super","0","10"); + //Negative cases + //add assert + apiStore.getPublishedAPIsByApplication("CommentRatingAPI-Application-Wrong"); + apiStore.isRatingActivated(); + apiStore.addRatingToAPI("NoAPI", APIVersion, providerName, "4"); + apiStore.removeRatingFromAPI("NoAPI", APIVersion, providerName); + apiStore.getAllDocumentationOfApi("NoAPI", APIVersion, providerName); + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + apiStore.removeApplication("CommentRatingAPI-Application"); + super.cleanup(); + } + +} diff --git a/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/ThrottlingTestCase.java b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/ThrottlingTestCase.java new file mode 100644 index 0000000000..041c6d8a41 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/ThrottlingTestCase.java @@ -0,0 +1,97 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.sample; + +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.admin.clients.registry.ResourceAdminServiceClient; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; +import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; +import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; +import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; +import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; + +import javax.activation.DataHandler; +import java.io.File; +import java.net.URL; + +public class ThrottlingTestCase extends APIManagerIntegrationTest { + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private ServerConfigurationManager serverConfigurationManager; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + /* + Before run this test we need to add throttling tiers xml file to registry and also we need to deploy API + to gateway Server. + Deploy API available in AM/synapseconfigs/throttling/throttling-api-synapse.xml + Add throttling definition available in configFiles/throttling/throttle-policy.xml to /_system/governance/apimgt/applicationdata/test-tiers.xml + */ + super.init(); + serverConfigurationManager = new ServerConfigurationManager(context); + super.init(); + loadESBConfigurationFromClasspath("artifacts" + File.separator + "AM" + + File.separator + "synapseconfigs" + File.separator + + "throttling" + + File.separator + "throttling-api-synapse.xml"); + //apiPublisher = new APIPublisherRestClient(getServerURLHttp()); + //apiStore = new APIStoreRestClient(getServerURLHttp()); + + } + + @Test(groups = { "wso2.am" }, description = "Token API Test sample") + public void throttlingTestCase() throws Exception { + //APIProviderHostObject test=new APIProviderHostObject("admin"); + //add client IP to tiers xml + ResourceAdminServiceClient resourceAdminServiceStub = + new ResourceAdminServiceClient(contextUrls.getBackEndUrl(), sessionCookie); + + //resourceAdminServiceStub.deleteResource("/_system/config/proxy"); + resourceAdminServiceStub.addCollection("/_system/config/", "proxy", "", + "Contains test proxy tests files"); + + Assert.assertTrue(resourceAdminServiceStub.addResource( + "/_system/governance/apimgt/applicationdata/test-tiers.xml", "application/xml", + "xml files", + setEndpoints(new DataHandler(new URL("file:///" + getAMResourceLocation() + + File.separator + "configFiles/throttling/" + + "throttle-policy.xml"))) + ) + , "Adding Resource failed"); + Thread.sleep(2000); + HttpResponse response = HttpRequestUtil + .sendGetRequest(getApiInvocationURLHttp("stockquote") + "/test/", null); + Assert.assertEquals(response.getResponseCode(), 200, "Response code mismatch"); + + HttpResponse errorResponse = + HttpRequestUtil.doGet(getApiInvocationURLHttp("stockquote") + "/test/", null); + Assert.assertEquals(errorResponse.getResponseCode(), 503, "Response code mismatch"); + //assert response + + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + super.cleanup(); + } +} diff --git a/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/TokenAPITestCase.java b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/TokenAPITestCase.java new file mode 100644 index 0000000000..c1efde8bb0 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/TokenAPITestCase.java @@ -0,0 +1,241 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.sample; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.am.integration.test.utils.bean.*; +import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; +import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; +import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; +import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; +import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; + +import java.io.File; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class TokenAPITestCase extends APIManagerIntegrationTest { + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private ServerConfigurationManager serverConfigurationManager; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(); + /* + If test run in external distributed deployment you need to copy following resources accordingly. + configFiles/hostobjecttest/api-manager.xml + configFiles/tokenTest/log4j.properties + To tests issue mentioned in https://wso2.org/jira/browse/APIMANAGER-2065 please run this test against + WSo2 Load balancer fronted 2 gateways 2 key manager setup with WSClient mode. Please refer resource api-manager.xml file. + */ + String publisherURLHttp; + String storeURLHttp; + if (isBuilderEnabled()) { + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + serverConfigurationManager = new ServerConfigurationManager(context); + serverConfigurationManager.applyConfigurationWithoutRestart(new File(getAMResourceLocation() + + File.separator + + "configFiles/tokenTest/" + + "api-manager.xml")); + serverConfigurationManager.applyConfiguration(new File(getAMResourceLocation() + + File.separator + + "configFiles/tokenTest/" + + "log4j.properties")); + super.init(); + } else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + apiPublisher = new APIPublisherRestClient(publisherURLHttp); + apiStore = new APIStoreRestClient(storeURLHttp); + + apiPublisher.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + apiStore.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + + } + + @Test(groups = { "wso2.am" }, description = "Token API Test sample") + public void testTokenAPITestCase() throws Exception { + String APIName = "TokenTestAPI"; + String APIContext = "tokenTestAPI"; + String tags = "youtube, token, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiRequest.setSandbox(url); + apiPublisher.addAPI(apiRequest); + APILifeCycleStateRequest updateRequest = + new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + + apiStore.addApplication("TokenTestAPI-Application", "Gold", "", "this-is-test"); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, + context.getContextTenant() + .getContextUser() + .getUserName() + ); + subscriptionRequest.setTier("Gold"); + subscriptionRequest.setApplicationName("TokenTestAPI-Application"); + apiStore.subscribe(subscriptionRequest); + + //Generate sandbox Token and invoke with that + GenerateAppKeyRequest generateAppKeyRequestSandBox = + new GenerateAppKeyRequest("TokenTestAPI-Application"); + generateAppKeyRequestSandBox.setKeyType("SANDBOX"); + String responseStringSandBox = + apiStore.generateApplicationKey(generateAppKeyRequestSandBox).getData(); + JSONObject responseSandBOX = new JSONObject(responseStringSandBox); + String SANDbOXAccessToken = + responseSandBOX.getJSONObject("data").getJSONObject("key").get("accessToken") + .toString(); + Map requestHeadersSandBox = new HashMap(); + requestHeadersSandBox.put("Authorization", "Bearer " + SANDbOXAccessToken); + HttpResponse youTubeResponseSandBox = HttpRequestUtil + .doGet(getApiInvocationURLHttp("tokenTestAPI/1.0.0/most_popular"), + requestHeadersSandBox); + // Assert.assertEquals(youTubeResponseSandBox.getResponseCode(), 200, "Response code mismatched"); + + //Generate production token and invoke with that + GenerateAppKeyRequest generateAppKeyRequest = + new GenerateAppKeyRequest("TokenTestAPI-Application"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + /*Response would be like - + {"validityTime":"360000","consumerKey":"Ow2cGYBf3xlAPpG3Q51W_3qnoega", + "accessToken":"qo3oNebQaF16C6qw1a56aZn2nwEa","enableRegenarate":true,"accessallowdomains":"ALL"," + consumerSecret":"ctHfsc1jFR7ovUgZ0oeHK8i9F9oa"}*/ + + String accessToken = + response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + String consumerKey = + response.getJSONObject("data").getJSONObject("key").getString("consumerKey"); + String consumerSecret = + response.getJSONObject("data").getJSONObject("key").getString("consumerSecret"); + //Obtain user access token + Thread.sleep(2000); + String requestBody = "grant_type=password&username=admin&password=admin&scope=PRODUCTION"; + URL tokenEndpointURL = new URL("https://localhost:8243/token"); + JSONObject accessTokenGenerationResponse = new JSONObject( + apiStore.generateUserAccessKey(consumerKey, consumerSecret, requestBody, + tokenEndpointURL).getData() + ); + /*Response would be like - + {"token_type":"bearer","expires_in":3600,"refresh_token":"736b6b5354e4cf24f217718b2f3f72b", + "access_token":"e06f12e3d6b1367d8471b093162f6729"} + */ + String userAccessToken = accessTokenGenerationResponse.getString("access_token"); + String refreshToken = accessTokenGenerationResponse.getString("refresh_token"); + Map requestHeaders = new HashMap(); + //Check User Access Token + requestHeaders.put("Authorization", "Bearer " + userAccessToken); + Thread.sleep(2000); + HttpResponse youTubeResponse = HttpRequestUtil + .doGet(getApiInvocationURLHttp("tokenTestAPI/1.0.0/most_popular"), requestHeaders); + //check JWT headers here + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched"); + Assert.assertTrue(youTubeResponse.getData().contains(""), + "Response data mismatched"); + + //Check Application Access Token + requestHeaders.clear(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + HttpResponse youTubeResponseWithApplicationToken = HttpRequestUtil + .doGet(getApiInvocationURLHttp("tokenTestAPI/1.0.0/most_popular"), requestHeaders); + Assert.assertEquals(youTubeResponseWithApplicationToken.getResponseCode(), 200, + "Response code mismatched"); + Assert.assertTrue(youTubeResponseWithApplicationToken.getData().contains(""), + "Response data mismatched"); + + //Invoke Https end point + HttpResponse youTubeResponseWithApplicationTokenHttps = HttpRequestUtil + .doGet(getApiInvocationURLHttps("tokenTestAPI/1.0.0/most_popular"), requestHeaders); + // Assert.assertEquals(youTubeResponseWithApplicationTokenHttps.getResponseCode(), 200, "Response code mismatched"); + + HttpResponse errorResponse = null; + for (int i = 0; i < 40; i++) { + errorResponse = HttpRequestUtil + .doGet(getApiInvocationURLHttps("tokenTestAPI/1.0.0/most_popular"), + requestHeaders); + errorResponse = HttpRequestUtil + .doGet(getApiInvocationURLHttp("tokenTestAPI/1.0.0/most_popular"), + requestHeaders); + } + Assert.assertEquals(errorResponse.getResponseCode(), 503, + "Response code mismatched while token API test case"); + Thread.sleep(60000); + errorResponse = HttpRequestUtil + .doGet(getApiInvocationURLHttp("tokenTestAPI/1.0.0/most_popular"), requestHeaders); + + apiPublisher.revokeAccessToken(accessToken, consumerKey, providerName); + requestHeaders.clear(); + requestHeaders.put("Authorization", "Bearer " + "this-is-incorrect-token"); + errorResponse = HttpRequestUtil + .doGet(getApiInvocationURLHttp("tokenTestAPI/1.0.0/most_popular"), requestHeaders); + Assert.assertEquals(errorResponse.getResponseCode(), 401, + "Response code mismatched while token API test case"); + //TODO handle this in automation core level + try { + StringBuilder soapRequest = new StringBuilder( + ""); + soapRequest + .append("Sam"); + soapRequest.append(""); + errorResponse = HttpRequestUtil + .doPost(new URL(getApiInvocationURLHttp("tokenTestAPI/1.0.0/most_popular")), + soapRequest.toString(), requestHeaders); + } catch (Exception e) { + //handle error + } + //Assert.assertEquals(errorResponse.getResponseCode(), 401, "Response code mismatched while token API test case"); + + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + apiStore.removeApplication("TokenTestAPI-Application"); + super.cleanup(); + serverConfigurationManager.restoreToLastConfiguration(); + } +} diff --git a/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/YouTubeAPITestCase.java b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/YouTubeAPITestCase.java new file mode 100644 index 0000000000..a98b73f8cd --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/java/org/wso2/carbon/am/tests/sample/YouTubeAPITestCase.java @@ -0,0 +1,113 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.sample; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.test.utils.APIManagerIntegrationTest; +import org.wso2.am.integration.test.utils.bean.*; +import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; +import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; +import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; +import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class YouTubeAPITestCase extends APIManagerIntegrationTest { + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(); + + String publisherURLHttp; + String storeURLHttp; + + if (isBuilderEnabled()) { + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + } else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + + apiPublisher = new APIPublisherRestClient(publisherURLHttp); + apiStore = new APIStoreRestClient(storeURLHttp); + + apiPublisher.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + apiStore.login(context.getContextTenant().getContextUser().getUserName(), + context.getContextTenant().getContextUser().getPassword()); + } + + @Test(groups = { "wso2.am" }, description = "You Tube sample") + public void testYouTubeApiSample() throws Exception { + APIRequest apiRequest = new APIRequest("YoutubeFeeds", "youtube", + new URL("http://gdata.youtube.com/feeds/api/standardfeeds")); + apiPublisher.addAPI(apiRequest); + APILifeCycleStateRequest updateRequest = + new APILifeCycleStateRequest("YoutubeFeeds", context + .getContextTenant().getContextUser().getUserName(), + APILifeCycleState.PUBLISHED + ); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + apiStore.addApplication("YoutubeFeeds-Application", "Gold", "", "this-is-test"); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest("YoutubeFeeds", + context.getContextTenant() + .getContextUser() + .getUserName() + ); + subscriptionRequest.setApplicationName("YoutubeFeeds-Application"); + apiStore.subscribe(subscriptionRequest); + + GenerateAppKeyRequest generateAppKeyRequest = + new GenerateAppKeyRequest("YoutubeFeeds-Application"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = + response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + + Thread.sleep(2000); + HttpResponse youTubeResponse = HttpRequestUtil.doGet( + getApiInvocationURLHttp("youtube/1.0.0/most_popular"), requestHeaders); + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, + "Response code mismatched when api invocation"); + Assert.assertTrue(youTubeResponse.getData().contains(""), + "Response data mismatched when api invocation"); + + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + apiStore.removeApplication("YoutubeFeeds-Application"); + super.cleanup(); + } +} diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/hostobjecttest/api-manager.xml b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/hostobjecttest/api-manager.xml new file mode 100755 index 0000000000..a7cbbc3a14 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/hostobjecttest/api-manager.xml @@ -0,0 +1,537 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + admin + + admin + + + + + + X-JWT-Assertion + + + org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever + + + http://wso2.org/claims + + + SHA256withRSA + + + true + + + true + + + + + + + + + + + + Production and Sandbox + + 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} + + + + + true + + + referer + + + + + true + + + + + + false + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + 7612 + + + tcp://localhost:7612/ + + + admin + + + admin + + + + + + + + false + + + UA-XXXXXXXX-X + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + + admin + + + admin + + true + + + + true + + + + WSClient + 10397 + 10000 + 10397 + + true + + + + + + + + /oauth2/token + + + false + + + + + + + true + + + + + + true + + + subscriber + + + true + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/store + + true + + true + + + true + + + true + + + + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/publisher + + + + + + + + + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + + + + + + + + + + true + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + /resource + http://localhost:9764/resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + Store1 + http://localhost:9763/store + user1@tenantdomain1.com + test123 + + + + + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + GET,POST,PUT,DELETE,OPTIONS + + + + diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/jaggery/test.jag b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/jaggery/test.jag new file mode 100644 index 0000000000..48d3201391 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/jaggery/test.jag @@ -0,0 +1,5 @@ +<% + application.put("wso2", "test artifacts.AM.configFiles.jaggery application value"); + print(application.get("wso2")); + application.remove("wso2"); +%> \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/throttling/throttle-policy.xml b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/throttling/throttle-policy.xml new file mode 100755 index 0000000000..aa5de6f71d --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/throttling/throttle-policy.xml @@ -0,0 +1,34 @@ + + + + 127.0.0.1 + + + + 1 + 60000 + + + + + + + other + + + + 2 + 60000 + + + + + + + 1000 + + other + + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/tokenTest/api-manager.xml b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/tokenTest/api-manager.xml new file mode 100755 index 0000000000..aea4c2fb38 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/tokenTest/api-manager.xml @@ -0,0 +1,556 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + admin + + admin + + + + + + X-JWT-Assertion + + + org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever + + + http://wso2.org/claims + + + SHA256withRSA + + + true + + + + + + + + + + + + + + + Production and Sandbox + + 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} + + + + + true + + + referer + + + + + true + + + + + + false + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + 7612 + + + tcp://localhost:7612/ + + + admin + + + admin + + + + + + + + false + + + UA-XXXXXXXX-X + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + + admin + + + admin + + true + + + + true + + + + WSClient + 10397 + 10000 + 10397 + + true + + + + + + + + /oauth2/token + + + false + + + + + + + true + + + + + + true + + + subscriber + + + true + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/store + + true + + true + + + true + + + true + + + + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/publisher + + + + + + + + + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + + + + + + + + + + true + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + /resource + http://localhost:9764/resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + + + + + + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + GET,POST,PUT,DELETE,OPTIONS + + + + diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/tokenTest/log4j.properties b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/tokenTest/log4j.properties new file mode 100755 index 0000000000..76c7eb5251 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/tokenTest/log4j.properties @@ -0,0 +1,180 @@ +# +# 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.category.org.apache.synapse=INFO +log4j.category.org.apache.synapse.transport=INFO +log4j.category.org.apache.axis2=INFO +log4j.category.org.apache.axis2.transport=INFO +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 +#log4j.logger.org.wso2.carbon.apimgt.gateway.handlers=DEBUG +#log4j.logger.org.wso2.carbon.apimgt.gateway.handlers.throttling=DEBUG +log4j.logger.org.wso2.carbon.apimgt=DEBUG + +# 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 + +# 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 + +# The console appender is used to display general information at console +log4j.appender.CARBON_CONSOLE=org.wso2.carbon.logging.appenders.CarbonConsoleAppender +log4j.appender.CARBON_CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CARBON_CONSOLE.layout.ConversionPattern=[%d{ISO8601}] %5p - %c{1} %m%n + +# 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-apigw-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-apigw-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.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.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-apigw-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.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 + +# LOGEVENT is set to be a LogEventAppender using a PatternLayout to send logs to LOGEVENT +log4j.appender.LOGEVENT=org.wso2.carbon.logging.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 + + +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 + +# LOGEVENT is set to be a LogEventAppender using a PatternLayout to send logs to LOGEVENT +log4j.appender.LOGEVENT=org.wso2.carbon.logging.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,%H,%I,%Stacktrace +log4j.appender.LOGEVENT.userName=admin +log4j.appender.LOGEVENT.password=admin + +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 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 + diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/usagemonitortest/api-manager.xml b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/usagemonitortest/api-manager.xml new file mode 100755 index 0000000000..406151fa75 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/usagemonitortest/api-manager.xml @@ -0,0 +1,537 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + admin + + admin + + + + + + X-JWT-Assertion + + + org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever + + + http://wso2.org/claims + + + SHA256withRSA + + + true + + + true + + + + + + + + + + + + Production and Sandbox + + 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} + + + + + true + + + referer + + + + + true + + + + + + true + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + 7612 + + + tcp://localhost:7612/ + + + admin + + + admin + + + + + + + + false + + + UA-XXXXXXXX-X + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + + admin + + + admin + + true + + + + true + + + + WSClient + 10397 + 10000 + 10397 + + true + + + + + + + + /oauth2/token + + + false + + + + + + + true + + + + + + true + + + subscriber + + + true + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/store + + true + + true + + + true + + + true + + + + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/publisher + + + + + + + + + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + + + + + + + + + + true + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + /resource + http://localhost:9764/resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + Store1 + http://localhost:9763/store + user1@tenantdomain1.com + test123 + + + + + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + GET,POST,PUT,DELETE,OPTIONS + + + + diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/usagemonitortest/master-datasources.xml b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/usagemonitortest/master-datasources.xml new file mode 100755 index 0000000000..8cc23ee0b4 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/configFiles/usagemonitortest/master-datasources.xml @@ -0,0 +1,109 @@ + + + + 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 + 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 + + + + + + WSO2AM_STATS_DB + The datasource used for getting statistics to API Manager + + jdbc/WSO2AM_STATS_DB + + + + jdbc:h2:;AUTO_SERVER=TRUE + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/jaggery/testPublisher.jag b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/jaggery/testPublisher.jag new file mode 100644 index 0000000000..3738f288e4 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/jaggery/testPublisher.jag @@ -0,0 +1,113 @@ +<% +//Order of these operations are important as we fetch results based on order. +//If you add new test add them to bottom of this file and update validate response method +//available in host object test class. +var publisher = require('apipublisher'); +var publisherHostObj = new publisher.APIProvider("admin"); +print("=="); +//print(publisherHostObj.getExternalAPIStores()); +//print("=="); +print(publisherHostObj.validateRoles('admin', 'admin')); +print("=="); +print(publisherHostObj.isURLValid("https","https://www.google.com")); +print("=="); +print(publisherHostObj.getAPIsByProvider("admin")); +print("=="); +print(publisherHostObj.getSubscribedAPIs("admin")); +print("=="); +print(publisherHostObj.getAPI("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.getTierPermissions()); +print("=="); +print(publisherHostObj.getTiers()); +print("=="); +print(publisherHostObj.getAllAPIs()); +print("=="); +print(publisherHostObj.getAPIsByProvider("admin")); +print("=="); +print(publisherHostObj.getSubscribersOfAPI("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.isContextExist("HostObjectTestAPI","HostObjectTestAPI")); +print("=="); +print(publisherHostObj.searchAPIs("admin","name:HostObjectTestAPI")); +print("=="); +print(publisherHostObj.hasCreatePermission()); +print("=="); +print(publisherHostObj.hasManageTierPermission()); +print("=="); +print(publisherHostObj.hasUserPermissions("admin")); +print("=="); +print(publisherHostObj.hasPublishPermission("admin")); +print("=="); +print(publisherHostObj.getAuthServerURL()); +print("=="); +print(publisherHostObj.getCustomInSequences()); +print("=="); +print(publisherHostObj.getCustomOutSequences()); +print("=="); +print(publisherHostObj.getHTTPsURL()); +print("=="); +print(publisherHostObj.isSynapseGateway()); +print("=="); +print(publisherHostObj.loadRegistryOfTenant("carbon.super")); +print("=="); +//print(publisherHostObj.updateDocumentation("admin","HostObjectTestAPI","1.0.0","Doc-Name", "How To", "summary","In-line","","","")); +//print("=="); +//print(publisherHostObj.addInlineContent("admin","HostObjectTestAPI","1.0.0","help","this is help")); +//print("=="); +print(publisherHostObj.getInlineContent("admin","HostObjectTestAPI","1.0.0","help")); +print("=="); +print(publisherHostObj.getAllDocumentation("admin@carbon.super","HostObjectTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.searchAccessTokens("*:*")); +print("=="); +print(publisherHostObj.getSubscriberCountByAPIs("admin@carbon.super")); +print("=="); +print(publisherHostObj.getSubscriberCountByAPIVersions("admin@carbon.super")); +print("=="); +//print(publisherHostObj.getExternalAPIStores()); +//print("=="); +var apiData = {}; +apiData["provider"] = "admin"; +apiData["name"] = "HostObjectTestAPI"; +apiData["version"] = "1.0.0"; +apiData["apiName"] = "HostObjectTestAPI"; +print(publisherHostObj.isAPIOlderVersionExist(apiData)); +print("=="); +print(publisherHostObj.updateSubscriptionStatus(apiData,"BLOCKED","1")); +print("=="); + +var tierData = {}; +tierData["tierName"] = "Gold"; +tierData["permissiontype"] = "Deny"; +tierData["roles"] = "admin"; +print(publisherHostObj.updateTierPermissions(tierData)); +print("=="); + +print(publisherHostObj.searchAPIs("admin","provider:admin")); +print("==") +print(publisherHostObj.searchAPIs("admin","context:HostObjectTestAPIAPIContext")); +print("==") +print(publisherHostObj.searchAPIs("admin","name:HOSTOBJECTTESTAPI")); +print("==") +print(publisherHostObj.searchAPIs("admin","name:hostobjecttestapi")); +print("==") +print(publisherHostObj.searchAPIs("admin","name:tobjecttesta")); +print("==") +print(publisherHostObj.searchAPIs("admin","provider:min")); +print("==") +print(publisherHostObj.searchAPIs("admin","context:APIContext")); +print("==") +print(publisherHostObj.searchAPIs("admin","context:invalid")); +print("==") +//print(publisherHostObj.updateExternalAPIStores(apiData)); +//print(publisherHostObj.createNewAPIVersion("admin","HostObjectTestAPI","1.0.0","1.0.1")); +//print(publisherHostObj.searchAccessTokens("admin")); +//print(publisherHostObj.getSubscriberCountByAPIVersions()); +var apiData1 = {}; +apiData1["provider"] = "admin"; +apiData1["name"] = "HostObjectTestAPI"; +apiData1["version"] = "1.0.0"; +apiData1["apiName"] = "HostObjectTestAPI"; +//print(publisherHostObj.updateExternalAPIStores(apiData1)); +%> \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/jaggery/testStore.jag b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/jaggery/testStore.jag new file mode 100644 index 0000000000..4dd29f1c3d --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/jaggery/testStore.jag @@ -0,0 +1,101 @@ +<% +<% +//Order of these operations are important as we fetch results based on order + //If you add new test add them to bottom of this file and update validate response method + //available in host object test class +store = require('apistore'); +var storeHostObj = new store.APIStore("admin"); +print("=="); +print(storeHostObj.isBillingEnabled()); +print("=="); +print(storeHostObj.getHTTPsURL("localhost")); +print("=="); +print(storeHostObj.getAuthServerURL()); +print("=="); +print(storeHostObj.getHTTPURL("localhost")); +print("=="); +print(storeHostObj.getDeniedTiers()); +print("=="); +print(storeHostObj.getActiveTenantDomains()); +print("=="); +print(storeHostObj.isSelfSignupEnabled()); +print("=="); +print(storeHostObj.getUserFields()); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("HostObjectTestAPI","carbon.super","0","10")); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("name:*","carbon.super","0","10")); +print("=="); +print(storeHostObj.searchAPIbyType("name:*","carbon.super")); +print("=="); +print(storeHostObj.searchAPIbyType("HostObjectTestAPI","carbon.super")); +print("=="); +print(storeHostObj.getPaginatedAPIsWithTag("youtube","0","10")); +print("=="); +print(storeHostObj.getPublishedAPIsByProvider("admin@carbon.super","admin","2")); +print("=="); +print(storeHostObj.getAllSubscriptions("admin@carbon.super")); +print("=="); +print(storeHostObj.rateAPI("admin","HostObjectTestAPI","1.0.0","3")); +print("=="); +print(storeHostObj.removeAPIRating("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(storeHostObj.getAllPaginatedPublishedAPIs("carbon.super","0","10")); +print("=="); +print(storeHostObj.getAPIsWithTag("youtube")); +print("=="); +print(storeHostObj.getAllPublishedAPIs("carbon.super")); +print("=="); +print(storeHostObj.getComments("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(storeHostObj.isUserExists("admin")); +print("=="); +print(storeHostObj.getAPI("admin","HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.isSubscribed("admin","HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.getSubscriptions("admin","HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.getSubscribedAPIs("3")); +print("=="); +print(storeHostObj.hasUserPermissions("admin")); +print("=="); +print(storeHostObj.getTiers("admin")); +print("=="); +print(storeHostObj.getAPIUsageforSubscriber("admin")); +print("=="); +print(storeHostObj.getDeniedTiers("admin")); +print("=="); +print(storeHostObj.getRecentlyAddedAPIs("5","carbon.super")); +print("=="); +print(storeHostObj.getTopRatedAPIs("5")); +print("=="); +print(storeHostObj.isBillingEnabled()); +print("=="); +print(storeHostObj.hasSubscribePermission()); +print("=="); +print(storeHostObj.isEnableEmailUsername()); +print("=="); +print(storeHostObj.updateApplicationTier("DefaultApplication","gold","admin")); +print("=="); +print(storeHostObj.updateApplication("DefaultApplicationTest","DefaultApplication","admin","gold","test-url","updated-application")); +print("=="); +print(storeHostObj.validateWFPermission("Basic YWRtaW46YWRtaW4=")); +print("=="); +print(storeHostObj.getSwaggerDiscoveryUrl("HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("context:*TestAPIdddAPIContext*","carbon.super","0","10")); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("version:1.0.0","carbon.super","0","10")); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("version:2.0.0","carbon.super","0","10")); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("context:*invalidcontext*","carbon.super","0","10")); +print("=="); +//print(storeHostObj.removeSubscriber("admin","HostObjectTestAPI","1.0.0","DefaultApplication","1")); +//print(storeHostObj.removeSubscription("admin","HostObjectTestAPI","1.0.0","DefaultApplication","1")); +//print(storeHostObj.rateAPI("admin","HostObjectTestAPI","1.0.0","3")); +//print("=="); +//print(storeHostObj.getTopRatedAPIs("3")); +%> +%> \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/jaggery/testUsageWithBAM.jag b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/jaggery/testUsageWithBAM.jag new file mode 100644 index 0000000000..e43384478b --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/jaggery/testUsageWithBAM.jag @@ -0,0 +1,36 @@ +<% +//Order of these operations are important as we fetch results based on order. +//If you add new test add them to bottom of this file and update validate response method +//available in host object test class. +var publisher = require('apipublisher'); +var publisherHostObj = new publisher.APIProvider("admin"); +print("=="); +print(publisherHostObj.getAPIUsageforSubscriber("admin")); +print("=="); +print(publisherHostObj.getAPIFaultyAnalyzeByTime("admin")); +print("=="); +var start=new Date(); +start.setFullYear(2014,0,14); +var end = new Date(); +end.setFullYear(2015,0,14); +print(publisherHostObj.getAPIResponseFaultCount("admin",start,end)); +print("=="); +print(publisherHostObj.getAPIUsageByResourcePath("admin",start,end)); +print("=="); +print(publisherHostObj.getAPIUsageByUser("admin",start,end)); +print("=="); +print(publisherHostObj.getAllAPIUsageByProvider("admin")); +print("=="); +print(publisherHostObj.getFirstAccessTime("admin")); +print("=="); +print(publisherHostObj.getProviderAPIServiceTime("admin",start,end)); +print("=="); +print(publisherHostObj.getProviderAPIUsage("admin","UsageTestAPI")); +print("=="); +print(publisherHostObj.getProviderAPIVersionUsage("admin","UsageTestAPI")); +print("=="); +print(publisherHostObj.getProviderAPIVersionUserUsage("admin","UsageTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.getProviderAPIVersionUserLastAccess("admin",start,end)); +print("=="); +%> \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/scripts/tenant_create.jmx b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/scripts/tenant_create.jmx new file mode 100644 index 0000000000..976581f9ad --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/scripts/tenant_create.jmx @@ -0,0 +1,634 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + GOOG_Stock_API_New + = + + + context + /GStocknew + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + userPrefix + user + = + + + resourceMethods + POST + = + + + authTypes + Application & Application User + = + + + throttlingTiers + Unlimited + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_number + # + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <ser:getTenant> + <!--Optional:--> + <ser:tenantDomain>tenantdomain${tenant_number}.com</ser:tenantDomain> + </ser:getTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:getTenant + true + false + + + + undefined + tenant_exists + //*[local-name()='active']/text() + false + false + true + tenant_exists + + + + false + true + true + false + + + + + ${tenant_exists}==false + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org" xmlns:xsd="http://beans.common.stratos.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <ser:addTenant> + <!--Optional:--> + <ser:tenantInfoBean> + <!--Optional:--> + <xsd:active>1</xsd:active> + <!--Optional:--> + <xsd:admin>${userPrefix}${tenant_number}</xsd:admin> + <!--Optional:--> + <xsd:adminPassword>test123</xsd:adminPassword> + <!--Optional:--> + <xsd:createdDate>2013-02-22T08:22:54</xsd:createdDate> + <!--Optional:--> + <xsd:email>ruwany@wso2.com</xsd:email> + <!--Optional:--> + <xsd:firstname>User1</xsd:firstname> + <!--Optional:--> + <xsd:lastname>LastName1</xsd:lastname> + <!--Optional:--> + <xsd:tenantDomain>tenantdomain${tenant_number}.com</xsd:tenantDomain> + <!--Optional:--> + <xsd:tenantId>0</xsd:tenantId> + <!--Optional:--> + <xsd:usagePlan>Demo</xsd:usagePlan> + </ser:tenantInfoBean> + </ser:addTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:addTenant + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + 202 + + Assertion.response_code + false + 1 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + + 1363957740000 + 1363957740000 + false + + + + + + + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_counter + # + false + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>${userPrefix}${tenant_counter}@tenantdomain${tenant_counter}.com</aut:username> + <!--Optional:--> + <aut:password>test123</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <xsd:getAllRolesNames> + <!--Optional:--> + <xsd:filter>*</xsd:filter> + <!--Optional:--> + <xsd:limit>100</xsd:limit> + </xsd:getAllRolesNames> + </soapenv:Body> +</soapenv:Envelope> + + urn:getAllRolesNames + true + false + + + + undefined + role_exists + //*[local-name()='itemName']/text()='subscriber_role_new' + false + false + true + + + + false + true + true + false + + + + + ${role_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addRole> + <!--Optional:--> + <mgt:roleName>subscriber_role_new</mgt:roleName> + <mgt:permissions>/permission/admin/login</mgt:permissions> + <mgt:permissions>/permission/admin/manage/api/subscribe</mgt:permissions> + <mgt:isSharedRole>false</mgt:isSharedRole> + </mgt:addRole> + </soapenv:Body> +</soapenv:Envelope> + + urn:addRole + true + false + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + user_ref + # + false + + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:listUsers> + <!--Optional:--> + <mgt:filter>${userPrefix}${tenant_counter}_user${user_ref}</mgt:filter> + <mgt:limit>10</mgt:limit> + </mgt:listUsers> + </soapenv:Body> +</soapenv:Envelope> + + urn:listUsers + true + false + + + + false + user_exists + //*[local-name()='return']/text()='${userPrefix}${tenant_counter}_user${user_ref}' + false + false + true + + + + false + true + true + false + + + + + ${user_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd" xmlns:xsd="http://common.mgt.user.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addUser> + <!--Optional:--> + <mgt:userName>${userPrefix}${tenant_counter}_user${user_ref}</mgt:userName> + <!--Optional:--> + <mgt:password>1qaz2wsx@</mgt:password> + <mgt:roles>subscriber_role_new</mgt:roles> + </mgt:addUser> + </soapenv:Body> +</soapenv:Envelope> + + urn:addUser + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy_report.jtl + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml new file mode 100644 index 0000000000..89b1b7b005 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml @@ -0,0 +1,223 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $1 + Status report + Runtime Error + $2 + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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. + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + The default main sequence for API manager - Returns 404 Not Found + + + + + + + + + + + + + + + + 30000 + fault + + + -1 + 0 + 1.0 + 0 + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/synapseconfigs/property/placeOrder.xml b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/synapseconfigs/property/placeOrder.xml new file mode 100644 index 0000000000..86da141b85 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/synapseconfigs/property/placeOrder.xml @@ -0,0 +1,7 @@ + + + 50 + 10 + IBM + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/synapseconfigs/rest/url-mapping-synapse.xml b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/synapseconfigs/rest/url-mapping-synapse.xml new file mode 100644 index 0000000000..a29656ba16 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/synapseconfigs/rest/url-mapping-synapse.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + +
    + + + + + + + 4.212070096051944 + -9.567415587431361 + -148.1740146577308 + IBM + + + + + + + + + + + + + diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/synapseconfigs/throttling/throttling-api-synapse.xml b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/synapseconfigs/throttling/throttling-api-synapse.xml new file mode 100644 index 0000000000..8e4f3c60b7 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/artifacts/AM/synapseconfigs/throttling/throttling-api-synapse.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + +
    + + + + + + + 4.212070096051944 + -9.567415587431361 + -148.1740146577308 + IBM + + + + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/automation.xml b/modules/integration/tests-integration/tests-scenario/src/test/resources/automation.xml new file mode 100644 index 0000000000..05c6f0214c --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/automation.xml @@ -0,0 +1,303 @@ + + + + + + + + 60000 + + standalone + + false + + false + + + + + + + http://10.100.2.51:4444/wd/hub/ + + + + firefox + + /home/test/name/webDriver + + + + + + + jdbc:h2:testDB + wso2carbon + wso2carbon + org.h2.Driver + + + jdbc:h2:testDB + wso2carbon + wso2carbon + org.h2.Driver + + + jdbc:mysql://localhost:3306/ + root + admin + com.mysql.jdbc.Driver + + + + + + + keystores/products/wso2carbon.jks + + JKS + + wso2carbon + + wso2carbon + + wso2carbon + + + + + keystores/products/client-truststore.jks + + JKS + + wso2carbon + + + + + + https://wso2.org/repo + file:///home/krishantha/test + + + + + + + + + + admin + admin + + + + + testuser11 + testuser11 + + + testuser21 + testuser21 + + + + + + + + + admin + admin + + + + + testuser11 + testuser11 + + + testuser21 + testuser21 + + + + + + + admin + admin + + + + + testuser11 + testuser11 + + + testuser21 + testuser21 + + + + + + + admin + admin + + + + + testuse11 + testuse11 + + + testuse21 + testuse21 + + + + + + + + + + + + + am.wso2con.com + mgt.am.wso2con.com + + + 8243 + 8280 + + + + + + + + localhost + + + 9764 + 9444 + 9446 + 8280 + + + + + + + + localhost + + + 9763 + 9443 + 8243 + 8280 + + + + + + + + localhost + + + 9765 + 9445 + 9446 + 8280 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/automationXMLSchema.xsd b/modules/integration/tests-integration/tests-scenario/src/test/resources/automationXMLSchema.xsd new file mode 100644 index 0000000000..c18b0826df --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/automationXMLSchema.xsd @@ -0,0 +1,573 @@ + + + + + + + ================================================= + Parameters ================================================= + Browser type with used by framework to execute UI test, supported types + - chrome|firefox|opera|ie|htmlUnit + + + + + + + Change this to edit wait time for test + artifact deployment + + + + + + Change this to product|platform/cloud to + execute test on specific environment + + + + + + + Change this to true if you want to generate + coverage statistics + + + + + + Change this to true if you want to enable + framework dashboard + + + + + + + + + + + + + + + Change to enable remote webDriver + URL of remote webDriver server + + + + + + + + + + + + + Type of the browser selenium tests + are running" + + + + + + + + path to webDriver + executable - required only for + chrome + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + KeyStore which will be used for + encrypting/decrypting passwords + and other sensitive information. + + + + + + + Keystore file location + + + + + + Keystore type (JKS/PKCS12 etc.) + + + + + + Keystore password + + + + + + Private Key alias + + + + + + Private Key password + + + + + + + + + + System wide trust-store which is used to + maintain the certificates of all + the trusted parties. + + + + + + + trust-store file location + + + + + + trust-store type (JKS/PKCS12 + etc.) + + + + + + trust-store password + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/axis2config/axis2_client.xml b/modules/integration/tests-integration/tests-scenario/src/test/resources/axis2config/axis2_client.xml new file mode 100644 index 0000000000..db07954a47 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/axis2config/axis2_client.xml @@ -0,0 +1,299 @@ + + + + + + + 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/integration/tests-integration/tests-scenario/src/test/resources/client/modules/addressing-1.6.1-wso2v11-20140804.232441-526.mar b/modules/integration/tests-integration/tests-scenario/src/test/resources/client/modules/addressing-1.6.1-wso2v11-20140804.232441-526.mar new file mode 100644 index 0000000000..a42c058499 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/src/test/resources/client/modules/addressing-1.6.1-wso2v11-20140804.232441-526.mar differ diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/client/modules/addressing-1.6.1-wso2v11-20140814.214646-548.mar b/modules/integration/tests-integration/tests-scenario/src/test/resources/client/modules/addressing-1.6.1-wso2v11-20140814.214646-548.mar new file mode 100644 index 0000000000..29dbdf2730 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/src/test/resources/client/modules/addressing-1.6.1-wso2v11-20140814.214646-548.mar differ diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/client/modules/addressing-1.6.1-wso2v9.mar b/modules/integration/tests-integration/tests-scenario/src/test/resources/client/modules/addressing-1.6.1-wso2v9.mar new file mode 100644 index 0000000000..d3871a1586 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/src/test/resources/client/modules/addressing-1.6.1-wso2v9.mar differ diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/emma.properties b/modules/integration/tests-integration/tests-scenario/src/test/resources/emma.properties new file mode 100644 index 0000000000..b39fffdb8e --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/emma.properties @@ -0,0 +1,103 @@ +# ------------------------------------------------------------- +# +# for user-editable property overrides use one of these options: +# +# (1) option-specific command line overrides, e.g. +# -Dreport.txt.out.file=coverage.txt +# +# (2) '-p ' command line option, +# +# (3) 'emma.properties' resource placed somewhere in the classpath +# (e.g., in \classes directory -- note that it does +# not exist by default), +# +# (4) '-Demma.*' JVM options, e.g. +# -Demma.report.txt.out.file=coverage.txt +# +# (5) 'emma.properties' JVM option pointing to a properties file +# -Demma.properties=./myproperties.txt +# ------------------------------------------------------------- + +# ------------------------------------------------------------- +# logging properties: + +verbosity.level: none + +# classloading properties: + +#clsload.forced_delegation_filter: +#clsload.through_delegation_filter: -* + +# ------------------------------------------------------------- + +# instrumentation properties: + +instr.exclude_empty_classes: true +instr.exclude_synthetic_methods: true +instr.exclude_bridge_methods: true +instr.do_suid_compensation: true + +# ------------------------------------------------------------- + +# runtime properties: + +rt.control: false +rt.control.host: localhost +rt.control.port: 44444 + +rt.filelock: true +rt.filelock.portbase: 59141 +rt.filelock.maxtime: 120000 +rt.filelock.retries: 11 + +# ------------------------------------------------------------- + +# apprunner session data output properties: + +session.out.file: coverage.es +session.out.merge: true + +# ------------------------------------------------------------- + +# runtime coverage data output properties: + +coverage.out.file: coverage.ec +coverage.out.merge: true + +# ------------------------------------------------------------- + +# instr metadata output properties: + +metadata.out.file: coverage.em +metadata.out.merge: true + +# ------------------------------------------------------------- + +# common report defaults: + +report.units: instr +report.depth: method +report.columns: name, line, block, method, class +report.sort: -line,-block,-method,-class,+name +report.metrics: method:40,block:80,line:40,class:100 + +# ------------------------------------------------------------- +# txt report properties: + +report.txt.depth: all +report.txt.columns: class,method,block,line,name +report.txt.out.file: coverage.txt + +# ------------------------------------------------------------- +# html report properties: + +#report.html.out.dir: coverage +report.html.out.encoding: ISO-8859-1 + +# ------------------------------------------------------------- +# xml report properties: + +report.xml.out.file: coverage.xml +report.xml.out.encoding: UTF-8 +# ------------------------------------------------------------- +# end of file diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/keystores/products/client-truststore.jks b/modules/integration/tests-integration/tests-scenario/src/test/resources/keystores/products/client-truststore.jks new file mode 100644 index 0000000000..9e3a51db3e Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/src/test/resources/keystores/products/client-truststore.jks differ diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/keystores/products/wso2carbon.jks b/modules/integration/tests-integration/tests-scenario/src/test/resources/keystores/products/wso2carbon.jks new file mode 100644 index 0000000000..7942c53cf9 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/src/test/resources/keystores/products/wso2carbon.jks differ diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/keystores/stratos/client-truststore.jks b/modules/integration/tests-integration/tests-scenario/src/test/resources/keystores/stratos/client-truststore.jks new file mode 100644 index 0000000000..9e3a51db3e Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/src/test/resources/keystores/stratos/client-truststore.jks differ diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/keystores/stratos/wso2carbon.jks b/modules/integration/tests-integration/tests-scenario/src/test/resources/keystores/stratos/wso2carbon.jks new file mode 100644 index 0000000000..7942c53cf9 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/src/test/resources/keystores/stratos/wso2carbon.jks differ diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/log4j.properties b/modules/integration/tests-integration/tests-scenario/src/test/resources/log4j.properties new file mode 100644 index 0000000000..693babfefe --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/log4j.properties @@ -0,0 +1,43 @@ +# +# Copyright 2009 WSO2, Inc. (http://wso2.com) +# +# 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 Carbon +# +# 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 Carbon Management Console, and those +# settings will override the settings in this file. +# + +log4j.rootLogger=INFO, console, Default + +log4j.logger.org.wso2=INFO + +#Automation file apender +log4j.appender.Default=org.apache.log4j.RollingFileAppender +log4j.appender.Default.File=logs/automation.log +log4j.appender.Default.Append=true +log4j.appender.Default.MaxFileSize=10MB +log4j.appender.Default.MaxBackupIndex=10 +log4j.appender.Default.layout=org.apache.log4j.PatternLayout +log4j.appender.Default.layout.ConversionPattern=%d{ISO8601} %-5p [%c] - %m%n + + +#Automation console apender +log4j.appender.console=org.apache.log4j.ConsoleAppender +log4j.appender.console.layout=org.apache.log4j.PatternLayout +log4j.appender.console.layout.ConversionPattern=%-5p [%c] - %m%n diff --git a/modules/integration/tests-integration/tests-scenario/src/test/resources/testng.xml b/modules/integration/tests-integration/tests-scenario/src/test/resources/testng.xml new file mode 100644 index 0000000000..6be6403867 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/src/test/resources/testng.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests-integration/tests-scenario/target/dependency-maven-plugin-markers/org.wso2.am-wso2am-zip-1.7.0-SNAPSHOT-213137672 b/modules/integration/tests-integration/tests-scenario/target/dependency-maven-plugin-markers/org.wso2.am-wso2am-zip-1.7.0-SNAPSHOT-213137672 new file mode 100644 index 0000000000..e69de29bb2 diff --git a/modules/integration/tests-integration/tests-scenario/target/logs/automation.log b/modules/integration/tests-integration/tests-scenario/target/logs/automation.log new file mode 100644 index 0000000000..3131e6bdf9 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/logs/automation.log @@ -0,0 +1,103 @@ +2015-01-26 14:52:42,363 INFO [org.wso2.carbon.automation.engine.testlisteners.TestExecutionListener] - Inside Test Execution Listener - On Execution +2015-01-26 14:52:42,442 INFO [org.wso2.carbon.automation.engine.testlisteners.TestTransformerListener] - Started Test method Transform manager for testApplication +2015-01-26 14:52:42,466 INFO [org.wso2.carbon.automation.engine.testlisteners.TestTransformerListener] - Started Configuration Transform manager init +2015-01-26 14:52:42,478 INFO [org.wso2.carbon.automation.engine.testlisteners.TestTransformerListener] - Started Configuration Transform manager destroy +2015-01-26 14:52:42,497 INFO [org.wso2.carbon.automation.engine.testlisteners.TestTransformerListener] - Started Test method Transform manager for testApplicationOperations +2015-01-26 14:52:42,508 INFO [org.wso2.carbon.automation.engine.testlisteners.TestTransformerListener] - Started Test method Transform manager for testAPIProvider +2015-01-26 14:52:42,519 INFO [org.wso2.carbon.automation.engine.testlisteners.TestTransformerListener] - Started Test method Transform manager for testHostObjectTestCase +2015-01-26 14:52:42,568 INFO [org.wso2.carbon.automation.engine.testlisteners.TestSuiteListener] - Inside Test Suite Listener - On Start +2015-01-26 14:52:42,838 INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: wso2caching-4.3.0-SNAPSHOT - file:/home/roshan/.m2/repository/org/wso2/carbon/org.wso2.carbon.caching.core/4.3.0-SNAPSHOT/org.wso2.carbon.caching.core-4.3.0-SNAPSHOT.jar +2015-01-26 14:52:42,848 INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: uddiversionmodule-4.2.0 - file:/home/roshan/.m2/repository/org/wso2/carbon/org.wso2.carbon.registry.uddi/4.2.0/org.wso2.carbon.registry.uddi-4.2.0.jar +2015-01-26 14:52:42,852 INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: pagination-4.2.0 - file:/home/roshan/.m2/repository/org/wso2/carbon/org.wso2.carbon.registry.server/4.2.0/org.wso2.carbon.registry.server-4.2.0.jar +2015-01-26 14:52:42,856 INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: ComponentMgtModule-4.2.0 - file:/home/roshan/.m2/repository/org/wso2/carbon/org.wso2.carbon.feature.mgt.services/4.2.0/org.wso2.carbon.feature.mgt.services-4.2.0.jar +2015-01-26 14:52:42,879 INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: rampart - file:/home/roshan/.m2/repository/org/apache/rampart/wso2/rampart-core/1.6.1.wso2v9/rampart-core-1.6.1.wso2v9.jar +2015-01-26 14:52:42,890 INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: rahas - file:/home/roshan/.m2/repository/org/apache/rampart/wso2/rampart-trust/1.6.1.wso2v9/rampart-trust-1.6.1.wso2v9.jar +2015-01-26 14:52:42,898 INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: POXSecurityModule-4.2.0 - file:/home/roshan/.m2/repository/org/wso2/carbon/org.wso2.carbon.security.mgt/4.2.0/org.wso2.carbon.security.mgt-4.2.0.jar +2015-01-26 14:52:42,932 INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: wso2throttle-4.2.0 - file:/home/roshan/.m2/repository/org/wso2/carbon/org.wso2.carbon.throttle.core/4.2.0/org.wso2.carbon.throttle.core-4.2.0.jar +2015-01-26 14:52:42,937 INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: metering-2.1.2 - file:/home/roshan/.m2/repository/org/wso2/carbon/org.wso2.carbon.usage.agent/2.1.2/org.wso2.carbon.usage.agent-2.1.2.jar +2015-01-26 14:52:42,943 INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: wso2statistics-4.1.0 - file:/home/roshan/.m2/repository/org/wso2/carbon/org.wso2.carbon.statistics/4.1.0/org.wso2.carbon.statistics-4.1.0.jar +2015-01-26 14:52:43,182 INFO [org.apache.commons.httpclient.HttpMethodDirector] - I/O exception (java.net.ConnectException) caught when processing request: Connection refused +2015-01-26 14:52:43,182 INFO [org.apache.commons.httpclient.HttpMethodDirector] - Retrying request +2015-01-26 14:52:43,183 INFO [org.apache.commons.httpclient.HttpMethodDirector] - I/O exception (java.net.ConnectException) caught when processing request: Connection refused +2015-01-26 14:52:43,183 INFO [org.apache.commons.httpclient.HttpMethodDirector] - Retrying request +2015-01-26 14:52:43,184 INFO [org.apache.commons.httpclient.HttpMethodDirector] - I/O exception (java.net.ConnectException) caught when processing request: Connection refused +2015-01-26 14:52:43,184 INFO [org.apache.commons.httpclient.HttpMethodDirector] - Retrying request +2015-01-26 14:52:43,185 INFO [org.apache.axis2.transport.http.HTTPSender] - Unable to sendViaPost to url[https://localhost:9443/services/AuthenticationAdmin] +java.net.ConnectException: Connection refused + at java.net.PlainSocketImpl.socketConnect(Native Method) + at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) + at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) + at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) + at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) + at java.net.Socket.connect(Socket.java:579) + at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:618) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:606) + at org.apache.commons.httpclient.protocol.ReflectionSocketFactory.createSocket(ReflectionSocketFactory.java:140) + at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:130) + at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707) + at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361) + at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387) + at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) + at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) + at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:630) + at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:195) + at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:77) + at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:451) + at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:278) + at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:442) + at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:430) + at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:225) + at org.apache.axis2.client.OperationClient.execute(OperationClient.java:149) + at org.wso2.carbon.authenticator.stub.AuthenticationAdminStub.login(AuthenticationAdminStub.java:659) + at org.wso2.carbon.integration.common.admin.client.AuthenticatorClient.login(AuthenticatorClient.java:59) + at org.wso2.carbon.integration.common.utils.LoginLogoutClient.login(LoginLogoutClient.java:68) + at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.login(APIManagerIntegrationTest.java:231) + at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.init(APIManagerIntegrationTest.java:85) + at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.init(APIManagerIntegrationTest.java:79) + at org.testlink.HOTestCase.init(HOTestCase.java:59) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:606) + at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84) + at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564) + at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213) + at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138) + at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:175) + at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:107) + at org.testng.TestRunner.privateRun(TestRunner.java:767) + at org.testng.TestRunner.run(TestRunner.java:617) + at org.testng.SuiteRunner.runTest(SuiteRunner.java:334) + at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329) + at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291) + at org.testng.SuiteRunner.run(SuiteRunner.java:240) + at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) + at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) + at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224) + at org.testng.TestNG.runSuitesLocally(TestNG.java:1149) + at org.testng.TestNG.run(TestNG.java:1057) + at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:178) + at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:92) + at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:96) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:606) + at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189) + at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165) + at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85) + at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115) + at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75) +2015-01-26 14:52:43,192 INFO [org.wso2.carbon.automation.engine.testlisteners.TestManagerListener] - Running the test method --- org.testlink.HOTestCase.testAPIProvider ---- +2015-01-26 14:52:43,192 INFO [org.wso2.carbon.automation.engine.testlisteners.TestManagerListener] - On test skipped... +2015-01-26 14:52:43,193 INFO [org.wso2.carbon.automation.engine.testlisteners.TestManagerListener] - Running the test method --- org.testlink.HOTestCase.testApplication ---- +2015-01-26 14:52:43,193 INFO [org.wso2.carbon.automation.engine.testlisteners.TestManagerListener] - On test skipped... +2015-01-26 14:52:43,193 INFO [org.wso2.carbon.automation.engine.testlisteners.TestManagerListener] - Running the test method --- org.testlink.HOTestCase.testApplicationOperations ---- +2015-01-26 14:52:43,193 INFO [org.wso2.carbon.automation.engine.testlisteners.TestManagerListener] - On test skipped... +2015-01-26 14:52:43,194 INFO [org.wso2.carbon.automation.engine.testlisteners.TestManagerListener] - Running the test method --- org.testlink.HOTestCase.testHostObjectTestCase ---- +2015-01-26 14:52:43,194 INFO [org.wso2.carbon.automation.engine.testlisteners.TestManagerListener] - On test skipped... +2015-01-26 14:52:43,222 INFO [org.wso2.carbon.automation.engine.testlisteners.TestSuiteListener] - Inside Test Suite Listener - On Finish +2015-01-26 14:52:43,223 INFO [org.wso2.carbon.automation.engine.testlisteners.TestExecutionListener] - Inside Test Execution Listener - On Finish diff --git a/modules/integration/tests-integration/tests-scenario/target/maven-archiver/pom.properties b/modules/integration/tests-integration/tests-scenario/target/maven-archiver/pom.properties new file mode 100644 index 0000000000..81a72ca7e8 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/maven-archiver/pom.properties @@ -0,0 +1,5 @@ +#Generated by Maven +#Mon Jan 26 14:52:43 IST 2015 +version=1.7.0-SNAPSHOT +groupId=org.wso2.am +artifactId=org.wso2.carbon.am.tests diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/AMTestSuite/AM-Sample-Test.html b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/AMTestSuite/AM-Sample-Test.html new file mode 100644 index 0000000000..9e485b535d --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/AMTestSuite/AM-Sample-Test.html @@ -0,0 +1,333 @@ + + +TestNG: AM-Sample-Test + + + + + + + + +

    AM-Sample-Test

    + + + + + + + + + + + +
    Tests passed/Failed/Skipped:0/0/4
    Started on:Mon Jan 26 14:52:42 IST 2015
    Total time:0 seconds (629 ms)
    Included groups:
    Excluded groups:

    +(Hover the method name to see the test class name)

    + + + + + + + + + + + + + + + + + +
    FAILED CONFIGURATIONS
    Test methodExceptionTime (seconds)Instance
    init
    Test class: org.testlink.HOTestCase
    org.apache.axis2.AxisFault: Connection refused
    +	at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)
    +	at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:199)
    +	at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:77)
    +	at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:451)
    +	at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:278)
    +	at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:442)
    +	at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:430)
    +	at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:225)
    +	at org.apache.axis2.client.OperationClient.execute(OperationClient.java:149)
    +	at org.wso2.carbon.authenticator.stub.AuthenticationAdminStub.login(AuthenticationAdminStub.java:659)
    +	at org.wso2.carbon.integration.common.admin.client.AuthenticatorClient.login(AuthenticatorClient.java:59)
    +	at org.wso2.carbon.integration.common.utils.LoginLogoutClient.login(LoginLogoutClient.java:68)
    +	at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.login(APIManagerIntegrationTest.java:231)
    +	at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.init(APIManagerIntegrationTest.java:85)
    +	at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.init(APIManagerIntegrationTest.java:79)
    +	at org.testlink.HOTestCase.init(HOTestCase.java:59)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    +	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    +	at java.lang.reflect.Method.invoke(Method.java:606)
    +	at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    +	at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564)
    +	at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213)
    +	at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138)
    +	at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:175)
    +	at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:107)
    +	at org.testng.TestRunner.privateRun(TestRunner.java:767)
    +	at org.testng.TestRunner.run(TestRunner.java:617)
    +	at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    +	at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    +	at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    +	at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    +	at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    +	at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    +	at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    +	at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    +	at org.testng.TestNG.run(TestNG.java:1057)
    +	at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:178)
    +	at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:92)
    +	at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:96)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    +	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    +	at java.lang.reflect.Method.invoke(Method.java:606)
    +	at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    +	at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    +	at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    +	at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    +	at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
    +Caused by: java.net.ConnectException: Connection refused
    +	at java.net.PlainSocketImpl.socketConnect(Native Method)
    +	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    +	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    +	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    +	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    +	at java.net.Socket.connect(Socket.java:579)
    +	at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:618)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    +	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    +	at java.lang.reflect.Method.invoke(Method.java:606)
    +	at org.apache.commons.httpclient.protocol.ReflectionSocketFactory.createSocket(ReflectionSocketFactory.java:140)
    +	at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:130)
    +	at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707)
    +	at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361)
    +	at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387)
    +	at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
    +	at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
    +	at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:630)
    +	at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:195)
    +	... 47 more
    +
    Click to show all stack frames +
    org.apache.axis2.AxisFault: Connection refused
    +	at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)
    +	at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:199)
    +	at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:77)
    +	at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:451)
    +	at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:278)
    +	at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:442)
    +	at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:430)
    +	at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:225)
    +	at org.apache.axis2.client.OperationClient.execute(OperationClient.java:149)
    +	at org.wso2.carbon.authenticator.stub.AuthenticationAdminStub.login(AuthenticationAdminStub.java:659)
    +	at org.wso2.carbon.integration.common.admin.client.AuthenticatorClient.login(AuthenticatorClient.java:59)
    +	at org.wso2.carbon.integration.common.utils.LoginLogoutClient.login(LoginLogoutClient.java:68)
    +	at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.login(APIManagerIntegrationTest.java:231)
    +	at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.init(APIManagerIntegrationTest.java:85)
    +	at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.init(APIManagerIntegrationTest.java:79)
    +	at org.testlink.HOTestCase.init(HOTestCase.java:59)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    +	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    +	at java.lang.reflect.Method.invoke(Method.java:606)
    +	at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    +	at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564)
    +	at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213)
    +	at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138)
    +	at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:175)
    +	at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:107)
    +	at org.testng.TestRunner.privateRun(TestRunner.java:767)
    +	at org.testng.TestRunner.run(TestRunner.java:617)
    +	at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    +	at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    +	at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    +	at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    +	at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    +	at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    +	at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    +	at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    +	at org.testng.TestNG.run(TestNG.java:1057)
    +	at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:178)
    +	at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:92)
    +	at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:96)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    +	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    +	at java.lang.reflect.Method.invoke(Method.java:606)
    +	at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    +	at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    +	at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    +	at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    +	at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
    +Caused by: java.net.ConnectException: Connection refused
    +	at java.net.PlainSocketImpl.socketConnect(Native Method)
    +	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    +	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    +	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    +	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    +	at java.net.Socket.connect(Socket.java:579)
    +	at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:618)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    +	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    +	at java.lang.reflect.Method.invoke(Method.java:606)
    +	at org.apache.commons.httpclient.protocol.ReflectionSocketFactory.createSocket(ReflectionSocketFactory.java:140)
    +	at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:130)
    +	at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707)
    +	at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361)
    +	at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387)
    +	at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
    +	at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
    +	at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:630)
    +	at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:195)
    +	... 47 more
    +
    0org.testlink.HOTestCase@420b90c1
    destroy
    Test class: org.testlink.HOTestCase
    java.lang.NullPointerException
    +	at org.testlink.HOTestCase.destroy(HOTestCase.java:253)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    +	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    +	at java.lang.reflect.Method.invoke(Method.java:606)
    +	at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    +	at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564)
    +	at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213)
    +	at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138)
    +	at org.testng.internal.TestMethodWorker.invokeAfterClassMethods(TestMethodWorker.java:225)
    +	at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:114)
    +	at org.testng.TestRunner.privateRun(TestRunner.java:767)
    +	at org.testng.TestRunner.run(TestRunner.java:617)
    +	at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    +	at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    +	at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    +	at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    +	at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    +	at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    +	at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    +	at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    +	at org.testng.TestNG.run(TestNG.java:1057)
    +	at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:178)
    +	at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:92)
    +	at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:96)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    +	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    +	at java.lang.reflect.Method.invoke(Method.java:606)
    +	at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    +	at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    +	at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    +	at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    +	at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
    +
    Click to show all stack frames +
    java.lang.NullPointerException
    +	at org.testlink.HOTestCase.destroy(HOTestCase.java:253)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    +	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    +	at java.lang.reflect.Method.invoke(Method.java:606)
    +	at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    +	at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564)
    +	at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213)
    +	at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138)
    +	at org.testng.internal.TestMethodWorker.invokeAfterClassMethods(TestMethodWorker.java:225)
    +	at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:114)
    +	at org.testng.TestRunner.privateRun(TestRunner.java:767)
    +	at org.testng.TestRunner.run(TestRunner.java:617)
    +	at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    +	at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    +	at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    +	at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    +	at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    +	at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    +	at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    +	at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    +	at org.testng.TestNG.run(TestNG.java:1057)
    +	at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:178)
    +	at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:92)
    +	at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:96)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    +	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    +	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    +	at java.lang.reflect.Method.invoke(Method.java:606)
    +	at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    +	at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    +	at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    +	at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    +	at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
    +
    0org.testlink.HOTestCase@420b90c1

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SKIPPED TESTS
    Test methodExceptionTime (seconds)Instance
    testAPIProvider
    Test class: org.testlink.HOTestCase
    Test method: Test application operations
    0org.testlink.HOTestCase@420b90c1
    testApplication
    Test class: org.testlink.HOTestCase
    Test method: Test application object
    0org.testlink.HOTestCase@420b90c1
    testApplicationOperations
    Test class: org.testlink.HOTestCase
    Test method: Test application operations
    0org.testlink.HOTestCase@420b90c1
    testHostObjectTestCase
    Test class: org.testlink.HOTestCase
    Test method: API Life cycle test case
    0org.testlink.HOTestCase@420b90c1

    + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/AMTestSuite/AM-Sample-Test.xml b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/AMTestSuite/AM-Sample-Test.xml new file mode 100644 index 0000000000..e6a75ea906 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/AMTestSuite/AM-Sample-Test.xml @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/AMTestSuite/testng-failed.xml b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/AMTestSuite/testng-failed.xml new file mode 100644 index 0000000000..800c5b2199 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/AMTestSuite/testng-failed.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/TEST-TestSuite.xml b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/TEST-TestSuite.xml new file mode 100644 index 0000000000..b1dd088051 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/TEST-TestSuite.xml @@ -0,0 +1,228 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.apache.axis2.AxisFault: Connection refused + at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430) + at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:199) + at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:77) + at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:451) + at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:278) + at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:442) + at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:430) + at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:225) + at org.apache.axis2.client.OperationClient.execute(OperationClient.java:149) + at org.wso2.carbon.authenticator.stub.AuthenticationAdminStub.login(AuthenticationAdminStub.java:659) + at org.wso2.carbon.integration.common.admin.client.AuthenticatorClient.login(AuthenticatorClient.java:59) + at org.wso2.carbon.integration.common.utils.LoginLogoutClient.login(LoginLogoutClient.java:68) + at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.login(APIManagerIntegrationTest.java:231) + at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.init(APIManagerIntegrationTest.java:85) + at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.init(APIManagerIntegrationTest.java:79) + at org.testlink.HOTestCase.init(HOTestCase.java:59) +Caused by: java.net.ConnectException: Connection refused + at java.net.PlainSocketImpl.socketConnect(Native Method) + at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) + at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) + at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) + at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) + at java.net.Socket.connect(Socket.java:579) + at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:618) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:606) + at org.apache.commons.httpclient.protocol.ReflectionSocketFactory.createSocket(ReflectionSocketFactory.java:140) + at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:130) + at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707) + at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361) + at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387) + at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) + at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) + at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:630) + at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:195) + ... 47 more + + INFO [org.wso2.carbon.automation.engine.testlisteners.TestExecutionListener] - Inside Test Execution Listener - On Execution +INFO [org.wso2.carbon.automation.engine.testlisteners.TestTransformerListener] - Started Test method Transform manager for testApplication +INFO [org.wso2.carbon.automation.engine.testlisteners.TestTransformerListener] - Started Configuration Transform manager init +INFO [org.wso2.carbon.automation.engine.testlisteners.TestTransformerListener] - Started Configuration Transform manager destroy +INFO [org.wso2.carbon.automation.engine.testlisteners.TestTransformerListener] - Started Test method Transform manager for testApplicationOperations +INFO [org.wso2.carbon.automation.engine.testlisteners.TestTransformerListener] - Started Test method Transform manager for testAPIProvider +INFO [org.wso2.carbon.automation.engine.testlisteners.TestTransformerListener] - Started Test method Transform manager for testHostObjectTestCase +INFO [org.wso2.carbon.automation.engine.testlisteners.TestSuiteListener] - Inside Test Suite Listener - On Start +INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: wso2caching-4.3.0-SNAPSHOT - file:/home/roshan/.m2/repository/org/wso2/carbon/org.wso2.carbon.caching.core/4.3.0-SNAPSHOT/org.wso2.carbon.caching.core-4.3.0-SNAPSHOT.jar +INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: uddiversionmodule-4.2.0 - file:/home/roshan/.m2/repository/org/wso2/carbon/org.wso2.carbon.registry.uddi/4.2.0/org.wso2.carbon.registry.uddi-4.2.0.jar +INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: pagination-4.2.0 - file:/home/roshan/.m2/repository/org/wso2/carbon/org.wso2.carbon.registry.server/4.2.0/org.wso2.carbon.registry.server-4.2.0.jar +INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: ComponentMgtModule-4.2.0 - file:/home/roshan/.m2/repository/org/wso2/carbon/org.wso2.carbon.feature.mgt.services/4.2.0/org.wso2.carbon.feature.mgt.services-4.2.0.jar +INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: rampart - file:/home/roshan/.m2/repository/org/apache/rampart/wso2/rampart-core/1.6.1.wso2v9/rampart-core-1.6.1.wso2v9.jar +INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: rahas - file:/home/roshan/.m2/repository/org/apache/rampart/wso2/rampart-trust/1.6.1.wso2v9/rampart-trust-1.6.1.wso2v9.jar +INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: POXSecurityModule-4.2.0 - file:/home/roshan/.m2/repository/org/wso2/carbon/org.wso2.carbon.security.mgt/4.2.0/org.wso2.carbon.security.mgt-4.2.0.jar +INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: wso2throttle-4.2.0 - file:/home/roshan/.m2/repository/org/wso2/carbon/org.wso2.carbon.throttle.core/4.2.0/org.wso2.carbon.throttle.core-4.2.0.jar +INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: metering-2.1.2 - file:/home/roshan/.m2/repository/org/wso2/carbon/org.wso2.carbon.usage.agent/2.1.2/org.wso2.carbon.usage.agent-2.1.2.jar +INFO [org.apache.axis2.deployment.ModuleDeployer] - Deploying module: wso2statistics-4.1.0 - file:/home/roshan/.m2/repository/org/wso2/carbon/org.wso2.carbon.statistics/4.1.0/org.wso2.carbon.statistics-4.1.0.jar +INFO [org.apache.commons.httpclient.HttpMethodDirector] - I/O exception (java.net.ConnectException) caught when processing request: Connection refused +INFO [org.apache.commons.httpclient.HttpMethodDirector] - Retrying request +INFO [org.apache.commons.httpclient.HttpMethodDirector] - I/O exception (java.net.ConnectException) caught when processing request: Connection refused +INFO [org.apache.commons.httpclient.HttpMethodDirector] - Retrying request +INFO [org.apache.commons.httpclient.HttpMethodDirector] - I/O exception (java.net.ConnectException) caught when processing request: Connection refused +INFO [org.apache.commons.httpclient.HttpMethodDirector] - Retrying request +INFO [org.apache.axis2.transport.http.HTTPSender] - Unable to sendViaPost to url[https://localhost:9443/services/AuthenticationAdmin] +java.net.ConnectException: Connection refused + at java.net.PlainSocketImpl.socketConnect(Native Method) + at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) + at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) + at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) + at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) + at java.net.Socket.connect(Socket.java:579) + at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:618) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:606) + at org.apache.commons.httpclient.protocol.ReflectionSocketFactory.createSocket(ReflectionSocketFactory.java:140) + at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:130) + at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707) + at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361) + at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387) + at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) + at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) + at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:630) + at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:195) + at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:77) + at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:451) + at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:278) + at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:442) + at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:430) + at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:225) + at org.apache.axis2.client.OperationClient.execute(OperationClient.java:149) + at org.wso2.carbon.authenticator.stub.AuthenticationAdminStub.login(AuthenticationAdminStub.java:659) + at org.wso2.carbon.integration.common.admin.client.AuthenticatorClient.login(AuthenticatorClient.java:59) + at org.wso2.carbon.integration.common.utils.LoginLogoutClient.login(LoginLogoutClient.java:68) + at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.login(APIManagerIntegrationTest.java:231) + at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.init(APIManagerIntegrationTest.java:85) + at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.init(APIManagerIntegrationTest.java:79) + at org.testlink.HOTestCase.init(HOTestCase.java:59) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:606) + at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84) + at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564) + at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213) + at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138) + at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:175) + at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:107) + at org.testng.TestRunner.privateRun(TestRunner.java:767) + at org.testng.TestRunner.run(TestRunner.java:617) + at org.testng.SuiteRunner.runTest(SuiteRunner.java:334) + at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329) + at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291) + at org.testng.SuiteRunner.run(SuiteRunner.java:240) + at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) + at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) + at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224) + at org.testng.TestNG.runSuitesLocally(TestNG.java:1149) + at org.testng.TestNG.run(TestNG.java:1057) + at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:178) + at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:92) + at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:96) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:606) + at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189) + at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165) + at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85) + at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115) + at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75) + + + + + INFO [org.wso2.carbon.automation.engine.testlisteners.TestManagerListener] - Running the test method --- org.testlink.HOTestCase.testAPIProvider ---- + + + + + INFO [org.wso2.carbon.automation.engine.testlisteners.TestManagerListener] - On test skipped... +INFO [org.wso2.carbon.automation.engine.testlisteners.TestManagerListener] - Running the test method --- org.testlink.HOTestCase.testApplication ---- + + + + + INFO [org.wso2.carbon.automation.engine.testlisteners.TestManagerListener] - On test skipped... +INFO [org.wso2.carbon.automation.engine.testlisteners.TestManagerListener] - Running the test method --- org.testlink.HOTestCase.testApplicationOperations ---- + + + + + INFO [org.wso2.carbon.automation.engine.testlisteners.TestManagerListener] - On test skipped... +INFO [org.wso2.carbon.automation.engine.testlisteners.TestManagerListener] - Running the test method --- org.testlink.HOTestCase.testHostObjectTestCase ---- + + + + java.lang.NullPointerException + at org.testlink.HOTestCase.destroy(HOTestCase.java:253) + + INFO [org.wso2.carbon.automation.engine.testlisteners.TestManagerListener] - On test skipped... + + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/TestSuite.txt b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/TestSuite.txt new file mode 100644 index 0000000000..8cd5361ddb --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/TestSuite.txt @@ -0,0 +1,49 @@ +------------------------------------------------------------------------------- +Test set: TestSuite +------------------------------------------------------------------------------- +Tests run: 6, Failures: 2, Errors: 0, Skipped: 4, Time elapsed: 1.357 sec <<< FAILURE! +init(org.testlink.HOTestCase) Time elapsed: 1.266 sec <<< FAILURE! +org.apache.axis2.AxisFault: Connection refused + at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430) + at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:199) + at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:77) + at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:451) + at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:278) + at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:442) + at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:430) + at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:225) + at org.apache.axis2.client.OperationClient.execute(OperationClient.java:149) + at org.wso2.carbon.authenticator.stub.AuthenticationAdminStub.login(AuthenticationAdminStub.java:659) + at org.wso2.carbon.integration.common.admin.client.AuthenticatorClient.login(AuthenticatorClient.java:59) + at org.wso2.carbon.integration.common.utils.LoginLogoutClient.login(LoginLogoutClient.java:68) + at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.login(APIManagerIntegrationTest.java:231) + at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.init(APIManagerIntegrationTest.java:85) + at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.init(APIManagerIntegrationTest.java:79) + at org.testlink.HOTestCase.init(HOTestCase.java:59) +Caused by: java.net.ConnectException: Connection refused + at java.net.PlainSocketImpl.socketConnect(Native Method) + at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) + at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) + at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) + at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) + at java.net.Socket.connect(Socket.java:579) + at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:618) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:606) + at org.apache.commons.httpclient.protocol.ReflectionSocketFactory.createSocket(ReflectionSocketFactory.java:140) + at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:130) + at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707) + at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361) + at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387) + at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) + at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) + at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:630) + at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:195) + ... 47 more + +destroy(org.testlink.HOTestCase) Time elapsed: 0.001 sec <<< FAILURE! +java.lang.NullPointerException + at org.testlink.HOTestCase.destroy(HOTestCase.java:253) + diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/bullet_point.png b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/bullet_point.png new file mode 100644 index 0000000000..176e6d5b3d Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/bullet_point.png differ diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/collapseall.gif b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/collapseall.gif new file mode 100644 index 0000000000..a2d80a9044 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/collapseall.gif differ diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/emailable-report.html b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/emailable-report.html new file mode 100644 index 0000000000..08151c0a2d --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/emailable-report.html @@ -0,0 +1,109 @@ + +TestNG Report
    Test# Passed# Skipped# FailedTime (ms)Included GroupsExcluded Groups
    AMTestSuite
    AM-Sample-Test040629
    ClassMethodStartTime (ms)
    AMTestSuite
    AM-Sample-Test — failed (configuration methods)
    org.testlink.HOTestCasedestroy14222641631940
    init14222641625740
    AM-Sample-Test — skipped
    org.testlink.HOTestCasetestAPIProvider14222641631911
    testApplication14222641631930
    testApplicationOperations14222641631930
    testHostObjectTestCase14222641631940

    AM-Sample-Test

    org.testlink.HOTestCase#destroy

    Exception
    java.lang.NullPointerException + at org.testlink.HOTestCase.destroy(HOTestCase.java:253) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:606) + at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84) + at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564) + at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213) + at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138) + at org.testng.internal.TestMethodWorker.invokeAfterClassMethods(TestMethodWorker.java:225) + at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:114) + at org.testng.TestRunner.privateRun(TestRunner.java:767) + at org.testng.TestRunner.run(TestRunner.java:617) + at org.testng.SuiteRunner.runTest(SuiteRunner.java:334) + at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329) + at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291) + at org.testng.SuiteRunner.run(SuiteRunner.java:240) + at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) + at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) + at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224) + at org.testng.TestNG.runSuitesLocally(TestNG.java:1149) + at org.testng.TestNG.run(TestNG.java:1057) + at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:178) + at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:92) + at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:96) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:606) + at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189) + at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165) + at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85) + at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115) + at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75) +

    back to summary

    org.testlink.HOTestCase#init

    Exception
    org.apache.axis2.AxisFault: Connection refused + at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430) + at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:199) + at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:77) + at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:451) + at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:278) + at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:442) + at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:430) + at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:225) + at org.apache.axis2.client.OperationClient.execute(OperationClient.java:149) + at org.wso2.carbon.authenticator.stub.AuthenticationAdminStub.login(AuthenticationAdminStub.java:659) + at org.wso2.carbon.integration.common.admin.client.AuthenticatorClient.login(AuthenticatorClient.java:59) + at org.wso2.carbon.integration.common.utils.LoginLogoutClient.login(LoginLogoutClient.java:68) + at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.login(APIManagerIntegrationTest.java:231) + at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.init(APIManagerIntegrationTest.java:85) + at org.wso2.am.integration.test.utils.APIManagerIntegrationTest.init(APIManagerIntegrationTest.java:79) + at org.testlink.HOTestCase.init(HOTestCase.java:59) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:606) + at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84) + at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564) + at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213) + at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138) + at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:175) + at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:107) + at org.testng.TestRunner.privateRun(TestRunner.java:767) + at org.testng.TestRunner.run(TestRunner.java:617) + at org.testng.SuiteRunner.runTest(SuiteRunner.java:334) + at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329) + at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291) + at org.testng.SuiteRunner.run(SuiteRunner.java:240) + at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) + at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) + at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224) + at org.testng.TestNG.runSuitesLocally(TestNG.java:1149) + at org.testng.TestNG.run(TestNG.java:1057) + at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:178) + at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:92) + at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:96) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:606) + at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189) + at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165) + at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85) + at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115) + at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75) +Caused by: java.net.ConnectException: Connection refused + at java.net.PlainSocketImpl.socketConnect(Native Method) + at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) + at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) + at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) + at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) + at java.net.Socket.connect(Socket.java:579) + at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:618) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:606) + at org.apache.commons.httpclient.protocol.ReflectionSocketFactory.createSocket(ReflectionSocketFactory.java:140) + at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:130) + at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707) + at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361) + at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387) + at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) + at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) + at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:630) + at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:195) + ... 47 more +

    back to summary

    org.testlink.HOTestCase#testAPIProvider

    back to summary

    org.testlink.HOTestCase#testApplication

    back to summary

    org.testlink.HOTestCase#testApplicationOperations

    back to summary

    org.testlink.HOTestCase#testHostObjectTestCase

    back to summary

    \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/failed.png b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/failed.png new file mode 100644 index 0000000000..c117be59a9 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/failed.png differ diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/index.html b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/index.html new file mode 100644 index 0000000000..57238cc95d --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/index.html @@ -0,0 +1,338 @@ + + + + + TestNG reports + + + + + + + + + + +
    + Test results +
    + 1 suite +
    + +
    +
    +
    +
    +
    + + org.testlink.HOTestCase +
    +
    +
    +
    + + + testAPIProvider + +(Test application operations) +
    +
    +
    +
    + + + testApplication + +(Test application object) +
    +
    +
    +
    + + + testApplicationOperations + +(Test application operations) +
    +
    +
    +
    + + + testHostObjectTestCase + +(API Life cycle test case) +
    +
    +
    +
    +
    +
    +
    + /home/roshan/workspace/GIT/product-apim/product-apim/modules/integration/tests-integration/tests-scenario/src/test/resources/testng.xml +
    +
    +
    +<?xml version="1.0" encoding="UTF-8"?>
    +<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
    +<suite verbose="0" name="AMTestSuite">
    +  <listeners>
    +    <listener class-name="org.wso2.carbon.automation.engine.testlisteners.TestManagerListener"/>
    +    <listener class-name="org.wso2.carbon.automation.engine.testlisteners.TestReportListener"/>
    +    <listener class-name="org.wso2.carbon.automation.engine.testlisteners.TestExecutionListener"/>
    +    <listener class-name="org.wso2.carbon.automation.engine.testlisteners.TestSuiteListener"/>
    +    <listener class-name="org.wso2.carbon.automation.engine.testlisteners.TestTransformerListener"/>
    +  </listeners>
    +  <test verbose="2" name="AM-Sample-Test">
    +    <classes>
    +      <class name="org.testlink.HOTestCase"/>
    +    </classes>
    +  </test> <!-- AM-Sample-Test -->
    +</suite> <!-- AMTestSuite -->
    +            
    +
    +
    +
    +
    + Tests for AMTestSuite +
    +
    +
      +
    • + AM-Sample-Test (1 class) +
    • +
    +
    +
    +
    +
    + Groups for AMTestSuite +
    +
    +
    + wso2.am +
    +
    + testAPIProvider +
    +
    +
    + testApplication +
    +
    +
    + testApplicationOperations +
    +
    +
    + testHostObjectTestCase +
    +
    +
    +
    +
    +
    +
    + Times for AMTestSuite +
    +
    +
    + + Total running time: 1 ms +
    +
    +
    +
    +
    +
    +
    + Reporter output for AMTestSuite +
    +
    +
    +
    +
    +
    + 0 ignored methods +
    +
    +
    +
    +
    +
    + Methods in chronological order +
    +
    +
    +
    org.testlink.HOTestCase
    +
    + + + init + 0 ms +
    +
    + testAPIProvider + 617 ms +
    +
    + testApplication + 619 ms +
    +
    + testApplicationOperations + 619 ms +
    +
    + testHostObjectTestCase + 620 ms +
    +
    + + + destroy + 620 ms +
    +
    +
    +
    +
    + + diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/jquery-1.7.1.min.js b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/jquery-1.7.1.min.js new file mode 100644 index 0000000000..198b3ff07d --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/jquery-1.7.1.min.js @@ -0,0 +1,4 @@ +/*! jQuery v1.7.1 jquery.com | jquery.org/license */ +(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"":"")+""),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g0){if(c!=="border")for(;g=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c
    a",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="
    "+""+"
    ",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="
    t
    ",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="
    ",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")}; +f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;le&&i.push({elem:this,matches:d.slice(e)});for(j=0;j0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return bc[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="

    ";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="
    ";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h0)for(h=g;h=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/",""],legend:[1,"
    ","
    "],thead:[1,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],col:[2,"","
    "],area:[1,"",""],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div
    ","
    "]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function() +{for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1>");try{for(var c=0,d=this.length;c1&&l0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]===""&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("
    ").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/junitreports/TEST-org.testlink.HOTestCase.xml b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/junitreports/TEST-org.testlink.HOTestCase.xml new file mode 100644 index 0000000000..45fbd4baf1 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/junitreports/TEST-org.testlink.HOTestCase.xml @@ -0,0 +1,164 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/navigator-bullet.png b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/navigator-bullet.png new file mode 100644 index 0000000000..36d90d395c Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/navigator-bullet.png differ diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/AM-Sample-Test.properties b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/AM-Sample-Test.properties new file mode 100644 index 0000000000..09c7e1e814 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/AM-Sample-Test.properties @@ -0,0 +1 @@ +[SuiteResult context=AM-Sample-Test] \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/classes.html b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/classes.html new file mode 100644 index 0000000000..f468cd12bf --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/classes.html @@ -0,0 +1,52 @@ +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Class nameMethod nameGroups
    org.testlink.HOTestCase  
    @Test
     testApplicationwso2.am
     testApplicationOperationswso2.am
     testHostObjectTestCasewso2.am
     testAPIProviderwso2.am
    @BeforeClass
     init 
    @BeforeMethod
    @AfterMethod
    @AfterClass
     destroy 
    diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/groups.html b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/groups.html new file mode 100644 index 0000000000..713edd69a4 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/groups.html @@ -0,0 +1,3 @@ +

    Groups used for this test run

    + +
    Group nameMethods
    wso2.amHOTestCase.testApplication()[pri:0, instance:org.testlink.HOTestCase@420b90c1]
    HOTestCase.testHostObjectTestCase()[pri:0, instance:org.testlink.HOTestCase@420b90c1]
    HOTestCase.testApplicationOperations()[pri:0, instance:org.testlink.HOTestCase@420b90c1]
    HOTestCase.testAPIProvider()[pri:0, instance:org.testlink.HOTestCase@420b90c1]
    diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/index.html b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/index.html new file mode 100644 index 0000000000..303e7ca8af --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/index.html @@ -0,0 +1,6 @@ +Results for AMTestSuite + + + + + diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/main.html b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/main.html new file mode 100644 index 0000000000..87ca3caaa4 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/main.html @@ -0,0 +1,2 @@ +Results for AMTestSuite +Select a result on the left-hand pane. diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/methods-alphabetical.html b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/methods-alphabetical.html new file mode 100644 index 0000000000..b65e349a7f --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/methods-alphabetical.html @@ -0,0 +1,16 @@ +

    Methods run, sorted chronologically

    >> means before, << means after


    AMTestSuite

    (Hover the method name to see the test class name)

    + + + + + + + + + + + + + + +
    TimeDelta (ms)Suite
    configuration
    Test
    configuration
    Class
    configuration
    Groups
    configuration
    Method
    configuration
    Test
    method
    ThreadInstances
    15/01/26 14:52:43 0   <<destroy    main@506941517
    15/01/26 14:52:42 -618   >>init    main@506941517
    15/01/26 14:52:43 -3      testAPIProvidermain@506941517
    15/01/26 14:52:43 -1      testApplicationmain@506941517
    15/01/26 14:52:43 -1      testApplicationOperationsmain@506941517
    15/01/26 14:52:43 0      testHostObjectTestCasemain@506941517
    diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/methods-not-run.html b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/methods-not-run.html new file mode 100644 index 0000000000..54b14cb854 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/methods-not-run.html @@ -0,0 +1,2 @@ +

    Methods that were not run

    +
    \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/methods.html b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/methods.html new file mode 100644 index 0000000000..4df7e7ad04 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/methods.html @@ -0,0 +1,16 @@ +

    Methods run, sorted chronologically

    >> means before, << means after


    AMTestSuite

    (Hover the method name to see the test class name)

    + + + + + + + + + + + + + + +
    TimeDelta (ms)Suite
    configuration
    Test
    configuration
    Class
    configuration
    Groups
    configuration
    Method
    configuration
    Test
    method
    ThreadInstances
    15/01/26 14:52:42 0   >>init    main@506941517
    15/01/26 14:52:43 615      testAPIProvidermain@506941517
    15/01/26 14:52:43 617      testApplicationmain@506941517
    15/01/26 14:52:43 617      testApplicationOperationsmain@506941517
    15/01/26 14:52:43 618      testHostObjectTestCasemain@506941517
    15/01/26 14:52:43 618   <<destroy    main@506941517
    diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/reporter-output.html b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/reporter-output.html new file mode 100644 index 0000000000..063bc2e96f --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/reporter-output.html @@ -0,0 +1 @@ +

    Reporter output

    \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/testng.xml.html b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/testng.xml.html new file mode 100644 index 0000000000..f4877d2093 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/testng.xml.html @@ -0,0 +1 @@ +testng.xml for AMTestSuite<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
    <suite verbose="0" name="AMTestSuite">
      <listeners>
        <listener class-name="org.wso2.carbon.automation.engine.testlisteners.TestManagerListener"/>
        <listener class-name="org.wso2.carbon.automation.engine.testlisteners.TestReportListener"/>
        <listener class-name="org.wso2.carbon.automation.engine.testlisteners.TestExecutionListener"/>
        <listener class-name="org.wso2.carbon.automation.engine.testlisteners.TestSuiteListener"/>
        <listener class-name="org.wso2.carbon.automation.engine.testlisteners.TestTransformerListener"/>
      </listeners>
      <test verbose="2" name="AM-Sample-Test">
        <classes>
          <class name="org.testlink.HOTestCase"/>
        </classes>
      </test> <!-- AM-Sample-Test -->
    </suite> <!-- AMTestSuite -->
    \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/toc.html b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/toc.html new file mode 100644 index 0000000000..704eb5b80c --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/AMTestSuite/toc.html @@ -0,0 +1,30 @@ + + +Results for AMTestSuite + + + + +

    Results for
    AMTestSuite

    + + + + + + + + + + +
    1 test1 class4 methods:
    +  chronological
    +  alphabetical
    +  not run (0)
    1 groupreporter outputtestng.xml
    + +

    +

    +
    AM-Sample-Test (0/0/4) + Results +
    +
    + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/index.html b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/index.html new file mode 100644 index 0000000000..c56d07760d --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/old/index.html @@ -0,0 +1,9 @@ + +Test results + + +

    Test results

    + + + +
    SuitePassedFailedSkippedtestng.xml
    Total004 
    AMTestSuite004Link
    diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/passed.png b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/passed.png new file mode 100644 index 0000000000..45e85bbfd0 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/passed.png differ diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/skipped.png b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/skipped.png new file mode 100644 index 0000000000..c36a324398 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/skipped.png differ diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/testng-failed.xml b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/testng-failed.xml new file mode 100644 index 0000000000..800c5b2199 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/testng-failed.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/testng-reports.css b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/testng-reports.css new file mode 100644 index 0000000000..29588e5572 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/testng-reports.css @@ -0,0 +1,309 @@ +body { + margin: 0px 0px 5px 5px; +} + +ul { + margin: 0px; +} + +li { + list-style-type: none; +} + +a { + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + +.navigator-selected { + background: #ffa500; +} + +.wrapper { + position: absolute; + top: 60px; + bottom: 0; + left: 400px; + right: 0; + overflow: auto; +} + +.navigator-root { + position: absolute; + top: 60px; + bottom: 0; + left: 0; + width: 400px; + overflow-y: auto; +} + +.suite { + margin: 0px 10px 10px 0px; + background-color: #fff8dc; +} + +.suite-name { + padding-left: 10px; + font-size: 25px; + font-family: Times; +} + +.main-panel-header { + padding: 5px; + background-color: #9FB4D9; //afeeee; + font-family: monospace; + font-size: 18px; +} + +.main-panel-content { + padding: 5px; + margin-bottom: 10px; + background-color: #DEE8FC; //d0ffff; +} + +.rounded-window { + border-radius: 10px; + border-style: solid; + border-width: 1px; +} + +.rounded-window-top { + border-top-right-radius: 10px 10px; + border-top-left-radius: 10px 10px; + border-style: solid; + border-width: 1px; + overflow: auto; +} + +.light-rounded-window-top { + border-top-right-radius: 10px 10px; + border-top-left-radius: 10px 10px; +} + +.rounded-window-bottom { + border-style: solid; + border-width: 0px 1px 1px 1px; + border-bottom-right-radius: 10px 10px; + border-bottom-left-radius: 10px 10px; + overflow: auto; +} + +.method-name { + font-size: 12px; + font-family: monospace; +} + +.method-content { + border-style: solid; + border-width: 0px 0px 1px 0px; + margin-bottom: 10; + padding-bottom: 5px; + width: 80%; +} + +.parameters { + font-size: 14px; + font-family: monospace; +} + +.stack-trace { + white-space: pre; + font-family: monospace; + font-size: 12px; + font-weight: bold; + margin-top: 0px; + margin-left: 20px; +} + +.testng-xml { + font-family: monospace; +} + +.method-list-content { + margin-left: 10px; +} + +.navigator-suite-content { + margin-left: 10px; + font: 12px 'Lucida Grande'; +} + +.suite-section-title { + margin-top: 10px; + width: 80%; + border-style: solid; + border-width: 1px 0px 0px 0px; + font-family: Times; + font-size: 18px; + font-weight: bold; +} + +.suite-section-content { + list-style-image: url(bullet_point.png); +} + +.top-banner-root { + position: absolute; + top: 0; + height: 45px; + left: 0; + right: 0; + padding: 5px; + margin: 0px 0px 5px 0px; + background-color: #0066ff; + font-family: Times; + color: #fff; + text-align: center; +} + +.top-banner-title-font { + font-size: 25px; +} + +.test-name { + font-family: 'Lucida Grande'; + font-size: 16px; +} + +.suite-icon { + padding: 5px; + float: right; + height: 20; +} + +.test-group { + font: 20px 'Lucida Grande'; + margin: 5px 5px 10px 5px; + border-width: 0px 0px 1px 0px; + border-style: solid; + padding: 5px; +} + +.test-group-name { + font-weight: bold; +} + +.method-in-group { + font-size: 16px; + margin-left: 80px; +} + +table.google-visualization-table-table { + width: 100%; +} + +.reporter-method-name { + font-size: 14px; + font-family: monospace; +} + +.reporter-method-output-div { + padding: 5px; + margin: 0px 0px 5px 20px; + font-size: 12px; + font-family: monospace; + border-width: 0px 0px 0px 1px; + border-style: solid; +} + +.ignored-class-div { + font-size: 14px; + font-family: monospace; +} + +.ignored-methods-div { + padding: 5px; + margin: 0px 0px 5px 20px; + font-size: 12px; + font-family: monospace; + border-width: 0px 0px 0px 1px; + border-style: solid; +} + +.border-failed { + border-top-left-radius: 10px 10px; + border-bottom-left-radius: 10px 10px; + border-style: solid; + border-width: 0px 0px 0px 10px; + border-color: #f00; +} + +.border-skipped { + border-top-left-radius: 10px 10px; + border-bottom-left-radius: 10px 10px; + border-style: solid; + border-width: 0px 0px 0px 10px; + border-color: #edc600; +} + +.border-passed { + border-top-left-radius: 10px 10px; + border-bottom-left-radius: 10px 10px; + border-style: solid; + border-width: 0px 0px 0px 10px; + border-color: #19f52d; +} + +.times-div { + text-align: center; + padding: 5px; +} + +.suite-total-time { + font: 16px 'Lucida Grande'; +} + +.configuration-suite { + margin-left: 20px; +} + +.configuration-test { + margin-left: 40px; +} + +.configuration-class { + margin-left: 60px; +} + +.configuration-method { + margin-left: 80px; +} + +.test-method { + margin-left: 100px; +} + +.chronological-class { + background-color: #0ccff; + border-style: solid; + border-width: 0px 0px 1px 1px; +} + +.method-start { + float: right; +} + +.chronological-class-name { + padding: 0px 0px 0px 5px; + color: #008; +} + +.after, .before, .test-method { + font-family: monospace; + font-size: 14px; +} + +.navigator-suite-header { + font-size: 22px; + margin: 0px 10px 5px 0px; + background-color: #deb887; + text-align: center; +} + +.collapse-all-icon { + padding: 5px; + float: right; +} diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/testng-reports.js b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/testng-reports.js new file mode 100644 index 0000000000..5159f81927 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/testng-reports.js @@ -0,0 +1,122 @@ +$(document).ready(function() { + $('a.navigator-link').click(function() { + // Extract the panel for this link + var panel = getPanelName($(this)); + + // Mark this link as currently selected + $('.navigator-link').parent().removeClass('navigator-selected'); + $(this).parent().addClass('navigator-selected'); + + showPanel(panel); + }); + + installMethodHandlers('failed'); + installMethodHandlers('skipped'); + installMethodHandlers('passed', true); // hide passed methods by default + + $('a.method').click(function() { + showMethod($(this)); + return false; + }); + + // Hide all the panels and display the first one (do this last + // to make sure the click() will invoke the listeners) + $('.panel').hide(); + $('.navigator-link').first().click(); + + // Collapse/expand the suites + $('a.collapse-all-link').click(function() { + var contents = $('.navigator-suite-content'); + if (contents.css('display') == 'none') { + contents.show(); + } else { + contents.hide(); + } + }); +}); + +// The handlers that take care of showing/hiding the methods +function installMethodHandlers(name, hide) { + function getContent(t) { + return $('.method-list-content.' + name + "." + t.attr('panel-name')); + } + + function getHideLink(t, name) { + var s = 'a.hide-methods.' + name + "." + t.attr('panel-name'); + return $(s); + } + + function getShowLink(t, name) { + return $('a.show-methods.' + name + "." + t.attr('panel-name')); + } + + function getMethodPanelClassSel(element, name) { + var panelName = getPanelName(element); + var sel = '.' + panelName + "-class-" + name; + return $(sel); + } + + $('a.hide-methods.' + name).click(function() { + var w = getContent($(this)); + w.hide(); + getHideLink($(this), name).hide(); + getShowLink($(this), name).show(); + getMethodPanelClassSel($(this), name).hide(); + }); + + $('a.show-methods.' + name).click(function() { + var w = getContent($(this)); + w.show(); + getHideLink($(this), name).show(); + getShowLink($(this), name).hide(); + showPanel(getPanelName($(this))); + getMethodPanelClassSel($(this), name).show(); + }); + + if (hide) { + $('a.hide-methods.' + name).click(); + } else { + $('a.show-methods.' + name).click(); + } +} + +function getHashForMethod(element) { + return element.attr('hash-for-method'); +} + +function getPanelName(element) { + return element.attr('panel-name'); +} + +function showPanel(panelName) { + $('.panel').hide(); + var panel = $('.panel[panel-name="' + panelName + '"]'); + panel.show(); +} + +function showMethod(element) { + var hashTag = getHashForMethod(element); + var panelName = getPanelName(element); + showPanel(panelName); + var current = document.location.href; + var base = current.substring(0, current.indexOf('#')) + document.location.href = base + '#' + hashTag; + var newPosition = $(document).scrollTop() - 65; + $(document).scrollTop(newPosition); +} + +function drawTable() { + for (var i = 0; i < suiteTableInitFunctions.length; i++) { + window[suiteTableInitFunctions[i]](); + } + + for (var k in window.suiteTableData) { + var v = window.suiteTableData[k]; + var div = v.tableDiv; + var data = v.tableData + var table = new google.visualization.Table(document.getElementById(div)); + table.draw(data, { + showRowNumber : false + }); + } +} diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/testng-results.xml b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/testng-results.xml new file mode 100644 index 0000000000..2906ea5d2a --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/testng-results.xml @@ -0,0 +1,163 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests-integration/tests-scenario/target/surefire-reports/testng.css b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/testng.css new file mode 100644 index 0000000000..3904800f0c --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/surefire-reports/testng.css @@ -0,0 +1,9 @@ +.invocation-failed, .test-failed { background-color: #DD0000; } +.invocation-percent, .test-percent { background-color: #006600; } +.invocation-passed, .test-passed { background-color: #00AA00; } +.invocation-skipped, .test-skipped { background-color: #CCCC00; } + +.main-page { + font-size: x-large; +} + diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/hostobjecttest/api-manager.xml b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/hostobjecttest/api-manager.xml new file mode 100644 index 0000000000..a7cbbc3a14 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/hostobjecttest/api-manager.xml @@ -0,0 +1,537 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + admin + + admin + + + + + + X-JWT-Assertion + + + org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever + + + http://wso2.org/claims + + + SHA256withRSA + + + true + + + true + + + + + + + + + + + + Production and Sandbox + + 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} + + + + + true + + + referer + + + + + true + + + + + + false + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + 7612 + + + tcp://localhost:7612/ + + + admin + + + admin + + + + + + + + false + + + UA-XXXXXXXX-X + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + + admin + + + admin + + true + + + + true + + + + WSClient + 10397 + 10000 + 10397 + + true + + + + + + + + /oauth2/token + + + false + + + + + + + true + + + + + + true + + + subscriber + + + true + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/store + + true + + true + + + true + + + true + + + + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/publisher + + + + + + + + + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + + + + + + + + + + true + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + /resource + http://localhost:9764/resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + Store1 + http://localhost:9763/store + user1@tenantdomain1.com + test123 + + + + + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + GET,POST,PUT,DELETE,OPTIONS + + + + diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/jaggery/test.jag b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/jaggery/test.jag new file mode 100644 index 0000000000..48d3201391 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/jaggery/test.jag @@ -0,0 +1,5 @@ +<% + application.put("wso2", "test artifacts.AM.configFiles.jaggery application value"); + print(application.get("wso2")); + application.remove("wso2"); +%> \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/throttling/throttle-policy.xml b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/throttling/throttle-policy.xml new file mode 100644 index 0000000000..aa5de6f71d --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/throttling/throttle-policy.xml @@ -0,0 +1,34 @@ + + + + 127.0.0.1 + + + + 1 + 60000 + + + + + + + other + + + + 2 + 60000 + + + + + + + 1000 + + other + + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/tokenTest/api-manager.xml b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/tokenTest/api-manager.xml new file mode 100644 index 0000000000..aea4c2fb38 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/tokenTest/api-manager.xml @@ -0,0 +1,556 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + admin + + admin + + + + + + X-JWT-Assertion + + + org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever + + + http://wso2.org/claims + + + SHA256withRSA + + + true + + + + + + + + + + + + + + + Production and Sandbox + + 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} + + + + + true + + + referer + + + + + true + + + + + + false + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + 7612 + + + tcp://localhost:7612/ + + + admin + + + admin + + + + + + + + false + + + UA-XXXXXXXX-X + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + + admin + + + admin + + true + + + + true + + + + WSClient + 10397 + 10000 + 10397 + + true + + + + + + + + /oauth2/token + + + false + + + + + + + true + + + + + + true + + + subscriber + + + true + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/store + + true + + true + + + true + + + true + + + + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/publisher + + + + + + + + + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + + + + + + + + + + true + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + /resource + http://localhost:9764/resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + + + + + + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + GET,POST,PUT,DELETE,OPTIONS + + + + diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/tokenTest/log4j.properties b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/tokenTest/log4j.properties new file mode 100644 index 0000000000..76c7eb5251 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/tokenTest/log4j.properties @@ -0,0 +1,180 @@ +# +# 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.category.org.apache.synapse=INFO +log4j.category.org.apache.synapse.transport=INFO +log4j.category.org.apache.axis2=INFO +log4j.category.org.apache.axis2.transport=INFO +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 +#log4j.logger.org.wso2.carbon.apimgt.gateway.handlers=DEBUG +#log4j.logger.org.wso2.carbon.apimgt.gateway.handlers.throttling=DEBUG +log4j.logger.org.wso2.carbon.apimgt=DEBUG + +# 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 + +# 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 + +# The console appender is used to display general information at console +log4j.appender.CARBON_CONSOLE=org.wso2.carbon.logging.appenders.CarbonConsoleAppender +log4j.appender.CARBON_CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CARBON_CONSOLE.layout.ConversionPattern=[%d{ISO8601}] %5p - %c{1} %m%n + +# 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-apigw-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-apigw-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.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.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-apigw-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.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 + +# LOGEVENT is set to be a LogEventAppender using a PatternLayout to send logs to LOGEVENT +log4j.appender.LOGEVENT=org.wso2.carbon.logging.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 + + +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 + +# LOGEVENT is set to be a LogEventAppender using a PatternLayout to send logs to LOGEVENT +log4j.appender.LOGEVENT=org.wso2.carbon.logging.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,%H,%I,%Stacktrace +log4j.appender.LOGEVENT.userName=admin +log4j.appender.LOGEVENT.password=admin + +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 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 + diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/usagemonitortest/api-manager.xml b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/usagemonitortest/api-manager.xml new file mode 100644 index 0000000000..406151fa75 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/usagemonitortest/api-manager.xml @@ -0,0 +1,537 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + admin + + admin + + + + + + X-JWT-Assertion + + + org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever + + + http://wso2.org/claims + + + SHA256withRSA + + + true + + + true + + + + + + + + + + + + Production and Sandbox + + 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} + + + + + true + + + referer + + + + + true + + + + + + true + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + 7612 + + + tcp://localhost:7612/ + + + admin + + + admin + + + + + + + + false + + + UA-XXXXXXXX-X + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + + admin + + + admin + + true + + + + true + + + + WSClient + 10397 + 10000 + 10397 + + true + + + + + + + + /oauth2/token + + + false + + + + + + + true + + + + + + true + + + subscriber + + + true + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/store + + true + + true + + + true + + + true + + + + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/publisher + + + + + + + + + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + + + + + + + + + + true + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + /resource + http://localhost:9764/resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + Store1 + http://localhost:9763/store + user1@tenantdomain1.com + test123 + + + + + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + GET,POST,PUT,DELETE,OPTIONS + + + + diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/usagemonitortest/master-datasources.xml b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/usagemonitortest/master-datasources.xml new file mode 100644 index 0000000000..8cc23ee0b4 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/configFiles/usagemonitortest/master-datasources.xml @@ -0,0 +1,109 @@ + + + + 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 + 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 + + + + + + WSO2AM_STATS_DB + The datasource used for getting statistics to API Manager + + jdbc/WSO2AM_STATS_DB + + + + jdbc:h2:;AUTO_SERVER=TRUE + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/jaggery/testPublisher.jag b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/jaggery/testPublisher.jag new file mode 100644 index 0000000000..3738f288e4 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/jaggery/testPublisher.jag @@ -0,0 +1,113 @@ +<% +//Order of these operations are important as we fetch results based on order. +//If you add new test add them to bottom of this file and update validate response method +//available in host object test class. +var publisher = require('apipublisher'); +var publisherHostObj = new publisher.APIProvider("admin"); +print("=="); +//print(publisherHostObj.getExternalAPIStores()); +//print("=="); +print(publisherHostObj.validateRoles('admin', 'admin')); +print("=="); +print(publisherHostObj.isURLValid("https","https://www.google.com")); +print("=="); +print(publisherHostObj.getAPIsByProvider("admin")); +print("=="); +print(publisherHostObj.getSubscribedAPIs("admin")); +print("=="); +print(publisherHostObj.getAPI("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.getTierPermissions()); +print("=="); +print(publisherHostObj.getTiers()); +print("=="); +print(publisherHostObj.getAllAPIs()); +print("=="); +print(publisherHostObj.getAPIsByProvider("admin")); +print("=="); +print(publisherHostObj.getSubscribersOfAPI("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.isContextExist("HostObjectTestAPI","HostObjectTestAPI")); +print("=="); +print(publisherHostObj.searchAPIs("admin","name:HostObjectTestAPI")); +print("=="); +print(publisherHostObj.hasCreatePermission()); +print("=="); +print(publisherHostObj.hasManageTierPermission()); +print("=="); +print(publisherHostObj.hasUserPermissions("admin")); +print("=="); +print(publisherHostObj.hasPublishPermission("admin")); +print("=="); +print(publisherHostObj.getAuthServerURL()); +print("=="); +print(publisherHostObj.getCustomInSequences()); +print("=="); +print(publisherHostObj.getCustomOutSequences()); +print("=="); +print(publisherHostObj.getHTTPsURL()); +print("=="); +print(publisherHostObj.isSynapseGateway()); +print("=="); +print(publisherHostObj.loadRegistryOfTenant("carbon.super")); +print("=="); +//print(publisherHostObj.updateDocumentation("admin","HostObjectTestAPI","1.0.0","Doc-Name", "How To", "summary","In-line","","","")); +//print("=="); +//print(publisherHostObj.addInlineContent("admin","HostObjectTestAPI","1.0.0","help","this is help")); +//print("=="); +print(publisherHostObj.getInlineContent("admin","HostObjectTestAPI","1.0.0","help")); +print("=="); +print(publisherHostObj.getAllDocumentation("admin@carbon.super","HostObjectTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.searchAccessTokens("*:*")); +print("=="); +print(publisherHostObj.getSubscriberCountByAPIs("admin@carbon.super")); +print("=="); +print(publisherHostObj.getSubscriberCountByAPIVersions("admin@carbon.super")); +print("=="); +//print(publisherHostObj.getExternalAPIStores()); +//print("=="); +var apiData = {}; +apiData["provider"] = "admin"; +apiData["name"] = "HostObjectTestAPI"; +apiData["version"] = "1.0.0"; +apiData["apiName"] = "HostObjectTestAPI"; +print(publisherHostObj.isAPIOlderVersionExist(apiData)); +print("=="); +print(publisherHostObj.updateSubscriptionStatus(apiData,"BLOCKED","1")); +print("=="); + +var tierData = {}; +tierData["tierName"] = "Gold"; +tierData["permissiontype"] = "Deny"; +tierData["roles"] = "admin"; +print(publisherHostObj.updateTierPermissions(tierData)); +print("=="); + +print(publisherHostObj.searchAPIs("admin","provider:admin")); +print("==") +print(publisherHostObj.searchAPIs("admin","context:HostObjectTestAPIAPIContext")); +print("==") +print(publisherHostObj.searchAPIs("admin","name:HOSTOBJECTTESTAPI")); +print("==") +print(publisherHostObj.searchAPIs("admin","name:hostobjecttestapi")); +print("==") +print(publisherHostObj.searchAPIs("admin","name:tobjecttesta")); +print("==") +print(publisherHostObj.searchAPIs("admin","provider:min")); +print("==") +print(publisherHostObj.searchAPIs("admin","context:APIContext")); +print("==") +print(publisherHostObj.searchAPIs("admin","context:invalid")); +print("==") +//print(publisherHostObj.updateExternalAPIStores(apiData)); +//print(publisherHostObj.createNewAPIVersion("admin","HostObjectTestAPI","1.0.0","1.0.1")); +//print(publisherHostObj.searchAccessTokens("admin")); +//print(publisherHostObj.getSubscriberCountByAPIVersions()); +var apiData1 = {}; +apiData1["provider"] = "admin"; +apiData1["name"] = "HostObjectTestAPI"; +apiData1["version"] = "1.0.0"; +apiData1["apiName"] = "HostObjectTestAPI"; +//print(publisherHostObj.updateExternalAPIStores(apiData1)); +%> \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/jaggery/testStore.jag b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/jaggery/testStore.jag new file mode 100644 index 0000000000..4dd29f1c3d --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/jaggery/testStore.jag @@ -0,0 +1,101 @@ +<% +<% +//Order of these operations are important as we fetch results based on order + //If you add new test add them to bottom of this file and update validate response method + //available in host object test class +store = require('apistore'); +var storeHostObj = new store.APIStore("admin"); +print("=="); +print(storeHostObj.isBillingEnabled()); +print("=="); +print(storeHostObj.getHTTPsURL("localhost")); +print("=="); +print(storeHostObj.getAuthServerURL()); +print("=="); +print(storeHostObj.getHTTPURL("localhost")); +print("=="); +print(storeHostObj.getDeniedTiers()); +print("=="); +print(storeHostObj.getActiveTenantDomains()); +print("=="); +print(storeHostObj.isSelfSignupEnabled()); +print("=="); +print(storeHostObj.getUserFields()); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("HostObjectTestAPI","carbon.super","0","10")); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("name:*","carbon.super","0","10")); +print("=="); +print(storeHostObj.searchAPIbyType("name:*","carbon.super")); +print("=="); +print(storeHostObj.searchAPIbyType("HostObjectTestAPI","carbon.super")); +print("=="); +print(storeHostObj.getPaginatedAPIsWithTag("youtube","0","10")); +print("=="); +print(storeHostObj.getPublishedAPIsByProvider("admin@carbon.super","admin","2")); +print("=="); +print(storeHostObj.getAllSubscriptions("admin@carbon.super")); +print("=="); +print(storeHostObj.rateAPI("admin","HostObjectTestAPI","1.0.0","3")); +print("=="); +print(storeHostObj.removeAPIRating("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(storeHostObj.getAllPaginatedPublishedAPIs("carbon.super","0","10")); +print("=="); +print(storeHostObj.getAPIsWithTag("youtube")); +print("=="); +print(storeHostObj.getAllPublishedAPIs("carbon.super")); +print("=="); +print(storeHostObj.getComments("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(storeHostObj.isUserExists("admin")); +print("=="); +print(storeHostObj.getAPI("admin","HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.isSubscribed("admin","HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.getSubscriptions("admin","HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.getSubscribedAPIs("3")); +print("=="); +print(storeHostObj.hasUserPermissions("admin")); +print("=="); +print(storeHostObj.getTiers("admin")); +print("=="); +print(storeHostObj.getAPIUsageforSubscriber("admin")); +print("=="); +print(storeHostObj.getDeniedTiers("admin")); +print("=="); +print(storeHostObj.getRecentlyAddedAPIs("5","carbon.super")); +print("=="); +print(storeHostObj.getTopRatedAPIs("5")); +print("=="); +print(storeHostObj.isBillingEnabled()); +print("=="); +print(storeHostObj.hasSubscribePermission()); +print("=="); +print(storeHostObj.isEnableEmailUsername()); +print("=="); +print(storeHostObj.updateApplicationTier("DefaultApplication","gold","admin")); +print("=="); +print(storeHostObj.updateApplication("DefaultApplicationTest","DefaultApplication","admin","gold","test-url","updated-application")); +print("=="); +print(storeHostObj.validateWFPermission("Basic YWRtaW46YWRtaW4=")); +print("=="); +print(storeHostObj.getSwaggerDiscoveryUrl("HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("context:*TestAPIdddAPIContext*","carbon.super","0","10")); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("version:1.0.0","carbon.super","0","10")); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("version:2.0.0","carbon.super","0","10")); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("context:*invalidcontext*","carbon.super","0","10")); +print("=="); +//print(storeHostObj.removeSubscriber("admin","HostObjectTestAPI","1.0.0","DefaultApplication","1")); +//print(storeHostObj.removeSubscription("admin","HostObjectTestAPI","1.0.0","DefaultApplication","1")); +//print(storeHostObj.rateAPI("admin","HostObjectTestAPI","1.0.0","3")); +//print("=="); +//print(storeHostObj.getTopRatedAPIs("3")); +%> +%> \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/jaggery/testUsageWithBAM.jag b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/jaggery/testUsageWithBAM.jag new file mode 100644 index 0000000000..e43384478b --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/jaggery/testUsageWithBAM.jag @@ -0,0 +1,36 @@ +<% +//Order of these operations are important as we fetch results based on order. +//If you add new test add them to bottom of this file and update validate response method +//available in host object test class. +var publisher = require('apipublisher'); +var publisherHostObj = new publisher.APIProvider("admin"); +print("=="); +print(publisherHostObj.getAPIUsageforSubscriber("admin")); +print("=="); +print(publisherHostObj.getAPIFaultyAnalyzeByTime("admin")); +print("=="); +var start=new Date(); +start.setFullYear(2014,0,14); +var end = new Date(); +end.setFullYear(2015,0,14); +print(publisherHostObj.getAPIResponseFaultCount("admin",start,end)); +print("=="); +print(publisherHostObj.getAPIUsageByResourcePath("admin",start,end)); +print("=="); +print(publisherHostObj.getAPIUsageByUser("admin",start,end)); +print("=="); +print(publisherHostObj.getAllAPIUsageByProvider("admin")); +print("=="); +print(publisherHostObj.getFirstAccessTime("admin")); +print("=="); +print(publisherHostObj.getProviderAPIServiceTime("admin",start,end)); +print("=="); +print(publisherHostObj.getProviderAPIUsage("admin","UsageTestAPI")); +print("=="); +print(publisherHostObj.getProviderAPIVersionUsage("admin","UsageTestAPI")); +print("=="); +print(publisherHostObj.getProviderAPIVersionUserUsage("admin","UsageTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.getProviderAPIVersionUserLastAccess("admin",start,end)); +print("=="); +%> \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/scripts/tenant_create.jmx b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/scripts/tenant_create.jmx new file mode 100644 index 0000000000..976581f9ad --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/scripts/tenant_create.jmx @@ -0,0 +1,634 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + GOOG_Stock_API_New + = + + + context + /GStocknew + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + userPrefix + user + = + + + resourceMethods + POST + = + + + authTypes + Application & Application User + = + + + throttlingTiers + Unlimited + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_number + # + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <ser:getTenant> + <!--Optional:--> + <ser:tenantDomain>tenantdomain${tenant_number}.com</ser:tenantDomain> + </ser:getTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:getTenant + true + false + + + + undefined + tenant_exists + //*[local-name()='active']/text() + false + false + true + tenant_exists + + + + false + true + true + false + + + + + ${tenant_exists}==false + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org" xmlns:xsd="http://beans.common.stratos.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <ser:addTenant> + <!--Optional:--> + <ser:tenantInfoBean> + <!--Optional:--> + <xsd:active>1</xsd:active> + <!--Optional:--> + <xsd:admin>${userPrefix}${tenant_number}</xsd:admin> + <!--Optional:--> + <xsd:adminPassword>test123</xsd:adminPassword> + <!--Optional:--> + <xsd:createdDate>2013-02-22T08:22:54</xsd:createdDate> + <!--Optional:--> + <xsd:email>ruwany@wso2.com</xsd:email> + <!--Optional:--> + <xsd:firstname>User1</xsd:firstname> + <!--Optional:--> + <xsd:lastname>LastName1</xsd:lastname> + <!--Optional:--> + <xsd:tenantDomain>tenantdomain${tenant_number}.com</xsd:tenantDomain> + <!--Optional:--> + <xsd:tenantId>0</xsd:tenantId> + <!--Optional:--> + <xsd:usagePlan>Demo</xsd:usagePlan> + </ser:tenantInfoBean> + </ser:addTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:addTenant + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + 202 + + Assertion.response_code + false + 1 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + + 1363957740000 + 1363957740000 + false + + + + + + + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_counter + # + false + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>${userPrefix}${tenant_counter}@tenantdomain${tenant_counter}.com</aut:username> + <!--Optional:--> + <aut:password>test123</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <xsd:getAllRolesNames> + <!--Optional:--> + <xsd:filter>*</xsd:filter> + <!--Optional:--> + <xsd:limit>100</xsd:limit> + </xsd:getAllRolesNames> + </soapenv:Body> +</soapenv:Envelope> + + urn:getAllRolesNames + true + false + + + + undefined + role_exists + //*[local-name()='itemName']/text()='subscriber_role_new' + false + false + true + + + + false + true + true + false + + + + + ${role_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addRole> + <!--Optional:--> + <mgt:roleName>subscriber_role_new</mgt:roleName> + <mgt:permissions>/permission/admin/login</mgt:permissions> + <mgt:permissions>/permission/admin/manage/api/subscribe</mgt:permissions> + <mgt:isSharedRole>false</mgt:isSharedRole> + </mgt:addRole> + </soapenv:Body> +</soapenv:Envelope> + + urn:addRole + true + false + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + user_ref + # + false + + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:listUsers> + <!--Optional:--> + <mgt:filter>${userPrefix}${tenant_counter}_user${user_ref}</mgt:filter> + <mgt:limit>10</mgt:limit> + </mgt:listUsers> + </soapenv:Body> +</soapenv:Envelope> + + urn:listUsers + true + false + + + + false + user_exists + //*[local-name()='return']/text()='${userPrefix}${tenant_counter}_user${user_ref}' + false + false + true + + + + false + true + true + false + + + + + ${user_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd" xmlns:xsd="http://common.mgt.user.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addUser> + <!--Optional:--> + <mgt:userName>${userPrefix}${tenant_counter}_user${user_ref}</mgt:userName> + <!--Optional:--> + <mgt:password>1qaz2wsx@</mgt:password> + <mgt:roles>subscriber_role_new</mgt:roles> + </mgt:addUser> + </soapenv:Body> +</soapenv:Envelope> + + urn:addUser + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy_report.jtl + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml new file mode 100644 index 0000000000..89b1b7b005 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml @@ -0,0 +1,223 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $1 + Status report + Runtime Error + $2 + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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. + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + The default main sequence for API manager - Returns 404 Not Found + + + + + + + + + + + + + + + + 30000 + fault + + + -1 + 0 + 1.0 + 0 + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/synapseconfigs/property/placeOrder.xml b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/synapseconfigs/property/placeOrder.xml new file mode 100644 index 0000000000..86da141b85 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/synapseconfigs/property/placeOrder.xml @@ -0,0 +1,7 @@ + + + 50 + 10 + IBM + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/synapseconfigs/rest/url-mapping-synapse.xml b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/synapseconfigs/rest/url-mapping-synapse.xml new file mode 100644 index 0000000000..a29656ba16 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/synapseconfigs/rest/url-mapping-synapse.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + +
    + + + + + + + 4.212070096051944 + -9.567415587431361 + -148.1740146577308 + IBM + + + + + + + + + + + + + diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/synapseconfigs/throttling/throttling-api-synapse.xml b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/synapseconfigs/throttling/throttling-api-synapse.xml new file mode 100644 index 0000000000..8e4f3c60b7 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/artifacts/AM/synapseconfigs/throttling/throttling-api-synapse.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + +
    + + + + + + + 4.212070096051944 + -9.567415587431361 + -148.1740146577308 + IBM + + + + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/automation.xml b/modules/integration/tests-integration/tests-scenario/target/test-classes/automation.xml new file mode 100644 index 0000000000..05c6f0214c --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/automation.xml @@ -0,0 +1,303 @@ + + + + + + + + 60000 + + standalone + + false + + false + + + + + + + http://10.100.2.51:4444/wd/hub/ + + + + firefox + + /home/test/name/webDriver + + + + + + + jdbc:h2:testDB + wso2carbon + wso2carbon + org.h2.Driver + + + jdbc:h2:testDB + wso2carbon + wso2carbon + org.h2.Driver + + + jdbc:mysql://localhost:3306/ + root + admin + com.mysql.jdbc.Driver + + + + + + + keystores/products/wso2carbon.jks + + JKS + + wso2carbon + + wso2carbon + + wso2carbon + + + + + keystores/products/client-truststore.jks + + JKS + + wso2carbon + + + + + + https://wso2.org/repo + file:///home/krishantha/test + + + + + + + + + + admin + admin + + + + + testuser11 + testuser11 + + + testuser21 + testuser21 + + + + + + + + + admin + admin + + + + + testuser11 + testuser11 + + + testuser21 + testuser21 + + + + + + + admin + admin + + + + + testuser11 + testuser11 + + + testuser21 + testuser21 + + + + + + + admin + admin + + + + + testuse11 + testuse11 + + + testuse21 + testuse21 + + + + + + + + + + + + + am.wso2con.com + mgt.am.wso2con.com + + + 8243 + 8280 + + + + + + + + localhost + + + 9764 + 9444 + 9446 + 8280 + + + + + + + + localhost + + + 9763 + 9443 + 8243 + 8280 + + + + + + + + localhost + + + 9765 + 9445 + 9446 + 8280 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/automationXMLSchema.xsd b/modules/integration/tests-integration/tests-scenario/target/test-classes/automationXMLSchema.xsd new file mode 100644 index 0000000000..c18b0826df --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/automationXMLSchema.xsd @@ -0,0 +1,573 @@ + + + + + + + ================================================= + Parameters ================================================= + Browser type with used by framework to execute UI test, supported types + - chrome|firefox|opera|ie|htmlUnit + + + + + + + Change this to edit wait time for test + artifact deployment + + + + + + Change this to product|platform/cloud to + execute test on specific environment + + + + + + + Change this to true if you want to generate + coverage statistics + + + + + + Change this to true if you want to enable + framework dashboard + + + + + + + + + + + + + + + Change to enable remote webDriver + URL of remote webDriver server + + + + + + + + + + + + + Type of the browser selenium tests + are running" + + + + + + + + path to webDriver + executable - required only for + chrome + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + KeyStore which will be used for + encrypting/decrypting passwords + and other sensitive information. + + + + + + + Keystore file location + + + + + + Keystore type (JKS/PKCS12 etc.) + + + + + + Keystore password + + + + + + Private Key alias + + + + + + Private Key password + + + + + + + + + + System wide trust-store which is used to + maintain the certificates of all + the trusted parties. + + + + + + + trust-store file location + + + + + + trust-store type (JKS/PKCS12 + etc.) + + + + + + trust-store password + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/axis2config/axis2_client.xml b/modules/integration/tests-integration/tests-scenario/target/test-classes/axis2config/axis2_client.xml new file mode 100644 index 0000000000..db07954a47 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/axis2config/axis2_client.xml @@ -0,0 +1,299 @@ + + + + + + + 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/integration/tests-integration/tests-scenario/target/test-classes/client/modules/addressing-1.6.1-wso2v11-20140804.232441-526.mar b/modules/integration/tests-integration/tests-scenario/target/test-classes/client/modules/addressing-1.6.1-wso2v11-20140804.232441-526.mar new file mode 100644 index 0000000000..a42c058499 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/test-classes/client/modules/addressing-1.6.1-wso2v11-20140804.232441-526.mar differ diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/client/modules/addressing-1.6.1-wso2v11-20140814.214646-548.mar b/modules/integration/tests-integration/tests-scenario/target/test-classes/client/modules/addressing-1.6.1-wso2v11-20140814.214646-548.mar new file mode 100644 index 0000000000..29dbdf2730 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/test-classes/client/modules/addressing-1.6.1-wso2v11-20140814.214646-548.mar differ diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/client/modules/addressing-1.6.1-wso2v9.mar b/modules/integration/tests-integration/tests-scenario/target/test-classes/client/modules/addressing-1.6.1-wso2v9.mar new file mode 100644 index 0000000000..d3871a1586 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/test-classes/client/modules/addressing-1.6.1-wso2v9.mar differ diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/emma.properties b/modules/integration/tests-integration/tests-scenario/target/test-classes/emma.properties new file mode 100644 index 0000000000..b39fffdb8e --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/emma.properties @@ -0,0 +1,103 @@ +# ------------------------------------------------------------- +# +# for user-editable property overrides use one of these options: +# +# (1) option-specific command line overrides, e.g. +# -Dreport.txt.out.file=coverage.txt +# +# (2) '-p ' command line option, +# +# (3) 'emma.properties' resource placed somewhere in the classpath +# (e.g., in \classes directory -- note that it does +# not exist by default), +# +# (4) '-Demma.*' JVM options, e.g. +# -Demma.report.txt.out.file=coverage.txt +# +# (5) 'emma.properties' JVM option pointing to a properties file +# -Demma.properties=./myproperties.txt +# ------------------------------------------------------------- + +# ------------------------------------------------------------- +# logging properties: + +verbosity.level: none + +# classloading properties: + +#clsload.forced_delegation_filter: +#clsload.through_delegation_filter: -* + +# ------------------------------------------------------------- + +# instrumentation properties: + +instr.exclude_empty_classes: true +instr.exclude_synthetic_methods: true +instr.exclude_bridge_methods: true +instr.do_suid_compensation: true + +# ------------------------------------------------------------- + +# runtime properties: + +rt.control: false +rt.control.host: localhost +rt.control.port: 44444 + +rt.filelock: true +rt.filelock.portbase: 59141 +rt.filelock.maxtime: 120000 +rt.filelock.retries: 11 + +# ------------------------------------------------------------- + +# apprunner session data output properties: + +session.out.file: coverage.es +session.out.merge: true + +# ------------------------------------------------------------- + +# runtime coverage data output properties: + +coverage.out.file: coverage.ec +coverage.out.merge: true + +# ------------------------------------------------------------- + +# instr metadata output properties: + +metadata.out.file: coverage.em +metadata.out.merge: true + +# ------------------------------------------------------------- + +# common report defaults: + +report.units: instr +report.depth: method +report.columns: name, line, block, method, class +report.sort: -line,-block,-method,-class,+name +report.metrics: method:40,block:80,line:40,class:100 + +# ------------------------------------------------------------- +# txt report properties: + +report.txt.depth: all +report.txt.columns: class,method,block,line,name +report.txt.out.file: coverage.txt + +# ------------------------------------------------------------- +# html report properties: + +#report.html.out.dir: coverage +report.html.out.encoding: ISO-8859-1 + +# ------------------------------------------------------------- +# xml report properties: + +report.xml.out.file: coverage.xml +report.xml.out.encoding: UTF-8 +# ------------------------------------------------------------- +# end of file diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/keystores/products/client-truststore.jks b/modules/integration/tests-integration/tests-scenario/target/test-classes/keystores/products/client-truststore.jks new file mode 100644 index 0000000000..9e3a51db3e Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/test-classes/keystores/products/client-truststore.jks differ diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/keystores/products/wso2carbon.jks b/modules/integration/tests-integration/tests-scenario/target/test-classes/keystores/products/wso2carbon.jks new file mode 100644 index 0000000000..7942c53cf9 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/test-classes/keystores/products/wso2carbon.jks differ diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/keystores/stratos/client-truststore.jks b/modules/integration/tests-integration/tests-scenario/target/test-classes/keystores/stratos/client-truststore.jks new file mode 100644 index 0000000000..9e3a51db3e Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/test-classes/keystores/stratos/client-truststore.jks differ diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/keystores/stratos/wso2carbon.jks b/modules/integration/tests-integration/tests-scenario/target/test-classes/keystores/stratos/wso2carbon.jks new file mode 100644 index 0000000000..7942c53cf9 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/test-classes/keystores/stratos/wso2carbon.jks differ diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/log4j.properties b/modules/integration/tests-integration/tests-scenario/target/test-classes/log4j.properties new file mode 100644 index 0000000000..693babfefe --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/log4j.properties @@ -0,0 +1,43 @@ +# +# Copyright 2009 WSO2, Inc. (http://wso2.com) +# +# 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 Carbon +# +# 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 Carbon Management Console, and those +# settings will override the settings in this file. +# + +log4j.rootLogger=INFO, console, Default + +log4j.logger.org.wso2=INFO + +#Automation file apender +log4j.appender.Default=org.apache.log4j.RollingFileAppender +log4j.appender.Default.File=logs/automation.log +log4j.appender.Default.Append=true +log4j.appender.Default.MaxFileSize=10MB +log4j.appender.Default.MaxBackupIndex=10 +log4j.appender.Default.layout=org.apache.log4j.PatternLayout +log4j.appender.Default.layout.ConversionPattern=%d{ISO8601} %-5p [%c] - %m%n + + +#Automation console apender +log4j.appender.console=org.apache.log4j.ConsoleAppender +log4j.appender.console.layout=org.apache.log4j.PatternLayout +log4j.appender.console.layout.ConversionPattern=%-5p [%c] - %m%n diff --git a/modules/integration/tests-integration/tests-scenario/target/test-classes/testng.xml b/modules/integration/tests-integration/tests-scenario/target/test-classes/testng.xml new file mode 100644 index 0000000000..6be6403867 --- /dev/null +++ b/modules/integration/tests-integration/tests-scenario/target/test-classes/testng.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/components/features/org.wso2.carbon.identity.provider.server_4.3.0.SNAPSHOT/conf/userRP.jks b/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/components/features/org.wso2.carbon.identity.provider.server_4.3.0.SNAPSHOT/conf/userRP.jks new file mode 100644 index 0000000000..2536ea8fb2 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/components/features/org.wso2.carbon.identity.provider.server_4.3.0.SNAPSHOT/conf/userRP.jks differ diff --git a/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/components/features/org.wso2.carbon.identity.provider.server_4.3.0.SNAPSHOT/conf/wso2is-user-certs.jks b/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/components/features/org.wso2.carbon.identity.provider.server_4.3.0.SNAPSHOT/conf/wso2is-user-certs.jks new file mode 100644 index 0000000000..3cb1ae7d62 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/components/features/org.wso2.carbon.identity.provider.server_4.3.0.SNAPSHOT/conf/wso2is-user-certs.jks differ diff --git a/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/components/features/org.wso2.carbon.identity.relying.party.server_4.3.0.SNAPSHOT/conf/userRP.jks b/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/components/features/org.wso2.carbon.identity.relying.party.server_4.3.0.SNAPSHOT/conf/userRP.jks new file mode 100644 index 0000000000..2536ea8fb2 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/components/features/org.wso2.carbon.identity.relying.party.server_4.3.0.SNAPSHOT/conf/userRP.jks differ diff --git a/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/components/features/org.wso2.carbon.identity.relying.party.server_4.3.0.SNAPSHOT/conf/wso2is-user-certs.jks b/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/components/features/org.wso2.carbon.identity.relying.party.server_4.3.0.SNAPSHOT/conf/wso2is-user-certs.jks new file mode 100644 index 0000000000..3cb1ae7d62 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/components/features/org.wso2.carbon.identity.relying.party.server_4.3.0.SNAPSHOT/conf/wso2is-user-certs.jks differ diff --git a/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/deployment/client/modules/addressing-1.6.1-wso2v11-20140814.214646-548.mar b/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/deployment/client/modules/addressing-1.6.1-wso2v11-20140814.214646-548.mar new file mode 100644 index 0000000000..29dbdf2730 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/deployment/client/modules/addressing-1.6.1-wso2v11-20140814.214646-548.mar differ diff --git a/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/resources/security/client-truststore.jks b/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/resources/security/client-truststore.jks new file mode 100644 index 0000000000..9e3a51db3e Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/resources/security/client-truststore.jks differ diff --git a/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/resources/security/wso2carbon.jks b/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/resources/security/wso2carbon.jks new file mode 100644 index 0000000000..7942c53cf9 Binary files /dev/null and b/modules/integration/tests-integration/tests-scenario/target/tobeCopied/wso2am-1.7.0-SNAPSHOT/repository/resources/security/wso2carbon.jks differ diff --git a/modules/integration/tests-new/pom.xml b/modules/integration/tests-new/pom.xml new file mode 100644 index 0000000000..e485cf5f0e --- /dev/null +++ b/modules/integration/tests-new/pom.xml @@ -0,0 +1,299 @@ + + + + org.wso2.am + integration + 1.7.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + WSO2 API Manager - Integration Test New Module + org.wso2.carbon.am.integration.test-new + jar + + + + + maven-surefire-plugin + false + 2.12.4 + + + -Xmx1024m -XX:PermSize=256m -XX:MaxPermSize=512m + + + src/test/resources/testng-server-mgt.xml + src/test/resources/testng.xml + + + + + maven.test.haltafterfailure + false + + + carbon.zip + + ${basedir}/../../distribution/product/target/wso2am-${project.version}.zip + + + + framework.resource.location + + ${basedir}/src/test/resources/ + + + + server.list + + artifacts.AM + + + + usedefaultlisteners + false + + ${basedir}/target/security-verifier/ + ${basedir}/target/emma + ${basedir}/src/test/resources/instrumentation.txt + ${basedir}/src/test/resources/filters.txt + ${basedir}/target/emma + + ${basedir}/target + + + + maven-dependency-plugin + + + + copy-emma-dependencies + compile + + copy-dependencies + + + ${project.build.directory}/emma + jar + emma,org.wso2.carbon.automation.core + + + + + + copy-secVerifier + compile + + copy-dependencies + + + ${basedir}/target/security-verifier + aar + SecVerifier + true + + + + + unpack-mar-jks + compile + + unpack + + + + + org.wso2.am + wso2am + ${project.version} + zip + true + ${basedir}/target/tobeCopied/ + **/*.jks,**/*.mar,**/axis2_client.xml + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + + test-jar + + + + + + org.apache.maven.plugins + maven-surefire-report-plugin + 2.7.1 + + ${basedir}/target/report + registry-api-test + + + + integration-test + + report-only + + + + + + + maven-resources-plugin + 2.6 + + + copy-resources-jks + compile + + copy-resources + + + ${basedir}/src/test/resources/keystores/products + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/resources/security/ + + + **/*.jks + + + + + + + copy-axis2files + compile + + copy-resources + + + ${basedir}/src/test/resources/axis2config + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/conf/axis2/ + + + **/*.xml + + + + + + + copy-resources-mar + compile + + copy-resources + + + ${basedir}/src/test/resources/client/modules + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/deployment/client/modules + + + **/*.mar + + + + + + + + + + + + + org.wso2.am + org.wso2.am.backend.service + 1.7.0 + + + org.wso2.carbon + org.wso2.carbon.apimgt.api + 1.2.0 + + + org.codehaus.jettison.wso2 + jettison + ${orbit.version.jettison} + + + emma + emma + ${emma.version} + + + org.wso2.carbon + SecVerifier + ${carbon.platform.version} + aar + + + org.wso2.carbon.automation + org.wso2.carbon.automation.test.api + ${test-automation-framework-version} + + + org.wso2.carbon.automation + org.wso2.carbon.automation.engine + ${test-automation-framework-version} + + + org.wso2.carbon.automation + org.wso2.carbon.automation.test.utils + ${test-automation-framework-version} + + + org.wso2.carbon.automation + org.wso2.carbon.automation.extensions + ${test-automation-framework-version} + + + org.testng + testng + 6.1.1 + test + + + org.wso2.carbon + org.wso2.carbon.integration.framework + 4.2.0 + + + org.wso2.carbon + org.wso2.carbon.apimgt.hostobjects + 1.2.0 + + + commons-digester + commons-digester + 2.1 + + + + 4.3.0 + + diff --git a/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/APIManagerBaseTest.java b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/APIManagerBaseTest.java new file mode 100644 index 0000000000..572cc8c041 --- /dev/null +++ b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/APIManagerBaseTest.java @@ -0,0 +1,50 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.automation.engine.context.AutomationContext; +import org.wso2.carbon.automation.engine.context.TestUserMode; + +import javax.xml.xpath.XPathExpressionException; + +public abstract class APIManagerBaseTest { + protected Log log = LogFactory.getLog(getClass()); + + protected AutomationContext automationContextStore; + protected AutomationContext automationContextPublisher; + + protected void initPublisher(String productGroupName, String instanceName, TestUserMode userMode) throws XPathExpressionException { + automationContextPublisher = new AutomationContext(productGroupName, instanceName, userMode); + } + + protected void initPublisher( TestUserMode userMode) throws XPathExpressionException { + automationContextPublisher = new AutomationContext("AM", userMode); + } + + protected void initStore( TestUserMode userMode) throws XPathExpressionException { + automationContextStore = new AutomationContext("AM", userMode); + } + protected void initStore(String productGroupName, String instanceName, TestUserMode userMode) throws XPathExpressionException { + automationContextStore = new AutomationContext(productGroupName, instanceName, userMode); + } + +} + diff --git a/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/rest/JAXRSSampleTestCase.java b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/rest/JAXRSSampleTestCase.java new file mode 100644 index 0000000000..6a00e2c1cc --- /dev/null +++ b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/rest/JAXRSSampleTestCase.java @@ -0,0 +1,165 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.rest; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.am.tests.APIManagerBaseTest; +import org.wso2.carbon.am.tests.util.APIMgtTestUtil; +import org.wso2.carbon.am.tests.util.APIPublisherRestClient; +import org.wso2.carbon.am.tests.util.APIStoreRestClient; +import org.wso2.carbon.am.tests.util.bean.*; +import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil; +import org.wso2.carbon.automation.test.api.clients.webapp.mgt.WebAppAdminClient; +import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; +import org.wso2.carbon.automation.test.utils.webapp.WebApplicationDeploymentUtil; + +import java.io.File; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +import static org.testng.Assert.assertTrue; + +/** + * This class will host jaxrs_sample_02.war in apimgr- publisher instance and invoke its service. + */ +public class JAXRSSampleTestCase extends APIManagerBaseTest { + + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private String userName; + private String password; + private String APIName = "JaxRsTestAPI"; + private String providerName = "admin"; + private String apiInvocationURL; + private WebAppAdminClient webAppAdminClient; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + + super.initPublisher("AM", "api publisher", + TestUserMode.SUPER_TENANT_ADMIN); + super.initStore("AM", "api store", + TestUserMode.SUPER_TENANT_ADMIN); + + userName = automationContextPublisher.getUser().getUserName(); + password = automationContextPublisher.getUser().getPassword(); + apiStore = new APIStoreRestClient(automationContextStore.getContextUrls().getWebAppURL()); + apiPublisher = new APIPublisherRestClient(automationContextPublisher.getContextUrls().getWebAppURL()); + apiInvocationURL = automationContextPublisher.getInstance().getProperty("endpoint").trim() + + File.separator + "jaxRsTestAPI/1.0.0"; + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + + apiStore.removeSubscription("JaxRsTestAPI", "1.0.0", "admin", 1); + apiPublisher.deleteApi("JaxRsTestAPI", "1.0.0", "admin"); + webAppAdminClient.deleteWebAppFile("jaxrs_sample_02.war"); + + log.info("jaxrs_sample_02.war deleted successfully"); + } + + + @Test(groups = "wso2.am", description = "upload war file and verify deployment") + public void webApplicationUpload() throws Exception { + + webAppAdminClient = new WebAppAdminClient + (automationContextPublisher.getContextUrls().getBackEndUrl(), automationContextPublisher.login()); + + webAppAdminClient.warFileUplaoder(FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + + File.separator + "AM" + File.separator + "jaxrs" + File.separator + "jaxrs_sample_02.war"); + + + boolean isDeployed = + WebApplicationDeploymentUtil.isWebApplicationDeployed + (automationContextPublisher.getContextUrls().getBackEndUrl(), + automationContextPublisher.login(), + "jaxrs_sample_02"); + + Assert.assertTrue(isDeployed, "jaxrs_sample_02.war deployment failure"); + + } + + @Test(groups = {"wso2.am"}, description = "Add JaxRsTestAPI", dependsOnMethods = "webApplicationUpload") + public void addAPITestCase() throws Exception { + + // adding api + String APIContext = "jaxRsTestAPI"; + String tags = "rest,jaxrs"; + String restBackendUrl = automationContextPublisher.getContextUrls().getWebAppURL() + + "/jaxrs_sample_02/services/Starbucks_Outlet_Service"; + String description = "This JaxRsTestAPI was created by API manager integration test"; + String APIVersion = "1.0.0"; + + apiPublisher.login(userName, password); + + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(restBackendUrl)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiRequest.setSandbox(restBackendUrl); + apiPublisher.addAPI(apiRequest); + + APIBean apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisher.getApi(APIName, providerName)); + + Assert.assertEquals(apiBean.getId().getApiName(), APIName, "API Name mismatch"); + Assert.assertEquals(apiBean.getContext().trim().substring(apiBean.getContext().indexOf("/") + 1), APIContext, "API context mismatch"); + Assert.assertEquals(apiBean.getId().getVersion(), APIVersion, "API version mismatch"); + Assert.assertEquals(apiBean.getId().getProviderName(), providerName, "Provider Name mismatch"); + for (String tag : apiBean.getTags()) { + Assert.assertTrue(tags.contains(tag), "API tag data mismatched"); + } + Assert.assertEquals(apiBean.getDescription(), description, "API description mismatch"); + } + + @Test(groups = {"wso2.am"}, description = "Send request to jaxrs service", + dependsOnMethods = "addAPITestCase") + public void invokeAPI() throws Exception { + + // publishing + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, + providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + + // subscribing + apiStore.login(userName, password); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, providerName); + apiStore.subscribe(subscriptionRequest); + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest("DefaultApplication"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + + Thread.sleep(2000); + + // invoke backend-service through api mgr + assertTrue(HttpRequestUtil.doGet(apiInvocationURL + File.separator + "orders/123", requestHeaders).getResponseCode() == 200); + assertTrue(HttpRequestUtil.doGet(apiInvocationURL + File.separator + "orders/123", requestHeaders).getData().contains("\"orderId\":123}}")); + } +} + + diff --git a/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/rest/RestPeopleTestCase.java b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/rest/RestPeopleTestCase.java new file mode 100644 index 0000000000..8f76883687 --- /dev/null +++ b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/rest/RestPeopleTestCase.java @@ -0,0 +1,144 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.rest; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.am.integration.services.jaxrs.customersample.CustomerConfig; +import org.wso2.carbon.am.tests.APIManagerBaseTest; +import org.wso2.carbon.am.tests.util.APIMgtTestUtil; +import org.wso2.carbon.am.tests.util.APIPublisherRestClient; +import org.wso2.carbon.am.tests.util.APIStoreRestClient; +import org.wso2.carbon.am.tests.util.bean.*; +import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.carbon.automation.extensions.servers.tomcatserver.TomcatServerManager; +import org.wso2.carbon.automation.extensions.servers.tomcatserver.TomcatServerType; +import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; + +import java.io.File; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +import static org.testng.Assert.assertTrue; + +public class RestPeopleTestCase extends APIManagerBaseTest { + + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private String userName; + private String password; + private String APIName = "RestBackendTestAPI"; + private String providerName = "admin"; + private String apiInvocationURL; + private TomcatServerManager tomcatServerManager; + private int tomcatServerPort = 8080; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + + super.initPublisher("AM", "api publisher", + TestUserMode.SUPER_TENANT_ADMIN); + super.initStore("AM", "api store", + TestUserMode.SUPER_TENANT_ADMIN); + + userName = automationContextPublisher.getUser().getUserName(); + password = automationContextPublisher.getUser().getPassword(); + apiStore = new APIStoreRestClient(automationContextStore.getContextUrls().getWebAppURL()); + apiPublisher = new APIPublisherRestClient(automationContextPublisher.getContextUrls().getWebAppURL()); + apiInvocationURL = automationContextPublisher.getInstance().getProperty("endpoint").trim() + + File.separator + "restBackendTestAPI/1.0.0"; + + tomcatServerManager = new TomcatServerManager( + CustomerConfig.class.getName(), TomcatServerType.jaxrs.name(), tomcatServerPort); + tomcatServerManager.startServer(); + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + + apiStore.removeSubscription("RestBackendTestAPI", "1.0.0", "admin", 1); + apiPublisher.deleteApi("RestBackendTestAPI", "1.0.0", "admin"); + tomcatServerManager.stop(); + } + + @Test(groups = {"wso2.am"}, description = "Add RestBackendTest API") + public void addAPITestCase() throws Exception { + + // adding api + String APIContext = "restBackendTestAPI"; + String tags = "rest, tomcat, jaxrs"; + String restBackendUrl = "http://" + automationContextStore.getDefaultInstance().getHosts().get("default") + ":" + + tomcatServerPort + "/rest/api/customerservice"; + String description = "This RestBackendTest API was created by API manager integration test"; + String APIVersion = "1.0.0"; + + apiPublisher.login(userName, password); + + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(restBackendUrl)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiRequest.setSandbox(restBackendUrl); + apiPublisher.addAPI(apiRequest); + + APIBean apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisher.getApi(APIName, providerName)); + + Assert.assertEquals(apiBean.getId().getApiName(), APIName, "API Name mismatch"); + Assert.assertEquals(apiBean.getContext().trim().substring(apiBean.getContext().indexOf("/") + 1), APIContext, "API context mismatch"); + Assert.assertEquals(apiBean.getId().getVersion(), APIVersion, "API version mismatch"); + Assert.assertEquals(apiBean.getId().getProviderName(), providerName, "Provider Name mismatch"); + for (String tag : apiBean.getTags()) { + Assert.assertTrue(tags.contains(tag), "API tag data mismatched"); + } + Assert.assertEquals(apiBean.getDescription(), description, "API description mismatch"); + } + + @Test(groups = {"wso2.am"}, description = "Send request to rest backend service", + dependsOnMethods = "addAPITestCase") + public void invokeAPI() throws Exception { + + // publishing + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, + providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + + // subscribing + apiStore.login(userName, password); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, providerName); + apiStore.subscribe(subscriptionRequest); + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest("DefaultApplication"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + + Thread.sleep(2000); + + // invoke backend-service through api mgr + assertTrue(HttpRequestUtil.doGet(apiInvocationURL + File.separator + "customers/123/", requestHeaders).getResponseCode() == 200); + assertTrue(HttpRequestUtil.doGet(apiInvocationURL + File.separator + "customers/123/", requestHeaders).getData().contains("John")); + } +} + + diff --git a/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/APIMgtTestUtil.java b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/APIMgtTestUtil.java new file mode 100644 index 0000000000..647614ae46 --- /dev/null +++ b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/APIMgtTestUtil.java @@ -0,0 +1,89 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util; + + +import org.json.JSONException; +import org.json.JSONObject; +import org.wso2.carbon.am.tests.util.bean.APIBean; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; +import org.wso2.carbon.automation.test.utils.http.HttpResponse; + +public class APIMgtTestUtil { + + public static APIBean getAPIBeanFromHttpResponse(HttpResponse httpResponse) { + JSONObject jsonObject = null; + String APIName = null; + String APIProvider = null; + String APIVersion = null; + APIBean apiBean = null; + try { + jsonObject = new JSONObject(httpResponse.getData()); + APIName = ((JSONObject) jsonObject.get("api")).getString("name"); + APIVersion = ((JSONObject) jsonObject.get("api")).getString("version"); + APIProvider = ((JSONObject) jsonObject.get("api")).getString("provider"); + APIIdentifier identifier = new APIIdentifier(APIProvider, APIName, APIVersion); + apiBean = new APIBean(identifier); + apiBean.setContext(((JSONObject) jsonObject.get("api")).getString("context")); + apiBean.setDescription(((JSONObject) jsonObject.get("api")).getString("description")); + apiBean.setWsdlUrl(((JSONObject) jsonObject.get("api")).getString("wsdl")); + apiBean.setTags(((JSONObject) jsonObject.get("api")).getString("tags")); + apiBean.setAvailableTiers(((JSONObject) jsonObject.get("api")).getString("availableTiers")); + apiBean.setThumbnailUrl(((JSONObject) jsonObject.get("api")).getString("thumb")); + apiBean.setSandboxUrl(((JSONObject) jsonObject.get("api")).getString("sandbox")); + apiBean.setBusinessOwner(((JSONObject) jsonObject.get("api")).getString("bizOwner")); + apiBean.setBusinessOwnerEmail(((JSONObject) jsonObject.get("api")).getString("bizOwnerMail")); + apiBean.setTechnicalOwner(((JSONObject) jsonObject.get("api")).getString("techOwner")); + apiBean.setTechnicalOwnerEmail(((JSONObject) jsonObject.get("api")).getString("techOwnerMail")); + apiBean.setWadlUrl(((JSONObject) jsonObject.get("api")).getString("wadl")); + apiBean.setVisibility(((JSONObject) jsonObject.get("api")).getString("visibility")); + apiBean.setVisibleRoles(((JSONObject) jsonObject.get("api")).getString("roles")); + apiBean.setEndpointUTUsername(((JSONObject) jsonObject.get("api")).getString("epUsername")); + apiBean.setEndpointUTPassword(((JSONObject) jsonObject.get("api")).getString("epPassword")); + apiBean.setEndpointSecured((Boolean.getBoolean(((JSONObject) jsonObject.get("api")).getString("endpointTypeSecured")))); + apiBean.setTransports(((JSONObject) jsonObject.get("api")).getString("transport_http")); + apiBean.setTransports(((JSONObject) jsonObject.get("api")).getString("transport_https")); + apiBean.setInSequence(((JSONObject) jsonObject.get("api")).getString("inSequence")); + apiBean.setOutSequence(((JSONObject) jsonObject.get("api")).getString("outSequence")); + apiBean.setAvailableTiers(((JSONObject) jsonObject.get("api")).getString("availableTiersDisplayNames")); + //-----------Here are some of unused properties, if we need to use them add params to APIBean class + //((JSONObject) jsonObject.get("api")).getString("name"); + //((JSONObject) jsonObject.get("api")).getString("endpoint"); + //((JSONObject) jsonObject.get("api")).getString("subscriptionAvailability"); + //((JSONObject) jsonObject.get("api")).getString("subscriptionTenants"); + //((JSONObject) jsonObject.get("api")).getString("endpointConfig"); + //((JSONObject) jsonObject.get("api")).getString("responseCache"); + //(((JSONObject) jsonObject.get("api")).getString("cacheTimeout"); + //((JSONObject) jsonObject.get("api")).getString("endpointConfig"); + //((JSONObject) jsonObject.get("api")).getString("version"); + //((JSONObject) jsonObject.get("api")).getString("apiStores"); + // ((JSONObject) jsonObject.get("api")).getString("provider"); + //)((JSONObject) jsonObject.get("api")).getString("tierDescs"); + //((JSONObject) jsonObject.get("api")).getString("subs"); + //((JSONObject) jsonObject.get("api")).getString("context"); + // apiBean.setLastUpdated(Date.parse((JSONObject); jsonObject.get("api")).getString("lastUpdated"))); + // apiBean.setUriTemplates((JSONObject) jsonObject.get("api")).getString("templates")); + } catch (JSONException e) { + e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } + return apiBean; + } +} + diff --git a/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/APIPublisherRestClient.java b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/APIPublisherRestClient.java new file mode 100644 index 0000000000..832c670a01 --- /dev/null +++ b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/APIPublisherRestClient.java @@ -0,0 +1,295 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util; + +import org.wso2.carbon.am.tests.util.bean.APILifeCycleStateRequest; +import org.wso2.carbon.am.tests.util.bean.APIRequest; +import org.wso2.carbon.automation.test.utils.http.HttpResponse; +import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class APIPublisherRestClient { + private String backEndUrl; + private static final String URL_SURFIX = "/publisher/site/blocks"; + private Map requestHeaders = new HashMap(); + + public APIPublisherRestClient(String backEndUrl) { + this.backEndUrl = backEndUrl; + if (requestHeaders.get("Content-Type") == null) { + this.requestHeaders.put("Content-Type", "application/x-www-form-urlencoded"); + } + } + + public HttpResponse login(String userName, String password) + throws Exception { + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + URL_SURFIX + "/user/login/ajax/login.jag") + , "action=login&username=" + userName + "&password=" + password + "", requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + String session = getSession(response.getHeaders()); + if (session == null) { + throw new Exception("No session cookie found with response"); + } + setSession(session); + return response; + } else { + throw new Exception("User Login failed> " + response.getData()); + } + + } + + public HttpResponse addAPI(APIRequest apiRequest) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + URL_SURFIX + "/item-add/ajax/add.jag") + , apiRequest.generateRequestParameters() + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Adding failed> " + response.getData()); + } + } + + public HttpResponse updateAPI(APIRequest apiRequest) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + URL_SURFIX + "/item-add/ajax/add.jag") + , apiRequest.generateRequestParameters("updateAPI") + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Adding failed> " + response.getData()); + } + } + + + public HttpResponse changeAPILifeCycleStatusTo(APILifeCycleStateRequest updateRequest) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/life-cycles/ajax/life-cycles.jag") + , updateRequest.generateRequestParameters() + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API LifeCycle Updating failed> " + response.getData()); + } + + } + + public HttpResponse getApi(String apiName, String provider) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/listing/ajax/item-list.jag") + , "action=getAPI&name=" + apiName + "&version=1.0.0&provider=" + provider + "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get API Information failed> " + response.getData()); + } + + /* name=YoutubeFeeds&version=1.0.0&provider=provider1&status=PUBLISHED&publishToGateway=true&action=updateStatus */ + + } + + public HttpResponse deleteApi(String name,String version,String provider) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/item-add/ajax/remove.jag") + , "action=removeAPI&name=" + name + "&version="+version+"&provider="+provider + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Deletion failed> " + response.getData()); + } + } + + + + + public void setHttpHeader(String headerName, String value) { + this.requestHeaders.put(headerName, value); + } + + public String getHttpHeader(String headerName) { + return this.requestHeaders.get(headerName); + } + + public void removeHttpHeader(String headerName) { + this.requestHeaders.remove(headerName); + } + + private String getSession(Map responseHeaders) { + return responseHeaders.get("Set-Cookie"); + } + + private String setSession(String session) { + return requestHeaders.put("Cookie", session); + } + + private boolean checkAuthentication() throws Exception { + if (requestHeaders.get("Cookie") == null) { + throw new Exception("No Session Cookie found. Please login first"); + } + return true; + } + + /** + * @param apiName String name of the API that need to remove + * @param version String version of the API that need to remove + * @param provider String provider name of the API that need to remove + * @return + * @throws Exception when invocation does ont return 200 response + */ + public HttpResponse removeAPI(String apiName, String version, String provider) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/item-add/ajax/remove.jag") + , "action=removeAPI" + "&name=" + apiName + "&version=" + version + "&provider=" + provider + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + + public HttpResponse addDocument(String apiName, String version, String provider, String docName, String docType, String sourceType, String docUrl, String summary, String docLocation) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/documentation/ajax/docs.jag") + , "action=addDocumentation" + "&provider=" + provider + "&apiName=" + apiName + "&version=" + version + "&docName=" + docName + "&docType=" + docType + "&sourceType=" + sourceType + "&docUrl=" + docUrl + + summary + "&docLocation=" + docLocation + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + /* + docDetails.name = request.getParameter("docName"); + docDetails.content = request.getParameter("content"); + result = mod.addInlineContent(apiDetails, docDetails); + */ + public HttpResponse inlineContent(String apiName, String version, String provider, String docName, String content, String docDetails) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/documentation/ajax/docs.jag") + , "action=addInlineContent" + "&provider=" + provider + "&apiName=" + apiName + "&version=" + version + "&docName=" + docName + "&content=" + content + "&docDetails=" + docDetails + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse removeDocumentation(String apiName, String version, String provider, String docName, String docType) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/documentation/ajax/docs.jag") + , "action=removeDocumentation" + "&provider=" + provider + "&apiName=" + apiName + "&version=" + version + "&docName=" + docName + "&docType=" + docType + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse getAccessTokenData(String accessToken) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/tokens/ajax/token.jag") + , "action=getAccessTokenData" + "&accessToken=" + accessToken + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse revokeAccessToken(String accessToken, String consumerKey, String authUser) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/tokens/ajax/revokeToken.jag") + , "action=revokeAccessToken" + "&accessToken=" + accessToken+"&authUser="+authUser+"&consumerKey="+consumerKey + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + public HttpResponse revokeAccessTokenBySubscriber(String subscriberName) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/tokens/ajax/revokeToken.jag") + , "action=revokeAccessTokenBySubscriber" + "&subscriberName=" + subscriberName + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse updatePermissions(String tierName, String permissionType, String roles) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/tiers/ajax/tiers.jag") + , "action=updatePermissions" + "&tierName=" + tierName + "&permissiontype=" + permissionType + "&roles=" + roles + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + + public HttpResponse createNewAPI(String provider, String apiName, String version, String newVersion) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/overview/ajax/overview.jag") + , "action=createNewAPI" + "&provider=" + provider + "&apiName=" + apiName + "&version=" + version +"&newVersion="+newVersion + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } +} diff --git a/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/APIStoreRestClient.java b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/APIStoreRestClient.java new file mode 100644 index 0000000000..e8607ecfff --- /dev/null +++ b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/APIStoreRestClient.java @@ -0,0 +1,438 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util; + +import org.apache.commons.codec.binary.Base64; +import org.wso2.carbon.am.tests.util.bean.GenerateAppKeyRequest; +import org.wso2.carbon.am.tests.util.bean.SubscriptionRequest; +import org.wso2.carbon.automation.test.utils.http.HttpResponse; +import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class APIStoreRestClient { + private String backEndUrl; + private Map requestHeaders = new HashMap(); + + public APIStoreRestClient(String backEndUrl) { + this.backEndUrl = backEndUrl; + if (requestHeaders.get("Content-Type") == null) { + this.requestHeaders.put("Content-Type", "application/x-www-form-urlencoded"); + } + } + + public HttpResponse login(String userName, String password) + throws Exception { + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/user/login/ajax/login.jag") + , "action=login&username=" + userName + "&password=" + password + "", requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + String session = getSession(response.getHeaders()); + if (session == null) { + throw new Exception("No session cookie found with response"); + } + setSession(session); + return response; + } else { + throw new Exception("User Login failed> " + response.getData()); + } + + } + + public HttpResponse subscribe(SubscriptionRequest subscriptionRequest) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag") + , subscriptionRequest.generateRequestParameters() + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + + } + + public HttpResponse generateApplicationKey(GenerateAppKeyRequest generateAppKeyRequest) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag") + , generateAppKeyRequest.generateRequestParameters() + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + + } + + public HttpResponse getAPI(String apiName) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/api/listing/ajax/list.jag?action=getAllPublishedAPIs") + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse removeSubscription(String name,String version,String provider,int id) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/subscription/subscription-remove/ajax/subscription-remove.jag") + , "action=removeSubscription&name=" + name + "&version="+version+"&provider="+provider+"&applicationId="+id + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Subscription Removal Failed " + response.getData()); + } + } + + public void setHttpHeader(String headerName, String value) { + this.requestHeaders.put(headerName, value); + } + + public String getHttpHeader(String headerName) { + return this.requestHeaders.get(headerName); + } + + public void removeHttpHeader(String headerName) { + this.requestHeaders.remove(headerName); + } + + private String getSession(Map responseHeaders) { + return responseHeaders.get("Set-Cookie"); + } + + private String setSession(String session) { + return requestHeaders.put("Cookie", session); + } + + private boolean checkAuthentication() throws Exception { + if (requestHeaders.get("Cookie") == null) { + throw new Exception("No Session Cookie found. Please login first"); + } + return true; + } + + + public HttpResponse generateUserAccessKey(String consumeKey, String consumerSecret, String body, URL tokenEndpointURL) + throws Exception { + checkAuthentication(); + Map authenticationRequestHeaders = new HashMap(); + String basicAuthHeader = consumeKey + ":" +consumerSecret; + byte[] encodedBytes = Base64.encodeBase64(basicAuthHeader.getBytes()); + authenticationRequestHeaders.put("Content-Type", "application/x-www-form-urlencoded"); + authenticationRequestHeaders.put("Authorization", "Basic " + new String(encodedBytes)); + HttpResponse response = HttpRequestUtil.doPost(tokenEndpointURL + , body + , authenticationRequestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + + public HttpResponse getAllPublishedAPIs() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl+"/store/site/blocks/api/listing/ajax/list.jag?action=getAllPublishedAPIs" + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + + public HttpResponse getAllApplications() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl+"/store/site/blocks/application/application-list/ajax/application-list.jag?action=getApplications" + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + public HttpResponse getPublishedAPIsByApplication(String applicationName) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl+"/store/site/blocks/subscription/subscription-list/ajax/subscription-list.jag?action=getSubscriptionByApplication&app="+applicationName + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + + public HttpResponse addRatingToAPI(String apiName, String version, String provider, String rating) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl+"/store/site/blocks/api/api-info/ajax/api-info.jag?" + + "action=addRating&name=" + apiName + "&version=" + version + "&provider=" + provider + "&rating=" + rating + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + public HttpResponse removeRatingFromAPI(String apiName, String version, String provider) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl+"/store/site/blocks/api/api-info/ajax/api-info.jag?" + + "action=removeRating&name=" + apiName + "&version=" + version + "&provider=" + provider + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + + public HttpResponse isRatingActivated() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl+"/store/site/blocks/api/api-info/ajax/api-info.jag?" + + "action=isRatingActivated" + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + /* + apiData.name = request.getParameter("name"); + apiData.version = request.getParameter("version"); + apiData.provider = request.getParameter("provider") + */ + public HttpResponse getAllDocumentationOfApi(String apiName, String version, String provider) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl+"/store/site/blocks/api/listing/ajax/list.jag?" + + "action=getAllDocumentationOfApi&name=" + apiName + "&version=" + version + "&provider=" + provider + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + /* + tenant = request.getParameter("tenant"); + var start=request.getParameter("start"); + var end=request.getParameter("end"); + */ + public HttpResponse getAllPaginatedPublishedAPIs(String tenant, String start, String end) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl+"/store/site/blocks/api/listing/ajax/list.jag?" + + "action=getAllPaginatedPublishedAPIs&tenant=" + tenant + "&start=" + start + "&end=" + end + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + public HttpResponse getAllPublishedAPIs(String tenant) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/api/listing/ajax/list.jag?action=getAllPublishedAPIs&tenant=" + tenant) + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse addApplication(String application, String tier, String callbackUrl, String description) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/application/application-add/ajax/application-add.jag?action=addApplication&tier=" + tier + "&callbackUrl="+callbackUrl+"&description="+description+"&application="+application) + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse getApplications() + throws Exception { + checkAuthentication(); + + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/application/application-list/ajax/application-list.jag?action=getApplications") + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse removeApplication(String application) + throws Exception { + checkAuthentication(); + + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/application/application-remove/ajax/application-remove.jag?action=removeApplication&application=" + application) + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse updateApplication(String applicationOld, String applicationNew, String callbackUrlNew, String descriptionNew, String tier) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/application/application-update/ajax/application-update.jag?" + + "action=updateApplication&applicationOld=" + applicationOld + "&applicationNew="+applicationNew+"&callbackUrlNew="+callbackUrlNew+ + "&descriptionNew="+descriptionNew+"&tier="+tier) + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + public HttpResponse getAllSubscriptions() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/subscription/subscription-list/ajax/subscription-list.jag?" + + "action=getAllSubscriptions") + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse getAllTags() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/tag/tag-cloud/ajax/list.jag?action=getAllTags") + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + /* + name = request.getParameter("name"); + version = request.getParameter("version"); + provider = request.getParameter("provider"); + comment = request.getParameter("comment"); + /home/sanjeewa/carbon/turing/components/apimgt/api-store-web/1.2.0/src/site/blocks/comment/comment-add/ajax/comment-add.jag + */ + public HttpResponse addComment(String name, String version, String provider, String comment) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl + "/store/site/blocks/comment/comment-add/ajax/comment-add.jag?" + + "action=addComment&name=" + name + "&version="+version+"&provider="+provider+"&comment="+comment + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse isCommentActivated() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl + "/store/site/blocks/comment/comment-add/ajax/comment-add.jag?" + + "action=isCommentActivated" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse getRecentlyAddedAPIs(String tenant, String limit) + throws Exception { + ///home/sanjeewa/carbon/turing/components/apimgt/api-store-web/1.2.0/src/site/blocks/api/recently-added/ajax/list.jag + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/api/recently-added/ajax/list.jag?action=getRecentlyAddedAPIs"+ + "&tenant="+tenant+"&limit="+limit) + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } +} diff --git a/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/VerificationUtil.java b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/VerificationUtil.java new file mode 100644 index 0000000000..91a3807d3b --- /dev/null +++ b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/VerificationUtil.java @@ -0,0 +1,31 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util; + +import org.json.JSONObject; +import org.wso2.carbon.automation.test.utils.http.HttpResponse; + +public class VerificationUtil { + public static void checkErrors(HttpResponse response) throws Exception { + JSONObject jsonObject = new JSONObject(response.getData()); + if ((Boolean) jsonObject.get("error")) { + throw new Exception("Operation not successful: " + jsonObject.get("message").toString()); + } + } +} diff --git a/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/WireMonitor.java b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/WireMonitor.java new file mode 100644 index 0000000000..dbb71dcacb --- /dev/null +++ b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/WireMonitor.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2005-2010, 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.carbon.am.tests.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; + +class WireMonitor extends Thread { + private Log log = LogFactory.getLog(WireMonitor.class); + private static final int TIMEOUT_VALUE = 60000; + private int port; + private ServerSocket providerSocket; + private Socket connection = null; + public String message = ""; + private WireMonitorServer trigger; + + public void run() { + try { + + // creating a server socket + providerSocket = new ServerSocket(port, 10); + + log.info("Waiting for connection"); + connection = providerSocket.accept(); + log.info("Connection received from " + + connection.getInetAddress().getHostName()); + InputStreamReader in = new InputStreamReader(connection.getInputStream()); + BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String line = ""; + Long time = System.currentTimeMillis(); + while ((line = rd.readLine()) != null && !line.equals("")) { + message = message + line; + // In this case no need of reading more than timeout value + if (System.currentTimeMillis() > (time + TIMEOUT_VALUE)) { + break; + } + } + + // Signaling Main thread to continue + trigger.response = message; + trigger.isFinished = true; + + //Sending default response + PrintWriter out = new PrintWriter(connection.getOutputStream()); + String responseText = "[Response] Request Received. This is the default Response."; + String httpResponse = "HTTP/1.1 200 OK\n" + + "Content-Type: text/xml;charset=utf-8\n" + + "Content-Length: " + responseText.length() + "\n" + + "\n" + + responseText; + out.write(httpResponse); + out.flush(); + + in.close(); + rd.close(); + out.close(); + + } catch (IOException ioException) { + ioException.printStackTrace(); + } finally { + try { + connection.close(); + providerSocket.close(); + } catch (Exception e) { + + } + } + + } + + public WireMonitor(int listenPort, WireMonitorServer trigger) { + port = listenPort; + this.trigger = trigger; + } + +} diff --git a/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/WireMonitorServer.java b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/WireMonitorServer.java new file mode 100644 index 0000000000..c7a98bc874 --- /dev/null +++ b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/WireMonitorServer.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2005-2010, 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.carbon.am.tests.util; + +/** + * This class can be used to capture wire messages + * + */ +public class WireMonitorServer { + private static final int TIMEOUT_VALUE = 60000; + boolean isFinished = false; + String response; + int port; + + /** + * Start listening to a port + * + * @param port + * to be listened + */ + public WireMonitorServer(int port) { + this.port = port; + } + + public void start() { + response = ""; + isFinished = false; + Thread thread = new WireMonitor(port, this); + thread.start(); + } + + + /** + * Wait until response is received and returns + * @return will return null if response is not received + */ + public String getCapturedMessage() { + Long time = System.currentTimeMillis(); + while (!isFinished) { + // If wire monitor is not responding than 2min this will continue + if (System.currentTimeMillis() > (time + TIMEOUT_VALUE)) { + break; + } + } + return response; + } +} diff --git a/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/APIBean.java b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/APIBean.java new file mode 100644 index 0000000000..99dd52caf7 --- /dev/null +++ b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/APIBean.java @@ -0,0 +1,48 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util.bean; + +import org.wso2.carbon.apimgt.api.model.*; + +import java.util.HashSet; +import java.util.Set; + +public class APIBean extends API { + private String tags; + private String availableTiers; + public APIBean(APIIdentifier id) { + super(id); + } + + public void setAvailableTiers(String availableTiers) { + this.availableTiers = availableTiers; + } + + public void setTags(String tags) { + this.tags = tags; + Set stringSet = new HashSet(); + String[] strings =tags.split(","); + for (String str :strings){ + stringSet.add(str); + } + super.addTags(stringSet); + } +} + diff --git a/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/APILifeCycleState.java b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/APILifeCycleState.java new file mode 100644 index 0000000000..e72188bdcc --- /dev/null +++ b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/APILifeCycleState.java @@ -0,0 +1,33 @@ +package org.wso2.carbon.am.tests.util.bean; +/* +*Copyright (c) 2005-2010, 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. +*/ + +public enum APILifeCycleState { + + PUBLISHED("PUBLISHED"), CREATED("CREATED"), DEPRECATED("DEPRECATED"), BLOCKED("BLOCKED"); + + private String state; + + APILifeCycleState(String state) { + this.state = state; + } + + public String getState() { + return state; + } +} diff --git a/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/APILifeCycleStateRequest.java b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/APILifeCycleStateRequest.java new file mode 100644 index 0000000000..f1049864b6 --- /dev/null +++ b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/APILifeCycleStateRequest.java @@ -0,0 +1,83 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util.bean; + + +/** + * action=updateStatus&name=YoutubeFeeds&version=1.0.0&provider=provider1&status=PUBLISHED&publishToGateway=true + */ +public class APILifeCycleStateRequest extends AbstractRequest { + private String name; + private String status; + private String provider; + private String version = "1.0.0"; + private String publishToGateway = "true"; + + public APILifeCycleStateRequest(String apiName, String provider, APILifeCycleState status) { + this.name = apiName; + this.status = status.getState(); + this.provider = provider; + } + @Override + public void setAction() { + setAction("updateStatus"); + } + + @Override + public void init() { + addParameter("name",name); + addParameter("status", status); + addParameter("provider", provider); + + addParameter("version", version); + addParameter("publishToGateway", publishToGateway); + } + + public String getName() { + return name; + } + + public String getState() { + return status; + } + + public void setState(APILifeCycleState status) { + this.status = status.getState(); + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getProvider() { + return provider; + } + + public boolean getPublishToGateway() { + return Boolean.valueOf(publishToGateway); + } + + public void setPublishToGateway(boolean publishToGateway) { + this.publishToGateway = String.valueOf(publishToGateway); + } +} diff --git a/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/APIRequest.java b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/APIRequest.java new file mode 100644 index 0000000000..1cc5802a7d --- /dev/null +++ b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/APIRequest.java @@ -0,0 +1,283 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util.bean; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.net.URL; + +/** + * action=addAPI&name=YoutubeFeeds&visibility=public&version=1.0.0&description=Youtube Live Feeds&endpointType=nonsecured + * &http_checked=http&https_checked=https&endpoint=http://gdata.youtube.com/feeds/api/standardfeeds&wsdl=& + * tags=youtube,gdata,multimedia&tier=Silver&thumbUrl=http://www.10bigideas.com.au/www/573/files/pf-thumbnail-youtube_logo.jpg + * &context=/youtube&tiersCollection=Gold&resourceCount=0&resourceMethod-0=GET + * &resourceMethodAuthType-0=Application&resourceMethodThrottlingTier-0=Unlimited&uriTemplate-0=/* + */ + +public class APIRequest extends AbstractRequest { + + private String name; + private String context; + private JSONObject endpoint; + + private String visibility = "public"; + private String version = "1.0.0"; + private String description = "description"; + private String endpointType = "nonsecured"; + private String http_checked = "http"; + private String https_checked = "https"; + private String tags = "tags"; + private String tier = "Silver"; + private String thumbUrl = ""; + private String tiersCollection = "Gold"; + private String resourceCount = "0"; + private String resourceMethod = "GET,POST"; + private String resourceMethodAuthType = "Application & Application User,Application & Application User"; + private String resourceMethodThrottlingTier = "Unlimited,Unlimited"; + private String uriTemplate = "/*"; + private String roles = ""; + private String wsdl = ""; + + public String getSandbox() { + return sandbox; + } + + public void setSandbox(String sandbox) { + this.sandbox = sandbox; + } + + private String sandbox = ""; + + public String getRoles() { + return roles; + } + + public void setRoles(String roles) { + this.roles = roles; + } + + public String getWsdl() { + return wsdl; + } + + public void setWsdl(String wsdl) { + this.wsdl = wsdl; + } + + + + private String provider ="admin"; + + public APIRequest(String apiName, String context, URL endpointUrl) { + this.name = apiName; + this.context = context; + try { + this.endpoint = new JSONObject("{\"production_endpoints\":{\"url\":\"" + + endpointUrl + "\",\"config\":null},\"endpoint_type\":\"" + + endpointUrl.getProtocol() + "\"}"); + } catch (JSONException e) { + //ignore + } + + } + + @Override + public void setAction() { + setAction("addAPI"); + } + + public void setAction(String action) { + super.setAction(action); + } + + @Override + public void init() { + addParameter("name", name); + addParameter("context", context); + addParameter("endpoint_config", endpoint.toString()); + addParameter("provider",getProvider()); + addParameter("visibility", getVisibility()); + addParameter("version", getVersion()); + addParameter("description", getDescription()); + addParameter("endpointType", getEndpointType()); + addParameter("http_checked", getHttp_checked()); + addParameter("https_checked", getHttps_checked()); + addParameter("tags", getTags()); + addParameter("tier", getTier()); + addParameter("thumbUrl", getThumbUrl()); + addParameter("tiersCollection", getTiersCollection()); + addParameter("resourceCount", getResourceCount()); + addParameter("resourceMethod-0", getResourceMethod()); + addParameter("resourceMethodAuthType-0", getResourceMethodAuthType()); + addParameter("resourceMethodThrottlingTier-0", getResourceMethodThrottlingTier()); + addParameter("uriTemplate-0", getUriTemplate()); + if(roles.length()>1){ + addParameter("roles", getRoles()); + } + if(wsdl.length()>1) { + addParameter("wsdl", getWsdl()); + } + if(sandbox.length()>1) { + addParameter("sandbox", getSandbox()); + } + + } + + public String getProvider() { + return provider; + } + + public void setProvider(String provider) { + this.provider = provider; + } + + public String getName() { + return name; + } + + public JSONObject getEndpointConfig() { + return endpoint; + } + + public String getContext() { + return context; + } + + public String getVisibility() { + return visibility; + } + + public void setVisibility(String visibility) { + this.visibility = visibility; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getEndpointType() { + return endpointType; + } + + public void setEndpointType(String endpointType) { + this.endpointType = endpointType; + } + + public String getHttp_checked() { + return http_checked; + } + + public void setHttp_checked(String http_checked) { + this.http_checked = http_checked; + } + + public String getHttps_checked() { + return https_checked; + } + + public void setHttps_checked(String https_checked) { + this.https_checked = https_checked; + } + + public String getTags() { + return tags; + } + + public void setTags(String tags) { + this.tags = tags; + } + + public String getTier() { + return tier; + } + + public void setTier(String tier) { + this.tier = tier; + } + + public String getThumbUrl() { + return thumbUrl; + } + + public void setThumbUrl(String thumbUrl) { + this.thumbUrl = thumbUrl; + } + + public String getTiersCollection() { + return tiersCollection; + } + + public void setTiersCollection(String tiersCollection) { + this.tiersCollection = tiersCollection; + } + + public String getResourceCount() { + return resourceCount; + } + + public void setResourceCount(String resourceCount) { + this.resourceCount = resourceCount; + } + + public String getResourceMethod() { + return resourceMethod; + } + + public void setResourceMethod(String resourceMethod) { + this.resourceMethod = resourceMethod; + } + + public String getResourceMethodAuthType() { + return resourceMethodAuthType; + } + + public void setResourceMethodAuthType(String resourceMethodAuthType) { + this.resourceMethodAuthType = resourceMethodAuthType; + } + + public String getResourceMethodThrottlingTier() { + return resourceMethodThrottlingTier; + } + + public void setResourceMethodThrottlingTier(String resourceMethodThrottlingTier) { + this.resourceMethodThrottlingTier = resourceMethodThrottlingTier; + } + + public String getUriTemplate() { + return uriTemplate; + } + + public void setUriTemplate(String uriTemplate) { + this.uriTemplate = uriTemplate; + } + +} diff --git a/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/AbstractRequest.java b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/AbstractRequest.java new file mode 100644 index 0000000000..3da20dc478 --- /dev/null +++ b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/AbstractRequest.java @@ -0,0 +1,67 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util.bean; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +public abstract class AbstractRequest { + public String action; + private Map parameterMap = new HashMap(); + private static final String ACTION_PARAMETER_VALUE = "action"; + + public String generateRequestParameters() { + parameterMap.clear(); + setAction(); + init(); + String requestParams = ACTION_PARAMETER_VALUE + "=" + action; + Iterator irt = parameterMap.keySet().iterator(); + while (irt.hasNext()) { + String key = irt.next(); + requestParams = requestParams + "&" + key + "=" + parameterMap.get(key); + } + return requestParams; + } + + public String generateRequestParameters(String actionName) { + parameterMap.clear(); + setAction(); + init(); + String requestParams = ACTION_PARAMETER_VALUE + "=" + actionName; + Iterator irt = parameterMap.keySet().iterator(); + while (irt.hasNext()) { + String key = irt.next(); + requestParams = requestParams + "&" + key + "=" + parameterMap.get(key); + } + return requestParams; + } + + public void addParameter(String key, String value) { + parameterMap.put(key, value); + } + + public abstract void setAction(); + + public abstract void init(); + + public void setAction(String actionName) { + this.action = actionName; + } +} diff --git a/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/GenerateAppKeyRequest.java b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/GenerateAppKeyRequest.java new file mode 100644 index 0000000000..951b17c523 --- /dev/null +++ b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/GenerateAppKeyRequest.java @@ -0,0 +1,81 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util.bean; + +/** + * action=generateApplicationKey&application=DefaultApplication&keytype=PRODUCTION&callbackUrl=&authorizedDomains=ALL&validityTime=360000 + */ +public class GenerateAppKeyRequest extends AbstractRequest { + + private String application ="DefaultApplication"; + private String keyType = "PRODUCTION"; + private String callbackUrl = "some-url"; + private String authorizedDomains = "ALL"; + private int validityTime = 360000; + + public GenerateAppKeyRequest(String application) { + this.application = application; + } + + @Override + public void setAction() { + setAction("generateApplicationKey"); + } + + @Override + public void init() { + addParameter("application", application); + addParameter("keytype", keyType); + addParameter("callbackUrl", callbackUrl); + addParameter("authorizedDomains", authorizedDomains); + addParameter("validityTime", String.valueOf(validityTime)); + } + + public String getKeyType() { + return keyType; + } + + public void setKeyType(String keyType) { + this.keyType = keyType; + } + + public String getCallbackUrl() { + return callbackUrl; + } + + public void setCallbackUrl(String callbackUrl) { + this.callbackUrl = callbackUrl; + } + + public String getAuthorizedDomains() { + return authorizedDomains; + } + + public void setAuthorizedDomains(String authorizedDomains) { + this.authorizedDomains = authorizedDomains; + } + + public int getValidityTime() { + return validityTime; + } + + public void setValidityTime(int validityTime) { + this.validityTime = validityTime; + } +} diff --git a/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/SubscriptionRequest.java b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/SubscriptionRequest.java new file mode 100644 index 0000000000..92cd2697ba --- /dev/null +++ b/modules/integration/tests-new/src/test/java/org/wso2/carbon/am/tests/util/bean/SubscriptionRequest.java @@ -0,0 +1,82 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util.bean; + +/** + * action=addAPISubscription&name=apiName&version=1.0.0&provider=provider&tier=Gold&applicationName=DefaultApplication + */ +public class SubscriptionRequest extends AbstractRequest { + + private String name; + private String provider; + private String version = "1.0.0"; + private String applicationName = "DefaultApplication"; + private String tier = "Gold"; + + public SubscriptionRequest(String apiName, String provider) { + this.name = apiName; + this.provider = provider; + } + + @Override + public void setAction() { + setAction("addAPISubscription"); + } + + @Override + public void init() { + addParameter("name", name); + addParameter("provider", provider); + addParameter("version", version); + addParameter("applicationName", applicationName); + addParameter("tier", tier); + } + + public String getName() { + return name; + } + + public String getProvider() { + return provider; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getApplicationName() { + return applicationName; + } + + public void setApplicationName(String applicationName) { + this.applicationName = applicationName; + } + + public String getTier() { + return tier; + } + + public void setTier(String tier) { + this.tier = tier; + } +} diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/hostobjecttest/api-manager.xml b/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/hostobjecttest/api-manager.xml new file mode 100755 index 0000000000..a7cbbc3a14 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/hostobjecttest/api-manager.xml @@ -0,0 +1,537 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + admin + + admin + + + + + + X-JWT-Assertion + + + org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever + + + http://wso2.org/claims + + + SHA256withRSA + + + true + + + true + + + + + + + + + + + + Production and Sandbox + + 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} + + + + + true + + + referer + + + + + true + + + + + + false + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + 7612 + + + tcp://localhost:7612/ + + + admin + + + admin + + + + + + + + false + + + UA-XXXXXXXX-X + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + + admin + + + admin + + true + + + + true + + + + WSClient + 10397 + 10000 + 10397 + + true + + + + + + + + /oauth2/token + + + false + + + + + + + true + + + + + + true + + + subscriber + + + true + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/store + + true + + true + + + true + + + true + + + + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/publisher + + + + + + + + + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + + + + + + + + + + true + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + /resource + http://localhost:9764/resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + Store1 + http://localhost:9763/store + user1@tenantdomain1.com + test123 + + + + + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + GET,POST,PUT,DELETE,OPTIONS + + + + diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/jaggery/test.jag b/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/jaggery/test.jag new file mode 100644 index 0000000000..48d3201391 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/jaggery/test.jag @@ -0,0 +1,5 @@ +<% + application.put("wso2", "test artifacts.AM.configFiles.jaggery application value"); + print(application.get("wso2")); + application.remove("wso2"); +%> \ No newline at end of file diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/throttling/throttle-policy.xml b/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/throttling/throttle-policy.xml new file mode 100755 index 0000000000..aa5de6f71d --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/throttling/throttle-policy.xml @@ -0,0 +1,34 @@ + + + + 127.0.0.1 + + + + 1 + 60000 + + + + + + + other + + + + 2 + 60000 + + + + + + + 1000 + + other + + + \ No newline at end of file diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/tokenTest/api-manager.xml b/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/tokenTest/api-manager.xml new file mode 100755 index 0000000000..628b9aad19 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/tokenTest/api-manager.xml @@ -0,0 +1,556 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + admin + + admin + + + + + + X-JWT-Assertion + + + org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever + + + http://wso2.org/claims + + + SHA256withRSA + + + true + + + true + + + + + + + + + + + + Production and Sandbox + + 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} + + + + + true + + + referer + + + + + true + + + + + + false + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + 7612 + + + tcp://localhost:7612/ + + + admin + + + admin + + + + + + + + false + + + UA-XXXXXXXX-X + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + + admin + + + admin + + true + + + + true + + + + WSClient + 10397 + 10000 + 10397 + + true + + + + + + + + /oauth2/token + + + false + + + + + + + true + + + + + + true + + + subscriber + + + true + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/store + + true + + true + + + true + + + true + + + + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/publisher + + + + + + + + + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + + + + + + + + + + true + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + /resource + http://localhost:9764/resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + + + + + + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + GET,POST,PUT,DELETE,OPTIONS + + + + diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/tokenTest/log4j.properties b/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/tokenTest/log4j.properties new file mode 100755 index 0000000000..76c7eb5251 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/tokenTest/log4j.properties @@ -0,0 +1,180 @@ +# +# 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.category.org.apache.synapse=INFO +log4j.category.org.apache.synapse.transport=INFO +log4j.category.org.apache.axis2=INFO +log4j.category.org.apache.axis2.transport=INFO +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 +#log4j.logger.org.wso2.carbon.apimgt.gateway.handlers=DEBUG +#log4j.logger.org.wso2.carbon.apimgt.gateway.handlers.throttling=DEBUG +log4j.logger.org.wso2.carbon.apimgt=DEBUG + +# 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 + +# 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 + +# The console appender is used to display general information at console +log4j.appender.CARBON_CONSOLE=org.wso2.carbon.logging.appenders.CarbonConsoleAppender +log4j.appender.CARBON_CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CARBON_CONSOLE.layout.ConversionPattern=[%d{ISO8601}] %5p - %c{1} %m%n + +# 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-apigw-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-apigw-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.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.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-apigw-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.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 + +# LOGEVENT is set to be a LogEventAppender using a PatternLayout to send logs to LOGEVENT +log4j.appender.LOGEVENT=org.wso2.carbon.logging.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 + + +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 + +# LOGEVENT is set to be a LogEventAppender using a PatternLayout to send logs to LOGEVENT +log4j.appender.LOGEVENT=org.wso2.carbon.logging.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,%H,%I,%Stacktrace +log4j.appender.LOGEVENT.userName=admin +log4j.appender.LOGEVENT.password=admin + +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 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 + diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/usagemonitortest/api-manager.xml b/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/usagemonitortest/api-manager.xml new file mode 100755 index 0000000000..406151fa75 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/usagemonitortest/api-manager.xml @@ -0,0 +1,537 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + admin + + admin + + + + + + X-JWT-Assertion + + + org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever + + + http://wso2.org/claims + + + SHA256withRSA + + + true + + + true + + + + + + + + + + + + Production and Sandbox + + 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} + + + + + true + + + referer + + + + + true + + + + + + true + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + 7612 + + + tcp://localhost:7612/ + + + admin + + + admin + + + + + + + + false + + + UA-XXXXXXXX-X + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + + admin + + + admin + + true + + + + true + + + + WSClient + 10397 + 10000 + 10397 + + true + + + + + + + + /oauth2/token + + + false + + + + + + + true + + + + + + true + + + subscriber + + + true + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/store + + true + + true + + + true + + + true + + + + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/publisher + + + + + + + + + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + + + + + + + + + + true + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + /resource + http://localhost:9764/resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + Store1 + http://localhost:9763/store + user1@tenantdomain1.com + test123 + + + + + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + GET,POST,PUT,DELETE,OPTIONS + + + + diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/usagemonitortest/master-datasources.xml b/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/usagemonitortest/master-datasources.xml new file mode 100755 index 0000000000..8cc23ee0b4 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/configFiles/usagemonitortest/master-datasources.xml @@ -0,0 +1,109 @@ + + + + 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 + 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 + + + + + + WSO2AM_STATS_DB + The datasource used for getting statistics to API Manager + + jdbc/WSO2AM_STATS_DB + + + + jdbc:h2:;AUTO_SERVER=TRUE + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/jaggery/testPublisher.jag b/modules/integration/tests-new/src/test/resources/artifacts/AM/jaggery/testPublisher.jag new file mode 100644 index 0000000000..bbd5eec078 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/jaggery/testPublisher.jag @@ -0,0 +1,96 @@ +<% +//Order of these operations are important as we fetch results based on order. +//If you add new test add them to bottom of this file and update validate response method +//available in host object test class. +var publisher = require('apipublisher'); +var publisherHostObj = new publisher.APIProvider("admin"); +print("=="); +print(publisherHostObj.getExternalAPIStores()); +print("=="); +print(publisherHostObj.validateRoles('admin', 'admin')); +print("=="); +print(publisherHostObj.isURLValid("https","https://www.google.com")); +print("=="); +print(publisherHostObj.getAPIsByProvider("admin")); +print("=="); +print(publisherHostObj.getSubscribedAPIs("admin")); +print("=="); +print(publisherHostObj.getAPI("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.getTierPermissions()); +print("=="); +print(publisherHostObj.getTiers()); +print("=="); +print(publisherHostObj.getAllAPIs()); +print("=="); +print(publisherHostObj.getAPIsByProvider("admin")); +print("=="); +print(publisherHostObj.getSubscribersOfAPI("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.isContextExist("HostObjectTestAPI","HostObjectTestAPI")); +print("=="); +print(publisherHostObj.searchAPIs("admin","name:HostObjectTestAPI")); +print("=="); +print(publisherHostObj.hasCreatePermission()); +print("=="); +print(publisherHostObj.hasManageTierPermission()); +print("=="); +print(publisherHostObj.hasUserPermissions("admin")); +print("=="); +print(publisherHostObj.hasPublishPermission("admin")); +print("=="); +print(publisherHostObj.getAuthServerURL()); +print("=="); +print(publisherHostObj.getCustomInSequences()); +print("=="); +print(publisherHostObj.getCustomOutSequences()); +print("=="); +print(publisherHostObj.getHTTPsURL()); +print("=="); +print(publisherHostObj.isSynapseGateway()); +print("=="); +print(publisherHostObj.loadRegistryOfTenant("carbon.super")); +print("=="); +print(publisherHostObj.updateDocumentation("admin","HostObjectTestAPI","1.0.0","Doc-Name", "How To", "summary","In-line")); +print("=="); +print(publisherHostObj.addInlineContent("admin","HostObjectTestAPI","1.0.0","help","this is helpe")); +print("=="); +print(publisherHostObj.getInlineContent("admin","HostObjectTestAPI","1.0.0","help")); +print("=="); +print(publisherHostObj.getAllDocumentation("admin@carbon.super","HostObjectTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.searchAccessTokens("*:*")); +print("=="); +print(publisherHostObj.getSubscriberCountByAPIs("admin@carbon.super")); +print("=="); +print(publisherHostObj.getSubscriberCountByAPIVersions("admin@carbon.super")); +print("=="); +print(publisherHostObj.getExternalAPIStores()); +print("=="); +var apiData = {}; +apiData["provider"] = "admin"; +apiData["name"] = "HostObjectTestAPI"; +apiData["version"] = "1.0.0"; +apiData["apiName"] = "HostObjectTestAPI"; +print(publisherHostObj.isAPIOlderVersionExist(apiData)); +print("=="); +print(publisherHostObj.updateSubscriptionStatus(apiData,"BLOCKED","1")); +print("=="); + +var tierData = {}; +tierData["tierName"] = "Gold"; +tierData["permissiontype"] = "Deny"; +tierData["roles"] = "admin"; +print(publisherHostObj.updateTierPermissions(tierData)); +print("=="); +//print(publisherHostObj.updateExternalAPIStores(apiData)); +//print(publisherHostObj.createNewAPIVersion("admin","HostObjectTestAPI","1.0.0","1.0.1")); +//print(publisherHostObj.searchAccessTokens("admin")); +//print(publisherHostObj.getSubscriberCountByAPIVersions()); +var apiData1 = {}; +apiData1["provider"] = "admin"; +apiData1["name"] = "HostObjectTestAPI"; +apiData1["version"] = "1.0.0"; +apiData1["apiName"] = "HostObjectTestAPI"; +//print(publisherHostObj.updateExternalAPIStores(apiData1)); +%> \ No newline at end of file diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/jaggery/testStore.jag b/modules/integration/tests-new/src/test/resources/artifacts/AM/jaggery/testStore.jag new file mode 100644 index 0000000000..3c307b619e --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/jaggery/testStore.jag @@ -0,0 +1,93 @@ +<% +<% +//Order of these operations are important as we fetch results based on order + //If you add new test add them to bottom of this file and update validate response method + //available in host object test class +store = require('apistore'); +var storeHostObj = new store.APIStore("admin"); +print("=="); +print(storeHostObj.isBillingEnabled()); +print("=="); +print(storeHostObj.getHTTPsURL("localhost")); +print("=="); +print(storeHostObj.getAuthServerURL()); +print("=="); +print(storeHostObj.getHTTPURL("localhost")); +print("=="); +print(storeHostObj.getDeniedTiers()); +print("=="); +print(storeHostObj.getActiveTenantDomains()); +print("=="); +print(storeHostObj.isSelfSignupEnabled()); +print("=="); +print(storeHostObj.getUserFields()); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("HostObjectTestAPI","carbon.super","0","10")); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("name:*","carbon.super","0","10")); +print("=="); +print(storeHostObj.searchAPIbyType("name:*","carbon.super")); +print("=="); +print(storeHostObj.searchAPIbyType("HostObjectTestAPI","carbon.super")); +print("=="); +print(storeHostObj.getPaginatedAPIsWithTag("youtube","0","10")); +print("=="); +print(storeHostObj.getPublishedAPIsByProvider("admin@carbon.super","admin")); +print("=="); +print(storeHostObj.getAllSubscriptions("admin@carbon.super")); +print("=="); +print(storeHostObj.rateAPI("admin","HostObjectTestAPI","1.0.0","3")); +print("=="); +print(storeHostObj.removeAPIRating("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(storeHostObj.getAllPaginatedPublishedAPIs("carbon.super","0","10")); +print("=="); +print(storeHostObj.getAPIsWithTag("youtube")); +print("=="); +print(storeHostObj.getAllPublishedAPIs("carbon.super")); +print("=="); +print(storeHostObj.getComments("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(storeHostObj.isUserExists("admin")); +print("=="); +print(storeHostObj.getAPI("admin","HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.isSubscribed("admin","HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.getSubscriptions("admin","HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.getSubscribedAPIs("3")); +print("=="); +print(storeHostObj.hasUserPermissions("admin")); +print("=="); +print(storeHostObj.getTiers("admin")); +print("=="); +print(storeHostObj.getAPIUsageforSubscriber("admin")); +print("=="); +print(storeHostObj.getDeniedTiers("admin")); +print("=="); +print(storeHostObj.getRecentlyAddedAPIs("5","carbon.super")); +print("=="); +print(storeHostObj.getTopRatedAPIs("5")); +print("=="); +print(storeHostObj.isBillingEnabled()); +print("=="); +print(storeHostObj.hasSubscribePermission()); +print("=="); +print(storeHostObj.isEnableEmailUsername()); +print("=="); +print(storeHostObj.updateApplicationTier("DefaultApplication","gold","admin")); +print("=="); +print(storeHostObj.updateApplication("DefaultApplicationTest","DefaultApplication","admin","gold","test-url","updated-application")); +print("=="); +print(storeHostObj.validateWFPermission("Basic YWRtaW46YWRtaW4=")); +print("=="); +print(storeHostObj.getSwaggerDiscoveryUrl("HostObjectTestAPI","1.0.0","admin")); +print("=="); +//print(storeHostObj.removeSubscriber("admin","HostObjectTestAPI","1.0.0","DefaultApplication","1")); +//print(storeHostObj.removeSubscription("admin","HostObjectTestAPI","1.0.0","DefaultApplication","1")); +//print(storeHostObj.rateAPI("admin","HostObjectTestAPI","1.0.0","3")); +//print("=="); +//print(storeHostObj.getTopRatedAPIs("3")); +%> +%> \ No newline at end of file diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/jaggery/testUsageWithBAM.jag b/modules/integration/tests-new/src/test/resources/artifacts/AM/jaggery/testUsageWithBAM.jag new file mode 100644 index 0000000000..e43384478b --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/jaggery/testUsageWithBAM.jag @@ -0,0 +1,36 @@ +<% +//Order of these operations are important as we fetch results based on order. +//If you add new test add them to bottom of this file and update validate response method +//available in host object test class. +var publisher = require('apipublisher'); +var publisherHostObj = new publisher.APIProvider("admin"); +print("=="); +print(publisherHostObj.getAPIUsageforSubscriber("admin")); +print("=="); +print(publisherHostObj.getAPIFaultyAnalyzeByTime("admin")); +print("=="); +var start=new Date(); +start.setFullYear(2014,0,14); +var end = new Date(); +end.setFullYear(2015,0,14); +print(publisherHostObj.getAPIResponseFaultCount("admin",start,end)); +print("=="); +print(publisherHostObj.getAPIUsageByResourcePath("admin",start,end)); +print("=="); +print(publisherHostObj.getAPIUsageByUser("admin",start,end)); +print("=="); +print(publisherHostObj.getAllAPIUsageByProvider("admin")); +print("=="); +print(publisherHostObj.getFirstAccessTime("admin")); +print("=="); +print(publisherHostObj.getProviderAPIServiceTime("admin",start,end)); +print("=="); +print(publisherHostObj.getProviderAPIUsage("admin","UsageTestAPI")); +print("=="); +print(publisherHostObj.getProviderAPIVersionUsage("admin","UsageTestAPI")); +print("=="); +print(publisherHostObj.getProviderAPIVersionUserUsage("admin","UsageTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.getProviderAPIVersionUserLastAccess("admin",start,end)); +print("=="); +%> \ No newline at end of file diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/API_Manager_Login_Test.jmx b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/API_Manager_Login_Test.jmx new file mode 100644 index 0000000000..6e46aeeaee --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/API_Manager_Login_Test.jmx @@ -0,0 +1,356 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + Youtube + = + + + context + /youtube + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + Tester_Acc2 + = + + + publisherName + admin + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://localhost:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + 200 + + Assertion.response_code + false + 2 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/aggregate_report.jtl + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + + + + diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest.jmx b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest.jmx new file mode 100644 index 0000000000..0852fe5dd7 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest.jmx @@ -0,0 +1,2902 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + GOOG_Stock_API + = + + + context + /GStock + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + userPrefix + tenant + = + + + resourceMethods + POST + = + + + authTypes + Application & Application User + = + + + throttlingTiers + Unlimited + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_number + # + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <ser:getTenant> + <!--Optional:--> + <ser:tenantDomain>domain${tenant_number}.com</ser:tenantDomain> + </ser:getTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:getTenant + true + false + + + + undefined + tenant_exists + //*[local-name()='active']/text() + false + false + true + tenant_exists + + + + false + true + true + false + + + + + ${tenant_exists}==false + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org" xmlns:xsd="http://beans.common.stratos.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <ser:addTenant> + <!--Optional:--> + <ser:tenantInfoBean> + <!--Optional:--> + <xsd:active>1</xsd:active> + <!--Optional:--> + <xsd:admin>${userPrefix}${tenant_number}</xsd:admin> + <!--Optional:--> + <xsd:adminPassword>1qaz2wsx@</xsd:adminPassword> + <!--Optional:--> + <xsd:createdDate>2013-02-22T08:22:54</xsd:createdDate> + <!--Optional:--> + <xsd:email>ruwany@wso2.com</xsd:email> + <!--Optional:--> + <xsd:firstname>User1</xsd:firstname> + <!--Optional:--> + <xsd:lastname>LastName1</xsd:lastname> + <!--Optional:--> + <xsd:tenantDomain>domain${tenant_number}.com</xsd:tenantDomain> + <!--Optional:--> + <xsd:tenantId>0</xsd:tenantId> + <!--Optional:--> + <xsd:usagePlan>Demo</xsd:usagePlan> + </ser:tenantInfoBean> + </ser:addTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:addTenant + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + 202 + + Assertion.response_code + false + 1 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + + 1363957740000 + 1363957740000 + false + + + + + + + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_counter + # + false + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>${userPrefix}${tenant_counter}@domain${tenant_counter}.com</aut:username> + <!--Optional:--> + <aut:password>1qaz2wsx@</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <xsd:getAllRolesNames> + <!--Optional:--> + <xsd:filter>*</xsd:filter> + <!--Optional:--> + <xsd:limit>100</xsd:limit> + </xsd:getAllRolesNames> + </soapenv:Body> +</soapenv:Envelope> + + urn:getAllRolesNames + true + false + + + + undefined + role_exists + //*[local-name()='itemName']/text()='subscriber_role' + false + false + true + + + + false + true + true + false + + + + + ${role_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addRole> + <!--Optional:--> + <mgt:roleName>subscriber_role</mgt:roleName> + <mgt:permissions>/permission/admin/login</mgt:permissions> + <mgt:permissions>/permission/admin/manage/api/subscribe</mgt:permissions> + <mgt:isSharedRole>false</mgt:isSharedRole> + </mgt:addRole> + </soapenv:Body> +</soapenv:Envelope> + + urn:addRole + true + false + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + user_ref + # + false + + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:listUsers> + <!--Optional:--> + <mgt:filter>${userPrefix}${tenant_counter}_user${user_ref}</mgt:filter> + <mgt:limit>10</mgt:limit> + </mgt:listUsers> + </soapenv:Body> +</soapenv:Envelope> + + urn:listUsers + true + false + + + + false + user_exists + //*[local-name()='return']/text()='${userPrefix}${tenant_counter}_user${user_ref}' + false + false + true + + + + false + true + true + false + + + + + ${user_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd" xmlns:xsd="http://common.mgt.user.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addUser> + <!--Optional:--> + <mgt:userName>${userPrefix}${tenant_counter}_user${user_ref}</mgt:userName> + <!--Optional:--> + <mgt:password>1qaz2wsx@</mgt:password> + <mgt:roles>subscriber_role</mgt:roles> + </mgt:addUser> + </soapenv:Body> +</soapenv:Envelope> + + urn:addUser + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy_report.jtl + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + String currentDir = System.getProperty("user.dir"); +FileOutputStream f = new FileOutputStream(currentDir + "/results.csv"); + + + false + + + + + + false + rfc2109 + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}@domain${input_value}.com + = + true + username + + + false + ${publisherPass} + = + true + password + + + false + null + = + true + tenant + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${numberOfAPIs} + + + + 1 + ${numberOfAPIs} + 1 + api_id + # + false + + + + + + + false + addAPI + = + true + action + + + false + ${apinm}${api_id} + = + true + name + + + false + ${context}${api_id} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + /* + = + true + uriTemplate-0 + + + false + ${resourceMethods} + = + true + resourceMethod-0 + + + false + ${authTypes} + = + true + resourceMethodAuthType-0 + + + false + ${throttlingTiers} + = + true + resourceMethodThrottlingTier-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + http + = + true + http_checked + + + false + https + = + true + https_checked + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm}${api_id} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + false + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${numberOfAPIs} + + + + 1 + ${numberOfAPIs} + 1 + api_id + # + false + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm}${api_id} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + Unlimited + = + true + tier + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com&password=1qaz2wsx@&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + +String tenant_count = vars.get("input_value"); +String user_count = vars.get("subsCount"); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + +String currentDir = System.getProperty("user.dir"); + +vars.put("current_directory" , currentDir); + +String context = vars.get("context"); +String apiID = vars.get("api_id"); + +f = new FileOutputStream(currentDir + "/results.csv", true); + +p = new PrintStream(f); + +this.interpreter.setOut(p); + +print("domain"+ tenant_count+".com" + "@@@" + accessToken +"@@@" + context+apiID); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + /t/domain${input_value}.com${context}${api_id}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getAllPublishedAPIs + = + true + action + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/api/listing/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + true + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getRecentlyAddedAPIs + = + true + action + + + false + 2000 + = + true + limit + + + false + domain1.com + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + store/site/blocks/api/recently-added/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getAllTags + = + true + action + + + + ${storeIP} + ${storePort} + + + + + store/site/blocks/tag/tag-cloud/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 10 + 1 + 1365001797000 + 1365001797000 + false + + + + + + + + import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.LineNumberReader; + +String currentDir = System.getProperty("user.dir"); + +LineNumberReader lnr = new LineNumberReader(new FileReader(new File(currentDir + "/results.csv"))); +lnr.skip(Long.MAX_VALUE); + +int min = 1; +int max = lnr.getLineNumber(); + +Random r = new Random(); +int i1 = r.nextInt(max - min + 1) + min; + +vars.put("random_value",""+i1); + +String lineConcerened = ""; + +BufferedReader br = new BufferedReader(new FileReader(new File(currentDir + "/results.csv"))); + +String strLine =""; + +for(int i=0; i<max; i++){ + strLine = br.readLine(); + if(i==i1-1){ + System.out.println(strLine); + lineConcerened = strLine; + } +} + +String[] splitVals = lineConcerened.split("@@@"); +String userName = splitVals[0]; +String token = splitVals[1]; +String contextAndAPIId = splitVals[2]; + +vars.put("line_count",""+i1); +vars.put("domain",userName); +vars.put("token",token); +vars.put("contextAndAPIId",contextAndAPIId); + + + false + + + + false + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + /t/${domain}${contextAndAPIId}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${token} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + false + true + true + false + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/aggregate_report.jtl + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + + + + diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest_new_tenant.jmx b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest_new_tenant.jmx new file mode 100644 index 0000000000..eb187dda28 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest_new_tenant.jmx @@ -0,0 +1,2671 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + GOOG_Stock_API_New + = + + + context + /GStocknew + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + userPrefix + tenant + = + + + resourceMethods + POST + = + + + authTypes + Application & Application User + = + + + throttlingTiers + Unlimited + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_number + # + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <ser:getTenant> + <!--Optional:--> + <ser:tenantDomain>domain${tenant_number}.com</ser:tenantDomain> + </ser:getTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:getTenant + true + false + + + + undefined + tenant_exists + //*[local-name()='active']/text() + false + false + true + tenant_exists + + + + false + true + true + false + + + + + ${tenant_exists}==false + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org" xmlns:xsd="http://beans.common.stratos.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <ser:addTenant> + <!--Optional:--> + <ser:tenantInfoBean> + <!--Optional:--> + <xsd:active>1</xsd:active> + <!--Optional:--> + <xsd:admin>${userPrefix}${tenant_number}</xsd:admin> + <!--Optional:--> + <xsd:adminPassword>1qaz2wsx@</xsd:adminPassword> + <!--Optional:--> + <xsd:createdDate>2013-02-22T08:22:54</xsd:createdDate> + <!--Optional:--> + <xsd:email>ruwany@wso2.com</xsd:email> + <!--Optional:--> + <xsd:firstname>User1</xsd:firstname> + <!--Optional:--> + <xsd:lastname>LastName1</xsd:lastname> + <!--Optional:--> + <xsd:tenantDomain>domain${tenant_number}.com</xsd:tenantDomain> + <!--Optional:--> + <xsd:tenantId>0</xsd:tenantId> + <!--Optional:--> + <xsd:usagePlan>Demo</xsd:usagePlan> + </ser:tenantInfoBean> + </ser:addTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:addTenant + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + 202 + + Assertion.response_code + false + 1 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + + 1363957740000 + 1363957740000 + false + + + + + + + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_counter + # + false + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>${userPrefix}${tenant_counter}@domain${tenant_counter}.com</aut:username> + <!--Optional:--> + <aut:password>1qaz2wsx@</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <xsd:getAllRolesNames> + <!--Optional:--> + <xsd:filter>*</xsd:filter> + <!--Optional:--> + <xsd:limit>100</xsd:limit> + </xsd:getAllRolesNames> + </soapenv:Body> +</soapenv:Envelope> + + urn:getAllRolesNames + true + false + + + + undefined + role_exists + //*[local-name()='itemName']/text()='subscriber_role_new' + false + false + true + + + + false + true + true + false + + + + + ${role_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addRole> + <!--Optional:--> + <mgt:roleName>subscriber_role_new</mgt:roleName> + <mgt:permissions>/permission/admin/login</mgt:permissions> + <mgt:permissions>/permission/admin/manage/api/subscribe</mgt:permissions> + <mgt:isSharedRole>false</mgt:isSharedRole> + </mgt:addRole> + </soapenv:Body> +</soapenv:Envelope> + + urn:addRole + true + false + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + user_ref + # + false + + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:listUsers> + <!--Optional:--> + <mgt:filter>${userPrefix}${tenant_counter}_user${user_ref}</mgt:filter> + <mgt:limit>10</mgt:limit> + </mgt:listUsers> + </soapenv:Body> +</soapenv:Envelope> + + urn:listUsers + true + false + + + + false + user_exists + //*[local-name()='return']/text()='${userPrefix}${tenant_counter}_user${user_ref}' + false + false + true + + + + false + true + true + false + + + + + ${user_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd" xmlns:xsd="http://common.mgt.user.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addUser> + <!--Optional:--> + <mgt:userName>${userPrefix}${tenant_counter}_user${user_ref}</mgt:userName> + <!--Optional:--> + <mgt:password>1qaz2wsx@</mgt:password> + <mgt:roles>subscriber_role_new</mgt:roles> + </mgt:addUser> + </soapenv:Body> +</soapenv:Envelope> + + urn:addUser + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy_report.jtl + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + String currentDir = System.getProperty("user.dir"); +FileOutputStream f = new FileOutputStream(currentDir + "/results.csv"); + + + false + + + + + + false + rfc2109 + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}@domain${input_value}.com + = + true + username + + + false + ${publisherPass} + = + true + password + + + false + null + = + true + tenant + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${numberOfAPIs} + + + + 1 + ${numberOfAPIs} + 1 + api_id + # + false + + + + + + + false + addAPI + = + true + action + + + false + ${apinm}${api_id} + = + true + name + + + false + ${context}${api_id} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + /* + = + true + uriTemplate-0 + + + false + ${resourceMethods} + = + true + resourceMethod-0 + + + false + ${authTypes} + = + true + resourceMethodAuthType-0 + + + false + ${throttlingTiers} + = + true + resourceMethodThrottlingTier-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + http + = + true + http_checked + + + false + https + = + true + https_checked + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm}${api_id} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + false + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${numberOfAPIs} + + + + 1 + ${numberOfAPIs} + 1 + api_id + # + false + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm}${api_id} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + Unlimited + = + true + tier + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com&password=1qaz2wsx@&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + +String tenant_count = vars.get("input_value"); +String user_count = vars.get("subsCount"); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + +String currentDir = System.getProperty("user.dir"); + +vars.put("current_directory" , currentDir); + +String context = vars.get("context"); +String apiID = vars.get("api_id"); + +f = new FileOutputStream(currentDir + "/results.csv", true); + +p = new PrintStream(f); + +this.interpreter.setOut(p); + +print("domain"+ tenant_count+".com" + "@@@" + accessToken +"@@@" + context+apiID); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + /t/domain${input_value}.com${context}${api_id}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getAllPublishedAPIs + = + true + action + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/api/listing/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + true + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getRecentlyAddedAPIs + = + true + action + + + false + 2000 + = + true + limit + + + false + domain1.com + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + store/site/blocks/api/recently-added/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getAllTags + = + true + action + + + + ${storeIP} + ${storePort} + + + + + store/site/blocks/tag/tag-cloud/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 10 + 1 + 1365001797000 + 1365001797000 + false + + + + + + + + import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.LineNumberReader; + +String currentDir = System.getProperty("user.dir"); + +LineNumberReader lnr = new LineNumberReader(new FileReader(new File(currentDir + "/results.csv"))); +lnr.skip(Long.MAX_VALUE); + +int min = 1; +int max = lnr.getLineNumber(); + +Random r = new Random(); +int i1 = r.nextInt(max - min + 1) + min; + +vars.put("random_value",""+i1); + +String lineConcerened = ""; + +BufferedReader br = new BufferedReader(new FileReader(new File(currentDir + "/results.csv"))); + +String strLine =""; + +for(int i=0; i<max; i++){ + strLine = br.readLine(); + if(i==i1-1){ + System.out.println(strLine); + lineConcerened = strLine; + } +} + +String[] splitVals = lineConcerened.split("@@@"); +String userName = splitVals[0]; +String token = splitVals[1]; +String contextAndAPIId = splitVals[2]; + +vars.put("line_count",""+i1); +vars.put("domain",userName); +vars.put("token",token); +vars.put("contextAndAPIId",contextAndAPIId); + + + false + + + + false + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + /t/${domain}${contextAndAPIId}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${token} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + false + true + true + false + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/DomainRestrictionTest.jmx b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/DomainRestrictionTest.jmx new file mode 100644 index 0000000000..55821fa75b --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/DomainRestrictionTest.jmx @@ -0,0 +1,1202 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + basic_functions_api_domain + = + + + context + /basic_functions_api_domain + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + super_tenant_user + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + https://lh6.ggpht.com/RNc8dD2hXG_rWGzlj09ZwAe1sXVvLWkeYT3ePx7zePCy4ZVV2XMGIxAzup4cKM85NFtL=w124 + = + true + apiThumb + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + POST + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Unlimited, Unlimited, Unlimited, Unlimited, Unlimited + = + true + resourceMethodThrottlingTier-0 + + + false + http + = + true + http_checked + + + false + https + = + true + https_checked + + + false + Application User + = + true + resourceMethodAuthType-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${noOfSubscribers} + + + + 1 + 10000 + 1 + subsCount + # + false + + + + + + + false + addUser + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + false + ${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}@test.com|| + = + true + allFieldsValues + + + false + + = + true + + + false + + = + true + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/sign-up/ajax/user-add.jag + POST + true + false + true + false + Java + false + + + + + 50 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//int eq = resp.indexOf("=", def - 8); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println("APP ID : " + appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + true + true + true + false + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + true + true + true + false + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + wso2.org + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + refreshToken + = + true + action + + + false + application + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${token} + = + true + oldAccessToken + + + false + ${consumerKey} + = + true + clientId + + + false + ${consumerSecret} + = + true + clientSecret + + + false + 5000 + = + true + validityTime + + + false + wso2.org + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${subsPrefix}_${subsCount}&password=subscriber@123&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + referer + wso2.org + + + + + + + 200 + + Assertion.response_data + false + 6 + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + + diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/basic_functionality_test.jmx b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/basic_functionality_test.jmx new file mode 100644 index 0000000000..dd959572bf --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/basic_functionality_test.jmx @@ -0,0 +1,1198 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + basic_functions_api + = + + + context + /basic_functions_api + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + super_tenant_user + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + https://lh6.ggpht.com/RNc8dD2hXG_rWGzlj09ZwAe1sXVvLWkeYT3ePx7zePCy4ZVV2XMGIxAzup4cKM85NFtL=w124 + = + true + apiThumb + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + POST + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Unlimited, Unlimited, Unlimited, Unlimited, Unlimited + = + true + resourceMethodThrottlingTier-0 + + + false + http + = + true + http_checked + + + false + https + = + true + https_checked + + + false + Application User + = + true + resourceMethodAuthType-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${noOfSubscribers} + + + + 1 + 10000 + 1 + subsCount + # + false + + + + + + + false + addUser + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + false + ${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}@test.com|| + = + true + allFieldsValues + + + false + + = + true + + + false + + = + true + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/sign-up/ajax/user-add.jag + POST + true + false + true + false + Java + false + + + + + 50 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//int eq = resp.indexOf("=", def - 8); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println("APP ID : " + appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + true + true + true + false + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + true + true + true + false + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + refreshToken + = + true + action + + + false + application + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${token} + = + true + oldAccessToken + + + false + ${consumerKey} + = + true + clientId + + + false + ${consumerSecret} + = + true + clientSecret + + + false + 5000 + = + true + validityTime + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${subsPrefix}_${subsCount}&password=subscriber@123&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + No data found + + Assertion.response_data + false + 6 + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + + diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/content_type_check_for_DELETE_script.jmx b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/content_type_check_for_DELETE_script.jmx new file mode 100644 index 0000000000..3b6fa90f65 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/content_type_check_for_DELETE_script.jmx @@ -0,0 +1,491 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + testContentTypeHeaderAPI + = + + + context + /testContentTypeHeaderAPI + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + + + + + false + rfc2109 + + + + + + + false + login + = + true + action + + + false + admin + = + true + username + + + false + admin + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + +System.out.println("####################################################################### Access Token Response: " + jsonResponse); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=admin&password=admin&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + false + ThisParamIsRequiredForTest_DELETE + = + true + param + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version}/ + DELETE + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/content_type_check_for_GET_script.jmx b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/content_type_check_for_GET_script.jmx new file mode 100644 index 0000000000..6385a2ed19 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/content_type_check_for_GET_script.jmx @@ -0,0 +1,498 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + testContentTypeHeaderAPI + = + + + context + /testContentTypeHeaderAPI + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + + + + + false + rfc2109 + + + + + + + false + login + = + true + action + + + false + admin + = + true + username + + + false + admin + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + false + 5600 + = + true + validityTime + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + +System.out.println("####################################################################### Access Token Response: " + jsonResponse); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=admin&password=admin&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + false + ThisParamIsRequiredForTest_GET + = + true + param + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version}/ + GET + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/content_type_check_publish_and_subscribe_script.jmx b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/content_type_check_publish_and_subscribe_script.jmx new file mode 100644 index 0000000000..f194dc87e4 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/content_type_check_publish_and_subscribe_script.jmx @@ -0,0 +1,665 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + testContentTypeHeaderAPI + = + + + context + /testContentTypeHeaderAPI + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + + + + + false + rfc2109 + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + 127.0.0.1:6789 + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + DELETE,GET + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + Application User,Application User + = + true + resourceMethodAuthType-0 + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Unlimited, Unlimited, Unlimited, Unlimited, Unlimited + = + true + resourceMethodThrottlingTier-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + admin + = + true + username + + + false + admin + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + admin + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//String appid = resp.substring(def+6, resp.indexOf("," )); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println("AppId: " + appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + 1.0.0 + = + true + version + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/tenant_create.jmx b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/tenant_create.jmx new file mode 100644 index 0000000000..976581f9ad --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/tenant_create.jmx @@ -0,0 +1,634 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + GOOG_Stock_API_New + = + + + context + /GStocknew + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + userPrefix + user + = + + + resourceMethods + POST + = + + + authTypes + Application & Application User + = + + + throttlingTiers + Unlimited + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_number + # + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <ser:getTenant> + <!--Optional:--> + <ser:tenantDomain>tenantdomain${tenant_number}.com</ser:tenantDomain> + </ser:getTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:getTenant + true + false + + + + undefined + tenant_exists + //*[local-name()='active']/text() + false + false + true + tenant_exists + + + + false + true + true + false + + + + + ${tenant_exists}==false + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org" xmlns:xsd="http://beans.common.stratos.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <ser:addTenant> + <!--Optional:--> + <ser:tenantInfoBean> + <!--Optional:--> + <xsd:active>1</xsd:active> + <!--Optional:--> + <xsd:admin>${userPrefix}${tenant_number}</xsd:admin> + <!--Optional:--> + <xsd:adminPassword>test123</xsd:adminPassword> + <!--Optional:--> + <xsd:createdDate>2013-02-22T08:22:54</xsd:createdDate> + <!--Optional:--> + <xsd:email>ruwany@wso2.com</xsd:email> + <!--Optional:--> + <xsd:firstname>User1</xsd:firstname> + <!--Optional:--> + <xsd:lastname>LastName1</xsd:lastname> + <!--Optional:--> + <xsd:tenantDomain>tenantdomain${tenant_number}.com</xsd:tenantDomain> + <!--Optional:--> + <xsd:tenantId>0</xsd:tenantId> + <!--Optional:--> + <xsd:usagePlan>Demo</xsd:usagePlan> + </ser:tenantInfoBean> + </ser:addTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:addTenant + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + 202 + + Assertion.response_code + false + 1 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + + 1363957740000 + 1363957740000 + false + + + + + + + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_counter + # + false + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>${userPrefix}${tenant_counter}@tenantdomain${tenant_counter}.com</aut:username> + <!--Optional:--> + <aut:password>test123</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <xsd:getAllRolesNames> + <!--Optional:--> + <xsd:filter>*</xsd:filter> + <!--Optional:--> + <xsd:limit>100</xsd:limit> + </xsd:getAllRolesNames> + </soapenv:Body> +</soapenv:Envelope> + + urn:getAllRolesNames + true + false + + + + undefined + role_exists + //*[local-name()='itemName']/text()='subscriber_role_new' + false + false + true + + + + false + true + true + false + + + + + ${role_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addRole> + <!--Optional:--> + <mgt:roleName>subscriber_role_new</mgt:roleName> + <mgt:permissions>/permission/admin/login</mgt:permissions> + <mgt:permissions>/permission/admin/manage/api/subscribe</mgt:permissions> + <mgt:isSharedRole>false</mgt:isSharedRole> + </mgt:addRole> + </soapenv:Body> +</soapenv:Envelope> + + urn:addRole + true + false + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + user_ref + # + false + + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:listUsers> + <!--Optional:--> + <mgt:filter>${userPrefix}${tenant_counter}_user${user_ref}</mgt:filter> + <mgt:limit>10</mgt:limit> + </mgt:listUsers> + </soapenv:Body> +</soapenv:Envelope> + + urn:listUsers + true + false + + + + false + user_exists + //*[local-name()='return']/text()='${userPrefix}${tenant_counter}_user${user_ref}' + false + false + true + + + + false + true + true + false + + + + + ${user_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd" xmlns:xsd="http://common.mgt.user.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addUser> + <!--Optional:--> + <mgt:userName>${userPrefix}${tenant_counter}_user${user_ref}</mgt:userName> + <!--Optional:--> + <mgt:password>1qaz2wsx@</mgt:password> + <mgt:roles>subscriber_role_new</mgt:roles> + </mgt:addUser> + </soapenv:Body> +</soapenv:Envelope> + + urn:addUser + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy_report.jtl + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/transport_restriction_check.jmx b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/transport_restriction_check.jmx new file mode 100644 index 0000000000..f45a4bcbe8 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/scripts/transport_restriction_check.jmx @@ -0,0 +1,1135 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + restricted_api + = + + + context + restricted_api + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + transport_users + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + https://lh6.ggpht.com/RNc8dD2hXG_rWGzlj09ZwAe1sXVvLWkeYT3ePx7zePCy4ZVV2XMGIxAzup4cKM85NFtL=w124 + = + true + apiThumb + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + POST + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Unlimited, Unlimited, Unlimited, Unlimited, Unlimited + = + true + resourceMethodThrottlingTier-0 + + + false + + = + true + http_checked + + + false + https + = + true + https_checked + + + false + Application User + = + true + resourceMethodAuthType-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${noOfSubscribers} + + + + 1 + 10000 + 1 + subsCount + # + false + + + + + + + false + addUser + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + false + ${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}@test.com|| + = + true + allFieldsValues + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/sign-up/ajax/user-add.jag + POST + true + false + true + false + Java + false + + + + + 50 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//int eq = resp.indexOf("=", def - 8); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + 1.0.0 + = + true + version + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${subsPrefix}_${subsCount}&password=subscriber@123&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + http + + ${context}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + Unsupported Transport + + Assertion.response_data + true + 2 + + + + + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + ${context}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml b/modules/integration/tests-new/src/test/resources/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml new file mode 100644 index 0000000000..4e06ac5885 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml @@ -0,0 +1,271 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $1 + Status report + Runtime Error + $2 + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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. + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + The default main sequence for API manager - Returns 404 Not Found + + + + + + + + + + + + + + + + 30000 + fault + + + -1 + 0 + 1.0 + 0 + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30000 + fault + + + -1 + 0 + 1.0 + 0 + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/synapseconfigs/property/placeOrder.xml b/modules/integration/tests-new/src/test/resources/artifacts/AM/synapseconfigs/property/placeOrder.xml new file mode 100644 index 0000000000..de239abdb6 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/synapseconfigs/property/placeOrder.xml @@ -0,0 +1,7 @@ + + + 50 + 10 + IBM + + \ No newline at end of file diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/synapseconfigs/rest/url-mapping-synapse.xml b/modules/integration/tests-new/src/test/resources/artifacts/AM/synapseconfigs/rest/url-mapping-synapse.xml new file mode 100644 index 0000000000..a29656ba16 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/synapseconfigs/rest/url-mapping-synapse.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + +
    + + + + + + + 4.212070096051944 + -9.567415587431361 + -148.1740146577308 + IBM + + + + + + + + + + + + + diff --git a/modules/integration/tests-new/src/test/resources/artifacts/AM/synapseconfigs/throttling/throttling-api-synapse.xml b/modules/integration/tests-new/src/test/resources/artifacts/AM/synapseconfigs/throttling/throttling-api-synapse.xml new file mode 100644 index 0000000000..8e4f3c60b7 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/artifacts/AM/synapseconfigs/throttling/throttling-api-synapse.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + +
    + + + + + + + 4.212070096051944 + -9.567415587431361 + -148.1740146577308 + IBM + + + + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests-new/src/test/resources/automation.xml b/modules/integration/tests-new/src/test/resources/automation.xml new file mode 100755 index 0000000000..199a32143e --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/automation.xml @@ -0,0 +1,274 @@ + + + + + + + + + 60000 + + standalone + + true + + false + + + + + + + http://10.100.2.51:4444/wd/hub/ + + + + firefox + + /home/test/name/webDriver + + + + + + + jdbc:h2:testDB + wso2carbon + wso2carbon + org.h2.Driver + + + jdbc:h2:testDB + wso2carbon + wso2carbon + org.h2.Driver + + + + + + + keystores/products/wso2carbon.jks + + JKS + + wso2carbon + + wso2carbon + + wso2carbon + + + + + client-truststore.jks + + JKS + + wso2carbon + + + + + + https://wso2.org/repo + file:///home/krishantha/test + + + + + + + + + + admin + admin + + + + + testuser11 + testuser11 + + + testuser21 + testuser21 + + + + + + + + + admin + admin + + + + + testuser11 + testuser11 + + + testuser21 + testuser21 + + + + + + + + + + + + + + localhost + + + 9763 + 9443 + + + + + + localhost + + + 9763 + 9443 + + + + http://localhost:8280 + + + + + + + + + + + + + + + org.wso2.carbon.automation.extensions.servers.carbonserver.CarbonServerExtension + + + org.wso2.carbon.automation.extensions.usermgt.UserPopulateExtension + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-new/src/test/resources/automationXMLSchema.xsd b/modules/integration/tests-new/src/test/resources/automationXMLSchema.xsd new file mode 100644 index 0000000000..42c5fe8c16 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/automationXMLSchema.xsd @@ -0,0 +1,498 @@ + + + + + + + ================================================= + Parameters ================================================= + Browser type with used by framework to execute UI test, supported types + - chrome|firefox|opera|ie|htmlUnit + + + + + + + Change this to edit wait time for test + artifact deployment + + + + + + Change this to product|platform/cloud to + execute test on specific environment + + + + + + + Change this to true if you want to generate + coverage statistics + + + + + + Change this to true if you want to enable + framework dashboard + + + + + + + + + + + + + + + Change to enable remote webDriver + URL of remote webDriver server + + + + + + + + + + + + + Type of the browser selenium tests + are running" + + + + + + + + path to webDriver + executable - required only for + chrome + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + KeyStore which will be used for + encrypting/decrypting passwords + and other sensitive information. + + + + + + + Keystore file location + + + + + + Keystore type (JKS/PKCS12 etc.) + + + + + + Keystore password + + + + + + Private Key alias + + + + + + Private Key password + + + + + + + + + + System wide trust-store which is used to + maintain the certificates of all + the trusted parties. + + + + + + + trust-store file location + + + + + + trust-store type (JKS/PKCS12 + etc.) + + + + + + trust-store password + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-new/src/test/resources/axis2config/axis2_client.xml b/modules/integration/tests-new/src/test/resources/axis2config/axis2_client.xml new file mode 100644 index 0000000000..db07954a47 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/axis2config/axis2_client.xml @@ -0,0 +1,299 @@ + + + + + + + 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/integration/tests-new/src/test/resources/client/modules/addressing-1.6.1-wso2v10.mar b/modules/integration/tests-new/src/test/resources/client/modules/addressing-1.6.1-wso2v10.mar new file mode 100644 index 0000000000..57f8576425 Binary files /dev/null and b/modules/integration/tests-new/src/test/resources/client/modules/addressing-1.6.1-wso2v10.mar differ diff --git a/modules/integration/tests-new/src/test/resources/client/modules/addressing-1.6.1-wso2v9.mar b/modules/integration/tests-new/src/test/resources/client/modules/addressing-1.6.1-wso2v9.mar new file mode 100644 index 0000000000..d3871a1586 Binary files /dev/null and b/modules/integration/tests-new/src/test/resources/client/modules/addressing-1.6.1-wso2v9.mar differ diff --git a/modules/integration/tests-new/src/test/resources/emma.properties b/modules/integration/tests-new/src/test/resources/emma.properties new file mode 100644 index 0000000000..1d53a533c6 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/emma.properties @@ -0,0 +1,103 @@ +# ------------------------------------------------------------- +# +# for user-editable property overrides use one of these options: +# +# (1) option-specific command line overrides, e.g. +# -Dreport.txt.out.file=coverage.txt +# +# (2) '-p ' command line option, +# +# (3) 'emma.properties' resource placed somewhere in the classpath +# (e.g., in \classes directory -- note that it does +# not exist by default), +# +# (4) '-Demma.*' JVM options, e.g. +# -Demma.report.txt.out.file=coverage.txt +# +# (5) 'emma.properties' JVM option pointing to a properties file +# -Demma.properties=./myproperties.txt +# ------------------------------------------------------------- + +# ------------------------------------------------------------- +# logging properties: + +verbosity.level: none + +# classloading properties: + +#clsload.forced_delegation_filter: +#clsload.through_delegation_filter: -* + +# ------------------------------------------------------------- + +# instrumentation properties: + +instr.exclude_empty_classes: true +instr.exclude_synthetic_methods: true +instr.exclude_bridge_methods: true +instr.do_suid_compensation: true + +# ------------------------------------------------------------- + +# runtime properties: + +rt.control: false +rt.control.host: localhost +rt.control.port: 44444 + +rt.filelock: true +rt.filelock.portbase: 59141 +rt.filelock.maxtime: 120000 +rt.filelock.retries: 11 + +# ------------------------------------------------------------- + +# apprunner session data output properties: + +session.out.file: coverage.es +session.out.merge: true + +# ------------------------------------------------------------- + +# runtime coverage data output properties: + +coverage.out.file: coverage.ec +coverage.out.merge: true + +# ------------------------------------------------------------- + +# instr metadata output properties: + +metadata.out.file: coverage.em +metadata.out.merge: true + +# ------------------------------------------------------------- + +# common report defaults: + +report.units: instr +report.depth: method +report.columns: name, line, block, method, class +report.sort: -line,-block,-method,-class,+name +report.metrics: method:40,block:80,line:40,class:100 + +# ------------------------------------------------------------- +# txt report properties: + +report.txt.depth: all +report.txt.columns: class,method,block,line,name +report.txt.out.file: coverage.txt + +# ------------------------------------------------------------- +# html report properties: + +#report.html.out.dir: coverage +report.html.out.encoding: ISO-8859-1 + +# ------------------------------------------------------------- +# xml report properties: + +#report.xml.out.file: coverage.xml +report.xml.out.encoding: UTF-8 +# ------------------------------------------------------------- +# end of file diff --git a/modules/integration/tests-new/src/test/resources/keystores/products/client-truststore.jks b/modules/integration/tests-new/src/test/resources/keystores/products/client-truststore.jks new file mode 100644 index 0000000000..be441f378e Binary files /dev/null and b/modules/integration/tests-new/src/test/resources/keystores/products/client-truststore.jks differ diff --git a/modules/integration/tests-new/src/test/resources/keystores/products/wso2carbon.jks b/modules/integration/tests-new/src/test/resources/keystores/products/wso2carbon.jks new file mode 100644 index 0000000000..7942c53cf9 Binary files /dev/null and b/modules/integration/tests-new/src/test/resources/keystores/products/wso2carbon.jks differ diff --git a/modules/integration/tests-new/src/test/resources/testng-server-mgt.xml b/modules/integration/tests-new/src/test/resources/testng-server-mgt.xml new file mode 100644 index 0000000000..5ae1d8571c --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/testng-server-mgt.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests-new/src/test/resources/testng.xml b/modules/integration/tests-new/src/test/resources/testng.xml new file mode 100644 index 0000000000..310715f320 --- /dev/null +++ b/modules/integration/tests-new/src/test/resources/testng.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests-ui/pom.xml b/modules/integration/tests-ui/pom.xml new file mode 100644 index 0000000000..2660765362 --- /dev/null +++ b/modules/integration/tests-ui/pom.xml @@ -0,0 +1,266 @@ + + + + org.wso2.am + integration + 1.7.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + WSO2 API Manager - Integration UI Test Module + org.wso2.carbon.am.integration.ui + jar + + + + + maven-surefire-plugin + false + 2.12.4 + + + -Xmx1024m -XX:PermSize=256m -XX:MaxPermSize=512m + + + src/test/resources/testng-server-mgt.xml + + + + + + maven.test.haltafterfailure + false + + + carbon.zip + + ${basedir}/../../distribution/product/target/wso2am-${project.version}.zip + + + + framework.resource.location + + ${basedir}/src/test/resources/ + + + + server.list + + AM + + + + usedefaultlisteners + false + + ${basedir}/target/security-verifier/ + ${basedir}/target/emma + ${basedir}/src/test/resources/instrumentation.txt + ${basedir}/src/test/resources/filters.txt + ${basedir}/target/emma + + ${basedir}/target + + + + maven-dependency-plugin + + + + copy-emma-dependencies + compile + + copy-dependencies + + + ${project.build.directory}/emma + jar + emma,org.wso2.carbon.automation.core + + + + + + copy-secVerifier + compile + + copy-dependencies + + + ${basedir}/target/security-verifier + aar + SecVerifier + true + + + + + unpack-mar-jks + compile + + unpack + + + + + org.wso2.am + wso2am + ${project.version} + zip + true + ${basedir}/target/tobeCopied/ + **/*.jks,**/*.mar,**/axis2_client.xml + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + + test-jar + + + + + + org.apache.maven.plugins + maven-surefire-report-plugin + 2.7.1 + + ${basedir}/target/report + registry-api-test + + + + integration-test + + report-only + + + + + + + maven-resources-plugin + 2.6 + + + copy-resources-jks + compile + + copy-resources + + + ${basedir}/src/test/resources/keystores/products + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/resources/security/ + + + **/*.jks + + + + + + + copy-axis2files + compile + + copy-resources + + + ${basedir}/src/test/resources/axis2config + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/conf/axis2/ + + + **/*.xml + + + + + + + copy-resources-mar + compile + + copy-resources + + + ${basedir}/src/test/resources/client/modules + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/deployment/client/modules + + + **/*.mar + + + + + + + + + + + + + emma + emma + ${emma.version} + + + org.wso2.carbon + SecVerifier + ${carbon.platform.version} + aar + + + org.wso2.carbon.automation + org.wso2.carbon.automation.api + ${test-automation-framework-version} + + + org.wso2.carbon.automation + org.wso2.carbon.automation.core + ${test-automation-framework-version} + + + org.wso2.carbon.automation + org.wso2.carbon.automation.utils + ${test-automation-framework-version} + + + org.wso2.carbon.automation + org.wso2.carbon.automation.tools.jmeter + ${test-automation-framework-version} + + + org.testng + testng + 6.1.1 + test + + + + ${carbon.platform.version} + + diff --git a/modules/integration/tests-ui/src/test/java/org/wso2/carbon/am/integration/ui/AMIntegrationUiTestBase.java b/modules/integration/tests-ui/src/test/java/org/wso2/carbon/am/integration/ui/AMIntegrationUiTestBase.java new file mode 100644 index 0000000000..a615f36191 --- /dev/null +++ b/modules/integration/tests-ui/src/test/java/org/wso2/carbon/am/integration/ui/AMIntegrationUiTestBase.java @@ -0,0 +1,64 @@ +/* +*Copyright (c) 2005-2010, 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.carbom.am.integration.ui; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.automation.core.utils.UserInfo; +import org.wso2.carbon.automation.core.utils.UserListCsvReader; +import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentBuilder; +import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentVariables; +import org.wso2.carbon.automation.core.utils.environmentutils.ProductUrlGeneratorUtil; + +public class AMIntegrationUiTestBase { + + private static final Log log = LogFactory.getLog(AMIntegrationUiTestBase.class); + protected EnvironmentVariables amServer; + protected UserInfo userInfo; + + protected void init() throws Exception { + int userId = 2; + userInfo = UserListCsvReader.getUserInfo(userId); + EnvironmentBuilder builder = new EnvironmentBuilder().am(userId); + amServer = builder.build().getAm(); + } + + protected void init(int userId) throws Exception { + userInfo = UserListCsvReader.getUserInfo(userId); + EnvironmentBuilder builder = new EnvironmentBuilder().am(userId); + amServer = builder.build().getAm(); + } + + protected void cleanup() { + userInfo = null; + amServer = null; + } + + protected String getLoginURL(String productName) { + EnvironmentBuilder environmentBuilder = new EnvironmentBuilder(); + boolean isRunningOnStratos = + environmentBuilder.getFrameworkSettings().getEnvironmentSettings().is_runningOnStratos(); + + if (isRunningOnStratos) { + return ProductUrlGeneratorUtil.getServiceHomeURL(productName); + } else { + return ProductUrlGeneratorUtil.getProductHomeURL(productName); + } + } +} diff --git a/modules/integration/tests-ui/src/test/java/org/wso2/carbon/am/integration/ui/LoginTestCase.java b/modules/integration/tests-ui/src/test/java/org/wso2/carbon/am/integration/ui/LoginTestCase.java new file mode 100644 index 0000000000..b72a821e1b --- /dev/null +++ b/modules/integration/tests-ui/src/test/java/org/wso2/carbon/am/integration/ui/LoginTestCase.java @@ -0,0 +1,55 @@ +/* +*Copyright (c) 2005-2010, 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.carbom.am.integration.ui; + +import org.openqa.selenium.WebDriver; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.automation.api.selenium.home.HomePage; +import org.wso2.carbon.automation.api.selenium.login.LoginPage; +import org.wso2.carbon.automation.core.BrowserManager; +import org.wso2.carbon.automation.core.ProductConstant; + +public class LoginTestCase extends AMIntegrationUiTestBase { + private WebDriver driver; + + @BeforeClass(alwaysRun = true) + public void setUp() throws Exception { + super.init(); + driver = BrowserManager.getWebDriver(); + driver.get(getLoginURL(ProductConstant.AM_SERVER_NAME)); + } + + @Test(groups = "wso2.greg", description = "verify login to governance registry") + public void testLogin() throws Exception { + LoginPage test = new LoginPage(driver); + HomePage home = test.loginAs(userInfo.getUserName(), userInfo.getPassword()); + home.logout(); + driver.close(); + System.out.println("Login test case is completed "); + } + + @AfterClass(alwaysRun = true) + public void tearDown() throws Exception { + driver.quit(); + } +} + + diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/hostobjecttest/api-manager.xml b/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/hostobjecttest/api-manager.xml new file mode 100755 index 0000000000..a7cbbc3a14 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/hostobjecttest/api-manager.xml @@ -0,0 +1,537 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + admin + + admin + + + + + + X-JWT-Assertion + + + org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever + + + http://wso2.org/claims + + + SHA256withRSA + + + true + + + true + + + + + + + + + + + + Production and Sandbox + + 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} + + + + + true + + + referer + + + + + true + + + + + + false + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + 7612 + + + tcp://localhost:7612/ + + + admin + + + admin + + + + + + + + false + + + UA-XXXXXXXX-X + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + + admin + + + admin + + true + + + + true + + + + WSClient + 10397 + 10000 + 10397 + + true + + + + + + + + /oauth2/token + + + false + + + + + + + true + + + + + + true + + + subscriber + + + true + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/store + + true + + true + + + true + + + true + + + + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/publisher + + + + + + + + + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + + + + + + + + + + true + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + /resource + http://localhost:9764/resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + Store1 + http://localhost:9763/store + user1@tenantdomain1.com + test123 + + + + + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + GET,POST,PUT,DELETE,OPTIONS + + + + diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/jaggery/test.jag b/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/jaggery/test.jag new file mode 100644 index 0000000000..48d3201391 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/jaggery/test.jag @@ -0,0 +1,5 @@ +<% + application.put("wso2", "test artifacts.AM.configFiles.jaggery application value"); + print(application.get("wso2")); + application.remove("wso2"); +%> \ No newline at end of file diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/throttling/throttle-policy.xml b/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/throttling/throttle-policy.xml new file mode 100755 index 0000000000..aa5de6f71d --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/throttling/throttle-policy.xml @@ -0,0 +1,34 @@ + + + + 127.0.0.1 + + + + 1 + 60000 + + + + + + + other + + + + 2 + 60000 + + + + + + + 1000 + + other + + + \ No newline at end of file diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/tokenTest/api-manager.xml b/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/tokenTest/api-manager.xml new file mode 100755 index 0000000000..628b9aad19 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/tokenTest/api-manager.xml @@ -0,0 +1,556 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + admin + + admin + + + + + + X-JWT-Assertion + + + org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever + + + http://wso2.org/claims + + + SHA256withRSA + + + true + + + true + + + + + + + + + + + + Production and Sandbox + + 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} + + + + + true + + + referer + + + + + true + + + + + + false + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + 7612 + + + tcp://localhost:7612/ + + + admin + + + admin + + + + + + + + false + + + UA-XXXXXXXX-X + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + + admin + + + admin + + true + + + + true + + + + WSClient + 10397 + 10000 + 10397 + + true + + + + + + + + /oauth2/token + + + false + + + + + + + true + + + + + + true + + + subscriber + + + true + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/store + + true + + true + + + true + + + true + + + + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/publisher + + + + + + + + + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + + + + + + + + + + true + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + /resource + http://localhost:9764/resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + + + + + + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + GET,POST,PUT,DELETE,OPTIONS + + + + diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/tokenTest/log4j.properties b/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/tokenTest/log4j.properties new file mode 100755 index 0000000000..76c7eb5251 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/tokenTest/log4j.properties @@ -0,0 +1,180 @@ +# +# 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.category.org.apache.synapse=INFO +log4j.category.org.apache.synapse.transport=INFO +log4j.category.org.apache.axis2=INFO +log4j.category.org.apache.axis2.transport=INFO +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 +#log4j.logger.org.wso2.carbon.apimgt.gateway.handlers=DEBUG +#log4j.logger.org.wso2.carbon.apimgt.gateway.handlers.throttling=DEBUG +log4j.logger.org.wso2.carbon.apimgt=DEBUG + +# 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 + +# 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 + +# The console appender is used to display general information at console +log4j.appender.CARBON_CONSOLE=org.wso2.carbon.logging.appenders.CarbonConsoleAppender +log4j.appender.CARBON_CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CARBON_CONSOLE.layout.ConversionPattern=[%d{ISO8601}] %5p - %c{1} %m%n + +# 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-apigw-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-apigw-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.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.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-apigw-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.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 + +# LOGEVENT is set to be a LogEventAppender using a PatternLayout to send logs to LOGEVENT +log4j.appender.LOGEVENT=org.wso2.carbon.logging.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 + + +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 + +# LOGEVENT is set to be a LogEventAppender using a PatternLayout to send logs to LOGEVENT +log4j.appender.LOGEVENT=org.wso2.carbon.logging.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,%H,%I,%Stacktrace +log4j.appender.LOGEVENT.userName=admin +log4j.appender.LOGEVENT.password=admin + +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 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 + diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/usagemonitortest/api-manager.xml b/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/usagemonitortest/api-manager.xml new file mode 100755 index 0000000000..406151fa75 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/usagemonitortest/api-manager.xml @@ -0,0 +1,537 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + admin + + admin + + + + + + X-JWT-Assertion + + + org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever + + + http://wso2.org/claims + + + SHA256withRSA + + + true + + + true + + + + + + + + + + + + Production and Sandbox + + 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} + + + + + true + + + referer + + + + + true + + + + + + true + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + 7612 + + + tcp://localhost:7612/ + + + admin + + + admin + + + + + + + + false + + + UA-XXXXXXXX-X + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + + admin + + + admin + + true + + + + true + + + + WSClient + 10397 + 10000 + 10397 + + true + + + + + + + + /oauth2/token + + + false + + + + + + + true + + + + + + true + + + subscriber + + + true + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/store + + true + + true + + + true + + + true + + + + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/publisher + + + + + + + + + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + + + + + + + + + + true + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + /resource + http://localhost:9764/resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + Store1 + http://localhost:9763/store + user1@tenantdomain1.com + test123 + + + + + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + GET,POST,PUT,DELETE,OPTIONS + + + + diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/usagemonitortest/master-datasources.xml b/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/usagemonitortest/master-datasources.xml new file mode 100755 index 0000000000..8cc23ee0b4 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/configFiles/usagemonitortest/master-datasources.xml @@ -0,0 +1,109 @@ + + + + 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 + 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 + + + + + + WSO2AM_STATS_DB + The datasource used for getting statistics to API Manager + + jdbc/WSO2AM_STATS_DB + + + + jdbc:h2:;AUTO_SERVER=TRUE + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/jaggery/testPublisher.jag b/modules/integration/tests-ui/src/test/resources/artifacts/AM/jaggery/testPublisher.jag new file mode 100644 index 0000000000..bbd5eec078 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/jaggery/testPublisher.jag @@ -0,0 +1,96 @@ +<% +//Order of these operations are important as we fetch results based on order. +//If you add new test add them to bottom of this file and update validate response method +//available in host object test class. +var publisher = require('apipublisher'); +var publisherHostObj = new publisher.APIProvider("admin"); +print("=="); +print(publisherHostObj.getExternalAPIStores()); +print("=="); +print(publisherHostObj.validateRoles('admin', 'admin')); +print("=="); +print(publisherHostObj.isURLValid("https","https://www.google.com")); +print("=="); +print(publisherHostObj.getAPIsByProvider("admin")); +print("=="); +print(publisherHostObj.getSubscribedAPIs("admin")); +print("=="); +print(publisherHostObj.getAPI("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.getTierPermissions()); +print("=="); +print(publisherHostObj.getTiers()); +print("=="); +print(publisherHostObj.getAllAPIs()); +print("=="); +print(publisherHostObj.getAPIsByProvider("admin")); +print("=="); +print(publisherHostObj.getSubscribersOfAPI("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.isContextExist("HostObjectTestAPI","HostObjectTestAPI")); +print("=="); +print(publisherHostObj.searchAPIs("admin","name:HostObjectTestAPI")); +print("=="); +print(publisherHostObj.hasCreatePermission()); +print("=="); +print(publisherHostObj.hasManageTierPermission()); +print("=="); +print(publisherHostObj.hasUserPermissions("admin")); +print("=="); +print(publisherHostObj.hasPublishPermission("admin")); +print("=="); +print(publisherHostObj.getAuthServerURL()); +print("=="); +print(publisherHostObj.getCustomInSequences()); +print("=="); +print(publisherHostObj.getCustomOutSequences()); +print("=="); +print(publisherHostObj.getHTTPsURL()); +print("=="); +print(publisherHostObj.isSynapseGateway()); +print("=="); +print(publisherHostObj.loadRegistryOfTenant("carbon.super")); +print("=="); +print(publisherHostObj.updateDocumentation("admin","HostObjectTestAPI","1.0.0","Doc-Name", "How To", "summary","In-line")); +print("=="); +print(publisherHostObj.addInlineContent("admin","HostObjectTestAPI","1.0.0","help","this is helpe")); +print("=="); +print(publisherHostObj.getInlineContent("admin","HostObjectTestAPI","1.0.0","help")); +print("=="); +print(publisherHostObj.getAllDocumentation("admin@carbon.super","HostObjectTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.searchAccessTokens("*:*")); +print("=="); +print(publisherHostObj.getSubscriberCountByAPIs("admin@carbon.super")); +print("=="); +print(publisherHostObj.getSubscriberCountByAPIVersions("admin@carbon.super")); +print("=="); +print(publisherHostObj.getExternalAPIStores()); +print("=="); +var apiData = {}; +apiData["provider"] = "admin"; +apiData["name"] = "HostObjectTestAPI"; +apiData["version"] = "1.0.0"; +apiData["apiName"] = "HostObjectTestAPI"; +print(publisherHostObj.isAPIOlderVersionExist(apiData)); +print("=="); +print(publisherHostObj.updateSubscriptionStatus(apiData,"BLOCKED","1")); +print("=="); + +var tierData = {}; +tierData["tierName"] = "Gold"; +tierData["permissiontype"] = "Deny"; +tierData["roles"] = "admin"; +print(publisherHostObj.updateTierPermissions(tierData)); +print("=="); +//print(publisherHostObj.updateExternalAPIStores(apiData)); +//print(publisherHostObj.createNewAPIVersion("admin","HostObjectTestAPI","1.0.0","1.0.1")); +//print(publisherHostObj.searchAccessTokens("admin")); +//print(publisherHostObj.getSubscriberCountByAPIVersions()); +var apiData1 = {}; +apiData1["provider"] = "admin"; +apiData1["name"] = "HostObjectTestAPI"; +apiData1["version"] = "1.0.0"; +apiData1["apiName"] = "HostObjectTestAPI"; +//print(publisherHostObj.updateExternalAPIStores(apiData1)); +%> \ No newline at end of file diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/jaggery/testStore.jag b/modules/integration/tests-ui/src/test/resources/artifacts/AM/jaggery/testStore.jag new file mode 100644 index 0000000000..3c307b619e --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/jaggery/testStore.jag @@ -0,0 +1,93 @@ +<% +<% +//Order of these operations are important as we fetch results based on order + //If you add new test add them to bottom of this file and update validate response method + //available in host object test class +store = require('apistore'); +var storeHostObj = new store.APIStore("admin"); +print("=="); +print(storeHostObj.isBillingEnabled()); +print("=="); +print(storeHostObj.getHTTPsURL("localhost")); +print("=="); +print(storeHostObj.getAuthServerURL()); +print("=="); +print(storeHostObj.getHTTPURL("localhost")); +print("=="); +print(storeHostObj.getDeniedTiers()); +print("=="); +print(storeHostObj.getActiveTenantDomains()); +print("=="); +print(storeHostObj.isSelfSignupEnabled()); +print("=="); +print(storeHostObj.getUserFields()); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("HostObjectTestAPI","carbon.super","0","10")); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("name:*","carbon.super","0","10")); +print("=="); +print(storeHostObj.searchAPIbyType("name:*","carbon.super")); +print("=="); +print(storeHostObj.searchAPIbyType("HostObjectTestAPI","carbon.super")); +print("=="); +print(storeHostObj.getPaginatedAPIsWithTag("youtube","0","10")); +print("=="); +print(storeHostObj.getPublishedAPIsByProvider("admin@carbon.super","admin")); +print("=="); +print(storeHostObj.getAllSubscriptions("admin@carbon.super")); +print("=="); +print(storeHostObj.rateAPI("admin","HostObjectTestAPI","1.0.0","3")); +print("=="); +print(storeHostObj.removeAPIRating("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(storeHostObj.getAllPaginatedPublishedAPIs("carbon.super","0","10")); +print("=="); +print(storeHostObj.getAPIsWithTag("youtube")); +print("=="); +print(storeHostObj.getAllPublishedAPIs("carbon.super")); +print("=="); +print(storeHostObj.getComments("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(storeHostObj.isUserExists("admin")); +print("=="); +print(storeHostObj.getAPI("admin","HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.isSubscribed("admin","HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.getSubscriptions("admin","HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.getSubscribedAPIs("3")); +print("=="); +print(storeHostObj.hasUserPermissions("admin")); +print("=="); +print(storeHostObj.getTiers("admin")); +print("=="); +print(storeHostObj.getAPIUsageforSubscriber("admin")); +print("=="); +print(storeHostObj.getDeniedTiers("admin")); +print("=="); +print(storeHostObj.getRecentlyAddedAPIs("5","carbon.super")); +print("=="); +print(storeHostObj.getTopRatedAPIs("5")); +print("=="); +print(storeHostObj.isBillingEnabled()); +print("=="); +print(storeHostObj.hasSubscribePermission()); +print("=="); +print(storeHostObj.isEnableEmailUsername()); +print("=="); +print(storeHostObj.updateApplicationTier("DefaultApplication","gold","admin")); +print("=="); +print(storeHostObj.updateApplication("DefaultApplicationTest","DefaultApplication","admin","gold","test-url","updated-application")); +print("=="); +print(storeHostObj.validateWFPermission("Basic YWRtaW46YWRtaW4=")); +print("=="); +print(storeHostObj.getSwaggerDiscoveryUrl("HostObjectTestAPI","1.0.0","admin")); +print("=="); +//print(storeHostObj.removeSubscriber("admin","HostObjectTestAPI","1.0.0","DefaultApplication","1")); +//print(storeHostObj.removeSubscription("admin","HostObjectTestAPI","1.0.0","DefaultApplication","1")); +//print(storeHostObj.rateAPI("admin","HostObjectTestAPI","1.0.0","3")); +//print("=="); +//print(storeHostObj.getTopRatedAPIs("3")); +%> +%> \ No newline at end of file diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/jaggery/testUsageWithBAM.jag b/modules/integration/tests-ui/src/test/resources/artifacts/AM/jaggery/testUsageWithBAM.jag new file mode 100644 index 0000000000..e43384478b --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/jaggery/testUsageWithBAM.jag @@ -0,0 +1,36 @@ +<% +//Order of these operations are important as we fetch results based on order. +//If you add new test add them to bottom of this file and update validate response method +//available in host object test class. +var publisher = require('apipublisher'); +var publisherHostObj = new publisher.APIProvider("admin"); +print("=="); +print(publisherHostObj.getAPIUsageforSubscriber("admin")); +print("=="); +print(publisherHostObj.getAPIFaultyAnalyzeByTime("admin")); +print("=="); +var start=new Date(); +start.setFullYear(2014,0,14); +var end = new Date(); +end.setFullYear(2015,0,14); +print(publisherHostObj.getAPIResponseFaultCount("admin",start,end)); +print("=="); +print(publisherHostObj.getAPIUsageByResourcePath("admin",start,end)); +print("=="); +print(publisherHostObj.getAPIUsageByUser("admin",start,end)); +print("=="); +print(publisherHostObj.getAllAPIUsageByProvider("admin")); +print("=="); +print(publisherHostObj.getFirstAccessTime("admin")); +print("=="); +print(publisherHostObj.getProviderAPIServiceTime("admin",start,end)); +print("=="); +print(publisherHostObj.getProviderAPIUsage("admin","UsageTestAPI")); +print("=="); +print(publisherHostObj.getProviderAPIVersionUsage("admin","UsageTestAPI")); +print("=="); +print(publisherHostObj.getProviderAPIVersionUserUsage("admin","UsageTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.getProviderAPIVersionUserLastAccess("admin",start,end)); +print("=="); +%> \ No newline at end of file diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/API_Manager_Login_Test.jmx b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/API_Manager_Login_Test.jmx new file mode 100644 index 0000000000..6e46aeeaee --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/API_Manager_Login_Test.jmx @@ -0,0 +1,356 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + Youtube + = + + + context + /youtube + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + Tester_Acc2 + = + + + publisherName + admin + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://localhost:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + 200 + + Assertion.response_code + false + 2 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/aggregate_report.jtl + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + + + + diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest.jmx b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest.jmx new file mode 100644 index 0000000000..0852fe5dd7 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest.jmx @@ -0,0 +1,2902 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + GOOG_Stock_API + = + + + context + /GStock + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + userPrefix + tenant + = + + + resourceMethods + POST + = + + + authTypes + Application & Application User + = + + + throttlingTiers + Unlimited + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_number + # + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <ser:getTenant> + <!--Optional:--> + <ser:tenantDomain>domain${tenant_number}.com</ser:tenantDomain> + </ser:getTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:getTenant + true + false + + + + undefined + tenant_exists + //*[local-name()='active']/text() + false + false + true + tenant_exists + + + + false + true + true + false + + + + + ${tenant_exists}==false + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org" xmlns:xsd="http://beans.common.stratos.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <ser:addTenant> + <!--Optional:--> + <ser:tenantInfoBean> + <!--Optional:--> + <xsd:active>1</xsd:active> + <!--Optional:--> + <xsd:admin>${userPrefix}${tenant_number}</xsd:admin> + <!--Optional:--> + <xsd:adminPassword>1qaz2wsx@</xsd:adminPassword> + <!--Optional:--> + <xsd:createdDate>2013-02-22T08:22:54</xsd:createdDate> + <!--Optional:--> + <xsd:email>ruwany@wso2.com</xsd:email> + <!--Optional:--> + <xsd:firstname>User1</xsd:firstname> + <!--Optional:--> + <xsd:lastname>LastName1</xsd:lastname> + <!--Optional:--> + <xsd:tenantDomain>domain${tenant_number}.com</xsd:tenantDomain> + <!--Optional:--> + <xsd:tenantId>0</xsd:tenantId> + <!--Optional:--> + <xsd:usagePlan>Demo</xsd:usagePlan> + </ser:tenantInfoBean> + </ser:addTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:addTenant + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + 202 + + Assertion.response_code + false + 1 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + + 1363957740000 + 1363957740000 + false + + + + + + + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_counter + # + false + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>${userPrefix}${tenant_counter}@domain${tenant_counter}.com</aut:username> + <!--Optional:--> + <aut:password>1qaz2wsx@</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <xsd:getAllRolesNames> + <!--Optional:--> + <xsd:filter>*</xsd:filter> + <!--Optional:--> + <xsd:limit>100</xsd:limit> + </xsd:getAllRolesNames> + </soapenv:Body> +</soapenv:Envelope> + + urn:getAllRolesNames + true + false + + + + undefined + role_exists + //*[local-name()='itemName']/text()='subscriber_role' + false + false + true + + + + false + true + true + false + + + + + ${role_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addRole> + <!--Optional:--> + <mgt:roleName>subscriber_role</mgt:roleName> + <mgt:permissions>/permission/admin/login</mgt:permissions> + <mgt:permissions>/permission/admin/manage/api/subscribe</mgt:permissions> + <mgt:isSharedRole>false</mgt:isSharedRole> + </mgt:addRole> + </soapenv:Body> +</soapenv:Envelope> + + urn:addRole + true + false + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + user_ref + # + false + + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:listUsers> + <!--Optional:--> + <mgt:filter>${userPrefix}${tenant_counter}_user${user_ref}</mgt:filter> + <mgt:limit>10</mgt:limit> + </mgt:listUsers> + </soapenv:Body> +</soapenv:Envelope> + + urn:listUsers + true + false + + + + false + user_exists + //*[local-name()='return']/text()='${userPrefix}${tenant_counter}_user${user_ref}' + false + false + true + + + + false + true + true + false + + + + + ${user_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd" xmlns:xsd="http://common.mgt.user.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addUser> + <!--Optional:--> + <mgt:userName>${userPrefix}${tenant_counter}_user${user_ref}</mgt:userName> + <!--Optional:--> + <mgt:password>1qaz2wsx@</mgt:password> + <mgt:roles>subscriber_role</mgt:roles> + </mgt:addUser> + </soapenv:Body> +</soapenv:Envelope> + + urn:addUser + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy_report.jtl + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + String currentDir = System.getProperty("user.dir"); +FileOutputStream f = new FileOutputStream(currentDir + "/results.csv"); + + + false + + + + + + false + rfc2109 + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}@domain${input_value}.com + = + true + username + + + false + ${publisherPass} + = + true + password + + + false + null + = + true + tenant + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${numberOfAPIs} + + + + 1 + ${numberOfAPIs} + 1 + api_id + # + false + + + + + + + false + addAPI + = + true + action + + + false + ${apinm}${api_id} + = + true + name + + + false + ${context}${api_id} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + /* + = + true + uriTemplate-0 + + + false + ${resourceMethods} + = + true + resourceMethod-0 + + + false + ${authTypes} + = + true + resourceMethodAuthType-0 + + + false + ${throttlingTiers} + = + true + resourceMethodThrottlingTier-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + http + = + true + http_checked + + + false + https + = + true + https_checked + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm}${api_id} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + false + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${numberOfAPIs} + + + + 1 + ${numberOfAPIs} + 1 + api_id + # + false + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm}${api_id} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + Unlimited + = + true + tier + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com&password=1qaz2wsx@&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + +String tenant_count = vars.get("input_value"); +String user_count = vars.get("subsCount"); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + +String currentDir = System.getProperty("user.dir"); + +vars.put("current_directory" , currentDir); + +String context = vars.get("context"); +String apiID = vars.get("api_id"); + +f = new FileOutputStream(currentDir + "/results.csv", true); + +p = new PrintStream(f); + +this.interpreter.setOut(p); + +print("domain"+ tenant_count+".com" + "@@@" + accessToken +"@@@" + context+apiID); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + /t/domain${input_value}.com${context}${api_id}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getAllPublishedAPIs + = + true + action + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/api/listing/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + true + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getRecentlyAddedAPIs + = + true + action + + + false + 2000 + = + true + limit + + + false + domain1.com + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + store/site/blocks/api/recently-added/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getAllTags + = + true + action + + + + ${storeIP} + ${storePort} + + + + + store/site/blocks/tag/tag-cloud/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 10 + 1 + 1365001797000 + 1365001797000 + false + + + + + + + + import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.LineNumberReader; + +String currentDir = System.getProperty("user.dir"); + +LineNumberReader lnr = new LineNumberReader(new FileReader(new File(currentDir + "/results.csv"))); +lnr.skip(Long.MAX_VALUE); + +int min = 1; +int max = lnr.getLineNumber(); + +Random r = new Random(); +int i1 = r.nextInt(max - min + 1) + min; + +vars.put("random_value",""+i1); + +String lineConcerened = ""; + +BufferedReader br = new BufferedReader(new FileReader(new File(currentDir + "/results.csv"))); + +String strLine =""; + +for(int i=0; i<max; i++){ + strLine = br.readLine(); + if(i==i1-1){ + System.out.println(strLine); + lineConcerened = strLine; + } +} + +String[] splitVals = lineConcerened.split("@@@"); +String userName = splitVals[0]; +String token = splitVals[1]; +String contextAndAPIId = splitVals[2]; + +vars.put("line_count",""+i1); +vars.put("domain",userName); +vars.put("token",token); +vars.put("contextAndAPIId",contextAndAPIId); + + + false + + + + false + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + /t/${domain}${contextAndAPIId}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${token} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + false + true + true + false + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/aggregate_report.jtl + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + + + + diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest_new_tenant.jmx b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest_new_tenant.jmx new file mode 100644 index 0000000000..eb187dda28 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest_new_tenant.jmx @@ -0,0 +1,2671 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + GOOG_Stock_API_New + = + + + context + /GStocknew + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + userPrefix + tenant + = + + + resourceMethods + POST + = + + + authTypes + Application & Application User + = + + + throttlingTiers + Unlimited + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_number + # + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <ser:getTenant> + <!--Optional:--> + <ser:tenantDomain>domain${tenant_number}.com</ser:tenantDomain> + </ser:getTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:getTenant + true + false + + + + undefined + tenant_exists + //*[local-name()='active']/text() + false + false + true + tenant_exists + + + + false + true + true + false + + + + + ${tenant_exists}==false + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org" xmlns:xsd="http://beans.common.stratos.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <ser:addTenant> + <!--Optional:--> + <ser:tenantInfoBean> + <!--Optional:--> + <xsd:active>1</xsd:active> + <!--Optional:--> + <xsd:admin>${userPrefix}${tenant_number}</xsd:admin> + <!--Optional:--> + <xsd:adminPassword>1qaz2wsx@</xsd:adminPassword> + <!--Optional:--> + <xsd:createdDate>2013-02-22T08:22:54</xsd:createdDate> + <!--Optional:--> + <xsd:email>ruwany@wso2.com</xsd:email> + <!--Optional:--> + <xsd:firstname>User1</xsd:firstname> + <!--Optional:--> + <xsd:lastname>LastName1</xsd:lastname> + <!--Optional:--> + <xsd:tenantDomain>domain${tenant_number}.com</xsd:tenantDomain> + <!--Optional:--> + <xsd:tenantId>0</xsd:tenantId> + <!--Optional:--> + <xsd:usagePlan>Demo</xsd:usagePlan> + </ser:tenantInfoBean> + </ser:addTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:addTenant + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + 202 + + Assertion.response_code + false + 1 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + + 1363957740000 + 1363957740000 + false + + + + + + + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_counter + # + false + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>${userPrefix}${tenant_counter}@domain${tenant_counter}.com</aut:username> + <!--Optional:--> + <aut:password>1qaz2wsx@</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <xsd:getAllRolesNames> + <!--Optional:--> + <xsd:filter>*</xsd:filter> + <!--Optional:--> + <xsd:limit>100</xsd:limit> + </xsd:getAllRolesNames> + </soapenv:Body> +</soapenv:Envelope> + + urn:getAllRolesNames + true + false + + + + undefined + role_exists + //*[local-name()='itemName']/text()='subscriber_role_new' + false + false + true + + + + false + true + true + false + + + + + ${role_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addRole> + <!--Optional:--> + <mgt:roleName>subscriber_role_new</mgt:roleName> + <mgt:permissions>/permission/admin/login</mgt:permissions> + <mgt:permissions>/permission/admin/manage/api/subscribe</mgt:permissions> + <mgt:isSharedRole>false</mgt:isSharedRole> + </mgt:addRole> + </soapenv:Body> +</soapenv:Envelope> + + urn:addRole + true + false + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + user_ref + # + false + + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:listUsers> + <!--Optional:--> + <mgt:filter>${userPrefix}${tenant_counter}_user${user_ref}</mgt:filter> + <mgt:limit>10</mgt:limit> + </mgt:listUsers> + </soapenv:Body> +</soapenv:Envelope> + + urn:listUsers + true + false + + + + false + user_exists + //*[local-name()='return']/text()='${userPrefix}${tenant_counter}_user${user_ref}' + false + false + true + + + + false + true + true + false + + + + + ${user_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd" xmlns:xsd="http://common.mgt.user.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addUser> + <!--Optional:--> + <mgt:userName>${userPrefix}${tenant_counter}_user${user_ref}</mgt:userName> + <!--Optional:--> + <mgt:password>1qaz2wsx@</mgt:password> + <mgt:roles>subscriber_role_new</mgt:roles> + </mgt:addUser> + </soapenv:Body> +</soapenv:Envelope> + + urn:addUser + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy_report.jtl + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + String currentDir = System.getProperty("user.dir"); +FileOutputStream f = new FileOutputStream(currentDir + "/results.csv"); + + + false + + + + + + false + rfc2109 + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}@domain${input_value}.com + = + true + username + + + false + ${publisherPass} + = + true + password + + + false + null + = + true + tenant + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${numberOfAPIs} + + + + 1 + ${numberOfAPIs} + 1 + api_id + # + false + + + + + + + false + addAPI + = + true + action + + + false + ${apinm}${api_id} + = + true + name + + + false + ${context}${api_id} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + /* + = + true + uriTemplate-0 + + + false + ${resourceMethods} + = + true + resourceMethod-0 + + + false + ${authTypes} + = + true + resourceMethodAuthType-0 + + + false + ${throttlingTiers} + = + true + resourceMethodThrottlingTier-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + http + = + true + http_checked + + + false + https + = + true + https_checked + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm}${api_id} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + false + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${numberOfAPIs} + + + + 1 + ${numberOfAPIs} + 1 + api_id + # + false + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm}${api_id} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + Unlimited + = + true + tier + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com&password=1qaz2wsx@&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + +String tenant_count = vars.get("input_value"); +String user_count = vars.get("subsCount"); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + +String currentDir = System.getProperty("user.dir"); + +vars.put("current_directory" , currentDir); + +String context = vars.get("context"); +String apiID = vars.get("api_id"); + +f = new FileOutputStream(currentDir + "/results.csv", true); + +p = new PrintStream(f); + +this.interpreter.setOut(p); + +print("domain"+ tenant_count+".com" + "@@@" + accessToken +"@@@" + context+apiID); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + /t/domain${input_value}.com${context}${api_id}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getAllPublishedAPIs + = + true + action + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/api/listing/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + true + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getRecentlyAddedAPIs + = + true + action + + + false + 2000 + = + true + limit + + + false + domain1.com + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + store/site/blocks/api/recently-added/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getAllTags + = + true + action + + + + ${storeIP} + ${storePort} + + + + + store/site/blocks/tag/tag-cloud/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 10 + 1 + 1365001797000 + 1365001797000 + false + + + + + + + + import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.LineNumberReader; + +String currentDir = System.getProperty("user.dir"); + +LineNumberReader lnr = new LineNumberReader(new FileReader(new File(currentDir + "/results.csv"))); +lnr.skip(Long.MAX_VALUE); + +int min = 1; +int max = lnr.getLineNumber(); + +Random r = new Random(); +int i1 = r.nextInt(max - min + 1) + min; + +vars.put("random_value",""+i1); + +String lineConcerened = ""; + +BufferedReader br = new BufferedReader(new FileReader(new File(currentDir + "/results.csv"))); + +String strLine =""; + +for(int i=0; i<max; i++){ + strLine = br.readLine(); + if(i==i1-1){ + System.out.println(strLine); + lineConcerened = strLine; + } +} + +String[] splitVals = lineConcerened.split("@@@"); +String userName = splitVals[0]; +String token = splitVals[1]; +String contextAndAPIId = splitVals[2]; + +vars.put("line_count",""+i1); +vars.put("domain",userName); +vars.put("token",token); +vars.put("contextAndAPIId",contextAndAPIId); + + + false + + + + false + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + /t/${domain}${contextAndAPIId}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${token} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + false + true + true + false + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/DomainRestrictionTest.jmx b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/DomainRestrictionTest.jmx new file mode 100644 index 0000000000..55821fa75b --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/DomainRestrictionTest.jmx @@ -0,0 +1,1202 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + basic_functions_api_domain + = + + + context + /basic_functions_api_domain + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + super_tenant_user + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + https://lh6.ggpht.com/RNc8dD2hXG_rWGzlj09ZwAe1sXVvLWkeYT3ePx7zePCy4ZVV2XMGIxAzup4cKM85NFtL=w124 + = + true + apiThumb + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + POST + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Unlimited, Unlimited, Unlimited, Unlimited, Unlimited + = + true + resourceMethodThrottlingTier-0 + + + false + http + = + true + http_checked + + + false + https + = + true + https_checked + + + false + Application User + = + true + resourceMethodAuthType-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${noOfSubscribers} + + + + 1 + 10000 + 1 + subsCount + # + false + + + + + + + false + addUser + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + false + ${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}@test.com|| + = + true + allFieldsValues + + + false + + = + true + + + false + + = + true + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/sign-up/ajax/user-add.jag + POST + true + false + true + false + Java + false + + + + + 50 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//int eq = resp.indexOf("=", def - 8); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println("APP ID : " + appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + true + true + true + false + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + true + true + true + false + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + wso2.org + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + refreshToken + = + true + action + + + false + application + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${token} + = + true + oldAccessToken + + + false + ${consumerKey} + = + true + clientId + + + false + ${consumerSecret} + = + true + clientSecret + + + false + 5000 + = + true + validityTime + + + false + wso2.org + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${subsPrefix}_${subsCount}&password=subscriber@123&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + referer + wso2.org + + + + + + + 200 + + Assertion.response_data + false + 6 + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + + diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/basic_functionality_test.jmx b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/basic_functionality_test.jmx new file mode 100644 index 0000000000..dd959572bf --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/basic_functionality_test.jmx @@ -0,0 +1,1198 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + basic_functions_api + = + + + context + /basic_functions_api + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + super_tenant_user + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + https://lh6.ggpht.com/RNc8dD2hXG_rWGzlj09ZwAe1sXVvLWkeYT3ePx7zePCy4ZVV2XMGIxAzup4cKM85NFtL=w124 + = + true + apiThumb + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + POST + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Unlimited, Unlimited, Unlimited, Unlimited, Unlimited + = + true + resourceMethodThrottlingTier-0 + + + false + http + = + true + http_checked + + + false + https + = + true + https_checked + + + false + Application User + = + true + resourceMethodAuthType-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${noOfSubscribers} + + + + 1 + 10000 + 1 + subsCount + # + false + + + + + + + false + addUser + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + false + ${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}@test.com|| + = + true + allFieldsValues + + + false + + = + true + + + false + + = + true + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/sign-up/ajax/user-add.jag + POST + true + false + true + false + Java + false + + + + + 50 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//int eq = resp.indexOf("=", def - 8); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println("APP ID : " + appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + true + true + true + false + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + true + true + true + false + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + refreshToken + = + true + action + + + false + application + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${token} + = + true + oldAccessToken + + + false + ${consumerKey} + = + true + clientId + + + false + ${consumerSecret} + = + true + clientSecret + + + false + 5000 + = + true + validityTime + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${subsPrefix}_${subsCount}&password=subscriber@123&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + No data found + + Assertion.response_data + false + 6 + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + + diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/content_type_check_for_DELETE_script.jmx b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/content_type_check_for_DELETE_script.jmx new file mode 100644 index 0000000000..3b6fa90f65 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/content_type_check_for_DELETE_script.jmx @@ -0,0 +1,491 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + testContentTypeHeaderAPI + = + + + context + /testContentTypeHeaderAPI + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + + + + + false + rfc2109 + + + + + + + false + login + = + true + action + + + false + admin + = + true + username + + + false + admin + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + +System.out.println("####################################################################### Access Token Response: " + jsonResponse); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=admin&password=admin&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + false + ThisParamIsRequiredForTest_DELETE + = + true + param + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version}/ + DELETE + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/content_type_check_for_GET_script.jmx b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/content_type_check_for_GET_script.jmx new file mode 100644 index 0000000000..6385a2ed19 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/content_type_check_for_GET_script.jmx @@ -0,0 +1,498 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + testContentTypeHeaderAPI + = + + + context + /testContentTypeHeaderAPI + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + + + + + false + rfc2109 + + + + + + + false + login + = + true + action + + + false + admin + = + true + username + + + false + admin + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + false + 5600 + = + true + validityTime + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + +System.out.println("####################################################################### Access Token Response: " + jsonResponse); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=admin&password=admin&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + false + ThisParamIsRequiredForTest_GET + = + true + param + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version}/ + GET + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/content_type_check_publish_and_subscribe_script.jmx b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/content_type_check_publish_and_subscribe_script.jmx new file mode 100644 index 0000000000..f194dc87e4 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/content_type_check_publish_and_subscribe_script.jmx @@ -0,0 +1,665 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + testContentTypeHeaderAPI + = + + + context + /testContentTypeHeaderAPI + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + + + + + false + rfc2109 + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + 127.0.0.1:6789 + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + DELETE,GET + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + Application User,Application User + = + true + resourceMethodAuthType-0 + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Unlimited, Unlimited, Unlimited, Unlimited, Unlimited + = + true + resourceMethodThrottlingTier-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + admin + = + true + username + + + false + admin + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + admin + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//String appid = resp.substring(def+6, resp.indexOf("," )); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println("AppId: " + appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + 1.0.0 + = + true + version + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/tenant_create.jmx b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/tenant_create.jmx new file mode 100644 index 0000000000..976581f9ad --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/tenant_create.jmx @@ -0,0 +1,634 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + GOOG_Stock_API_New + = + + + context + /GStocknew + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + userPrefix + user + = + + + resourceMethods + POST + = + + + authTypes + Application & Application User + = + + + throttlingTiers + Unlimited + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_number + # + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <ser:getTenant> + <!--Optional:--> + <ser:tenantDomain>tenantdomain${tenant_number}.com</ser:tenantDomain> + </ser:getTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:getTenant + true + false + + + + undefined + tenant_exists + //*[local-name()='active']/text() + false + false + true + tenant_exists + + + + false + true + true + false + + + + + ${tenant_exists}==false + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org" xmlns:xsd="http://beans.common.stratos.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <ser:addTenant> + <!--Optional:--> + <ser:tenantInfoBean> + <!--Optional:--> + <xsd:active>1</xsd:active> + <!--Optional:--> + <xsd:admin>${userPrefix}${tenant_number}</xsd:admin> + <!--Optional:--> + <xsd:adminPassword>test123</xsd:adminPassword> + <!--Optional:--> + <xsd:createdDate>2013-02-22T08:22:54</xsd:createdDate> + <!--Optional:--> + <xsd:email>ruwany@wso2.com</xsd:email> + <!--Optional:--> + <xsd:firstname>User1</xsd:firstname> + <!--Optional:--> + <xsd:lastname>LastName1</xsd:lastname> + <!--Optional:--> + <xsd:tenantDomain>tenantdomain${tenant_number}.com</xsd:tenantDomain> + <!--Optional:--> + <xsd:tenantId>0</xsd:tenantId> + <!--Optional:--> + <xsd:usagePlan>Demo</xsd:usagePlan> + </ser:tenantInfoBean> + </ser:addTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:addTenant + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + 202 + + Assertion.response_code + false + 1 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + + 1363957740000 + 1363957740000 + false + + + + + + + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_counter + # + false + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>${userPrefix}${tenant_counter}@tenantdomain${tenant_counter}.com</aut:username> + <!--Optional:--> + <aut:password>test123</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <xsd:getAllRolesNames> + <!--Optional:--> + <xsd:filter>*</xsd:filter> + <!--Optional:--> + <xsd:limit>100</xsd:limit> + </xsd:getAllRolesNames> + </soapenv:Body> +</soapenv:Envelope> + + urn:getAllRolesNames + true + false + + + + undefined + role_exists + //*[local-name()='itemName']/text()='subscriber_role_new' + false + false + true + + + + false + true + true + false + + + + + ${role_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addRole> + <!--Optional:--> + <mgt:roleName>subscriber_role_new</mgt:roleName> + <mgt:permissions>/permission/admin/login</mgt:permissions> + <mgt:permissions>/permission/admin/manage/api/subscribe</mgt:permissions> + <mgt:isSharedRole>false</mgt:isSharedRole> + </mgt:addRole> + </soapenv:Body> +</soapenv:Envelope> + + urn:addRole + true + false + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + user_ref + # + false + + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:listUsers> + <!--Optional:--> + <mgt:filter>${userPrefix}${tenant_counter}_user${user_ref}</mgt:filter> + <mgt:limit>10</mgt:limit> + </mgt:listUsers> + </soapenv:Body> +</soapenv:Envelope> + + urn:listUsers + true + false + + + + false + user_exists + //*[local-name()='return']/text()='${userPrefix}${tenant_counter}_user${user_ref}' + false + false + true + + + + false + true + true + false + + + + + ${user_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd" xmlns:xsd="http://common.mgt.user.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addUser> + <!--Optional:--> + <mgt:userName>${userPrefix}${tenant_counter}_user${user_ref}</mgt:userName> + <!--Optional:--> + <mgt:password>1qaz2wsx@</mgt:password> + <mgt:roles>subscriber_role_new</mgt:roles> + </mgt:addUser> + </soapenv:Body> +</soapenv:Envelope> + + urn:addUser + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy_report.jtl + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/transport_restriction_check.jmx b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/transport_restriction_check.jmx new file mode 100644 index 0000000000..f45a4bcbe8 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/scripts/transport_restriction_check.jmx @@ -0,0 +1,1135 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + restricted_api + = + + + context + restricted_api + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + transport_users + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + https://lh6.ggpht.com/RNc8dD2hXG_rWGzlj09ZwAe1sXVvLWkeYT3ePx7zePCy4ZVV2XMGIxAzup4cKM85NFtL=w124 + = + true + apiThumb + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + POST + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Unlimited, Unlimited, Unlimited, Unlimited, Unlimited + = + true + resourceMethodThrottlingTier-0 + + + false + + = + true + http_checked + + + false + https + = + true + https_checked + + + false + Application User + = + true + resourceMethodAuthType-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${noOfSubscribers} + + + + 1 + 10000 + 1 + subsCount + # + false + + + + + + + false + addUser + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + false + ${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}@test.com|| + = + true + allFieldsValues + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/sign-up/ajax/user-add.jag + POST + true + false + true + false + Java + false + + + + + 50 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//int eq = resp.indexOf("=", def - 8); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + 1.0.0 + = + true + version + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${subsPrefix}_${subsCount}&password=subscriber@123&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + http + + ${context}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + Unsupported Transport + + Assertion.response_data + true + 2 + + + + + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + ${context}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml b/modules/integration/tests-ui/src/test/resources/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml new file mode 100644 index 0000000000..4e06ac5885 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml @@ -0,0 +1,271 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $1 + Status report + Runtime Error + $2 + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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. + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + The default main sequence for API manager - Returns 404 Not Found + + + + + + + + + + + + + + + + 30000 + fault + + + -1 + 0 + 1.0 + 0 + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30000 + fault + + + -1 + 0 + 1.0 + 0 + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/synapseconfigs/property/placeOrder.xml b/modules/integration/tests-ui/src/test/resources/artifacts/AM/synapseconfigs/property/placeOrder.xml new file mode 100644 index 0000000000..de239abdb6 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/synapseconfigs/property/placeOrder.xml @@ -0,0 +1,7 @@ + + + 50 + 10 + IBM + + \ No newline at end of file diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/synapseconfigs/rest/url-mapping-synapse.xml b/modules/integration/tests-ui/src/test/resources/artifacts/AM/synapseconfigs/rest/url-mapping-synapse.xml new file mode 100644 index 0000000000..a29656ba16 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/synapseconfigs/rest/url-mapping-synapse.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + +
    + + + + + + + 4.212070096051944 + -9.567415587431361 + -148.1740146577308 + IBM + + + + + + + + + + + + + diff --git a/modules/integration/tests-ui/src/test/resources/artifacts/AM/synapseconfigs/throttling/throttling-api-synapse.xml b/modules/integration/tests-ui/src/test/resources/artifacts/AM/synapseconfigs/throttling/throttling-api-synapse.xml new file mode 100644 index 0000000000..8e4f3c60b7 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/artifacts/AM/synapseconfigs/throttling/throttling-api-synapse.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + +
    + + + + + + + 4.212070096051944 + -9.567415587431361 + -148.1740146577308 + IBM + + + + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests-ui/src/test/resources/automation.properties b/modules/integration/tests-ui/src/test/resources/automation.properties new file mode 100644 index 0000000000..aae824aff0 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/automation.properties @@ -0,0 +1,93 @@ +# Testing server details +#--------------------------------------------------------------------------------------------------- +stratos.test=false +port.enable=true +carbon.web.context.enable=false +service.deployment.delay=30000 +cluster.enable=false +product.list=AM +deployment.framework.enable=false +deployment.framework.home=/home/krishantha/automation/deployment-framework +builder.enable=true +coverage.enable=true +execution.environment=integration +execution.mode=user + +am.host.name=localhost +am.http.port=9763 +am.https.port=9443 + + +ravana.framework.path=/home/krishantha/new-machine/svn/ravana/ravana2 +ravana.test=true + +#(chrome|firefox|opera|ie|htmlUnit) +browser.name=firefox +path.to.chrome.driver="/home/krishantha/Downloads/chromedriver" + +#run selenium test on remote browser or not. (true|false) +remote.selenium.web.driver.start=false +remote.webdirver.url=http://10.100.2.51:4444/wd/hub/ + +#this database configuration is used for data service test in product testing. configuration used as a data source in dbs files +#database.driver.name=com.mysql.jdbc.Driver +#jdbc.url=jdbc:mysql://127.0.0.1:3306 +database.driver.name=org.h2.Driver +jdbc.url=jdbc:h2: +db.user=dbuser1 +db.password=dbuser123 +db.name=testDb + +#RSS Data Source configuration in Stratos. this user name and password are used to create a user on RSS Manager in stratos and used in .dbs file as well +#user name should be limited to 7 characters +rss.database.user = tstusr1 +rss.database.password =test123 + +ravana.jdbc.url=jdbc:mysql://127.0.0.1:3306 +ravana.db.user=root +ravana.db.password=root + + +#this database configuration is used for test result dashboard. +dashboard.enable=false +dashboard.database.driver.name=com.mysql.jdbc.Driver +dashboard.jdbc.url=jdbc:mysql://127.0.0.1:3306 +dashboard.db.user=root +dashboard.db.password=root +dashboard.db.name=FRAMEWORK_DB + + +#Stratos server details +#---------------------------------------------------------------------------------------------------- +app.service.host.name=appserver.stratosdev.private.wso2.com +esb.service.host.name=esb.stratosdev.private.wso2.com +greg.service.host.name=governance.stratosdev.private.wso2.com +dss.service.host.name=data.stratosdev.private.wso2.comso2.comso2.com +gs.service.host.name=gadget.stratosdev.private.wso2.comso2.com +brs.service.host.name=rule.stratosdev.private.wso2.com +bps.service.host.name=process.stratosdev.private.wso2.com +manager.service.host.name=stratosdev.private.wso2.com +ms.service.host.name=mashup.stratosdev.private.wso2.com +mb.service.host.name=messaging.stratosdev.private.wso2.com +cep.service.host.name=cep.stratosdev.private.wso2.com +bam.service.host.name=monitor.stratosdev.private.wso2.comso2.com +is.service.host.name=identity.stratosdev.private.wso2.com + + +#stratosliveqa.private.wso2.com + +#app.service.host.name=appserver.stratosliveqa.private.wso2.com +#esb.service.host.name=esb.stratosliveqa.private.wso2.com +#greg.service.host.name=governance.stratosliveqa.private.wso2.com +#dss.service.host.name=data.stratosliveqa.private.wso2.com +#gs.service.host.name=gadget.stratosliveqa.private.wso2.com +#brs.service.host.name=rule.stratosliveqa.private.wso2.com +#bps.service.host.name=process.stratosliveqa.private.wso2.com +#manager.service.host.name=stratosliveqa.private.wso2.com +#ms.service.host.name=mashup.stratosliveqa.private.wso2.com +#mb.service.host.name=messaging.stratosliveqa.private.wso2.com +#cep.service.host.name=cep.stratosliveqa.private.wso2.com +#bam.service.host.name=monitor.stratosliveqa.private.wso2.com +#is.service.host.name=identity.stratosliveqa.private.wso2.com + + diff --git a/modules/integration/tests-ui/src/test/resources/tenantList.csv b/modules/integration/tests-ui/src/test/resources/tenantList.csv new file mode 100644 index 0000000000..23439d5f25 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/tenantList.csv @@ -0,0 +1,16 @@ +"0","admin","admin" +"1","admin123@wso2autoQA0999.org","admin123" +"2","testuser2@wso2autoQA0999.org","admin123" +"3","testuser3@wso2autoQA0999.org","admin123" +"4","testuser4@wso2autoQA0999.org","admin123" +"5","testuser5@wso2autoQA0999.org","admin123" +"6","testuser6@wso2autoQA0999.org","admin123" +"7","testuser7@wso2autoQA0999.org","admin123" +"8","testuser8@wso2autoQA0999.org","admin123" +"9","testuser9@wso2autoQA0999.org","admin123" +"10","testuser10@wso2autoQA0999.org","admin123" +"11","testuser11@wso2autoQA0999.org","admin123" +"12","testuser12@wso2autoQA0999.org","admin123" +"13","testuser13@wso2autoQA0999.org","admin123" +"14","testuser14@wso2autoQA0999.org","admin123" +"15","testuser15@wso2autoQA0999.org","admin123" diff --git a/modules/integration/tests-ui/src/test/resources/testng-server-mgt.xml b/modules/integration/tests-ui/src/test/resources/testng-server-mgt.xml new file mode 100644 index 0000000000..032f82bb3d --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/testng-server-mgt.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests-ui/src/test/resources/userList.csv b/modules/integration/tests-ui/src/test/resources/userList.csv new file mode 100644 index 0000000000..50532c97a5 --- /dev/null +++ b/modules/integration/tests-ui/src/test/resources/userList.csv @@ -0,0 +1,16 @@ +"0","admin","admin" +"1","adminuser","adminuser" +"2","testuser2","testuser2" +"3","testuser3","testuser3" +"4","testuser4","testuser4" +"5","testuser5","testuser5" +"6","testuser6","testuser6" +"7","testuser7","testuser7" +"8","testuser8","testuser8" +"9","testuser9","testuser9" +"10","testuser10","testuser10" +"11","testuser11","testuser12" +"12","testuser12","testuser12" +"13","testuser13","testuser13" +"14","testuser14","testuser14" +"15","testuser15","testuser15" diff --git a/modules/integration/tests/pom.xml b/modules/integration/tests/pom.xml new file mode 100644 index 0000000000..3bfcdad33d --- /dev/null +++ b/modules/integration/tests/pom.xml @@ -0,0 +1,296 @@ + + + + org.wso2.am + integration + 1.7.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + WSO2 API Manager - Integration Test Module + org.wso2.carbon.am.integration.test + jar + + + + + maven-surefire-plugin + false + 2.12.4 + + + -Xmx1024m -XX:PermSize=256m -XX:MaxPermSize=512m + + + src/test/resources/testng-server-mgt.xml + src/test/resources/testng.xml + + + + + maven.test.haltafterfailure + false + + + carbon.zip + + ${basedir}/../../distribution/product/target/wso2am-${project.version}.zip + + + + framework.resource.location + + ${basedir}/src/test/resources/ + + + + server.list + + AM + + + + usedefaultlisteners + false + + ${basedir}/target/security-verifier/ + ${basedir}/target/emma + ${basedir}/src/test/resources/instrumentation.txt + ${basedir}/src/test/resources/filters.txt + ${basedir}/target/emma + + ${basedir}/target + + + + maven-dependency-plugin + + + + copy-emma-dependencies + compile + + copy-dependencies + + + ${project.build.directory}/emma + jar + emma,org.wso2.carbon.automation.core + + + + + + copy-secVerifier + compile + + copy-dependencies + + + ${basedir}/target/security-verifier + aar + SecVerifier + true + + + + + unpack-mar-jks + compile + + unpack + + + + + org.wso2.am + wso2am + ${project.version} + zip + true + ${basedir}/target/tobeCopied/ + **/*.jks,**/*.mar,**/axis2_client.xml + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + + test-jar + + + + + + org.apache.maven.plugins + maven-surefire-report-plugin + 2.7.1 + + ${basedir}/target/report + registry-api-test + + + + integration-test + + report-only + + + + + + + maven-resources-plugin + 2.6 + + + copy-resources-jks + compile + + copy-resources + + + ${basedir}/src/test/resources/keystores/products + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/resources/security/ + + + **/*.jks + + + + + + + copy-axis2files + compile + + copy-resources + + + ${basedir}/src/test/resources/axis2config + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/conf/axis2/ + + + **/*.xml + + + + + + + copy-resources-mar + compile + + copy-resources + + + ${basedir}/src/test/resources/client/modules + + + + + ${basedir}/target/tobeCopied/wso2am-${project.version}/repository/deployment/client/modules + + + **/*.mar + + + + + + + + + + + + + org.wso2.am + org.wso2.am.backend.service + 1.7.0-SNAPSHOT + + + org.wso2.carbon + org.wso2.carbon.apimgt.api + 1.2.0 + + + org.codehaus.jettison.wso2 + jettison + ${orbit.version.jettison} + + + emma + emma + ${emma.version} + + + org.wso2.carbon + SecVerifier + ${carbon.platform.version} + aar + + + org.wso2.carbon.automation + org.wso2.carbon.automation.api + ${test-automation-framework-version} + + + org.wso2.carbon.automation + org.wso2.carbon.automation.core + ${test-automation-framework-version} + + + org.wso2.carbon.automation + org.wso2.carbon.automation.utils + ${test-automation-framework-version} + + + org.wso2.carbon.automation + org.wso2.carbon.automation.tools.jmeter + ${test-automation-framework-version} + + + org.testng + testng + 6.1.1 + test + + + org.wso2.carbon + org.wso2.carbon.integration.framework + 4.2.0 + + + org.wso2.carbon + org.wso2.carbon.apimgt.hostobjects + 1.2.0 + + + commons-digester + commons-digester + 2.1 + + + + 4.2.5 + + diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/APIManagerIntegrationTest.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/APIManagerIntegrationTest.java new file mode 100644 index 0000000000..f38525d00a --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/APIManagerIntegrationTest.java @@ -0,0 +1,745 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests; + +import org.apache.axiom.attachments.ByteArrayDataSource; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.util.AXIOMUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.Assert; +import org.wso2.carbon.automation.api.clients.security.SecurityAdminServiceClient; +import org.wso2.carbon.automation.core.ProductConstant; +import org.wso2.carbon.automation.core.annotations.ExecutionEnvironment; +import org.wso2.carbon.automation.core.utils.UserInfo; +import org.wso2.carbon.automation.core.utils.UserListCsvReader; +import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentBuilder; +import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentVariables; +import org.wso2.carbon.automation.core.utils.environmentutils.ProductUrlGeneratorUtil; +import org.wso2.carbon.automation.core.utils.frameworkutils.FrameworkFactory; +import org.wso2.carbon.automation.core.utils.frameworkutils.FrameworkProperties; +import org.wso2.carbon.automation.core.utils.frameworkutils.productvariables.ProductVariables; +import org.wso2.carbon.automation.utils.esb.ESBTestCaseUtils; +import org.wso2.carbon.automation.utils.esb.EndpointGenerator; +import org.wso2.carbon.automation.utils.esb.StockQuoteClient; +import org.wso2.carbon.automation.utils.services.ServiceDeploymentUtil; +import org.wso2.carbon.security.mgt.stub.config.SecurityAdminServiceSecurityConfigExceptionException; +import org.wso2.carbon.sequences.stub.types.SequenceEditorException; + +import javax.activation.DataHandler; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public abstract class APIManagerIntegrationTest { + protected Log log = LogFactory.getLog(getClass()); + protected StockQuoteClient axis2Client; + protected EnvironmentVariables amServer; + protected UserInfo userInfo; + protected OMElement synapseConfiguration = null; + protected ESBTestCaseUtils esbUtils; + private List proxyServicesList = null; + private List sequencesList = null; + private List endpointsList = null; + private List localEntryList = null; + private List messageProcessorsList = null; + private List messageStoresList = null; + private List sequenceTemplateList = null; + private List apiList = null; + private List priorityExecutorList = null; + + + protected void init() throws Exception { + init(2); + + } + + protected void init(int userId) throws Exception { + axis2Client = new StockQuoteClient(); + userInfo = UserListCsvReader.getUserInfo(userId); + EnvironmentBuilder builder = new EnvironmentBuilder().am(userId); + amServer = builder.build().getAm(); + esbUtils = new ESBTestCaseUtils(); + } + + protected void cleanup() throws Exception { + try { + if (synapseConfiguration != null) { + esbUtils.deleteArtifact(synapseConfiguration, amServer.getBackEndUrl(), amServer.getSessionCookie()); + if (ExecutionEnvironment.stratos.name().equalsIgnoreCase(getExecutionEnvironment()) || isClusterEnabled()) { + + long deploymentDelay = FrameworkFactory.getFrameworkProperties( + ProductConstant.ESB_SERVER_NAME).getEnvironmentVariables().getDeploymentDelay(); + Thread.sleep(deploymentDelay); + Iterator proxies = synapseConfiguration.getChildrenWithLocalName("proxy"); + while (proxies.hasNext()) { + String proxy = proxies.next().getAttributeValue(new QName("name")); + + Assert.assertTrue(isProxyWSDlNotExist(getProxyServiceURLHttp(proxy), deploymentDelay) + , "UnDeployment Synchronizing failed in workers"); + Assert.assertTrue(isProxyWSDlNotExist(getProxyServiceURLHttp(proxy), deploymentDelay) + , "UnDeployment Synchronizing failed in workers"); + Assert.assertTrue(isProxyWSDlNotExist(getProxyServiceURLHttp(proxy), deploymentDelay) + , "UnDeployment Synchronizing failed in workers"); + } + } + } + + deleteProxyServices(); + + deleteSequences(); + + deleteEndpoints(); + + deleteMessageProcessors(); + + deleteMessageStores(); + + deleteSequenceTemplates(); + + deleteLocalEntries(); + + deleteApi(); + + deletePriorityExecutors(); + + } finally { + synapseConfiguration = null; + proxyServicesList = null; + messageProcessorsList = null; + proxyServicesList = null; + sequencesList = null; + endpointsList = null; + localEntryList = null; + apiList = null; + priorityExecutorList = null; + if (axis2Client != null) { + axis2Client.destroy(); + } + axis2Client = null; + userInfo = null; + amServer = null; + esbUtils = null; + + } + } + + protected String getMainSequenceURL() { + String mainSequenceUrl = amServer.getServiceUrl(); + if (mainSequenceUrl.endsWith("/services")) { + mainSequenceUrl = mainSequenceUrl.replace("/services", ""); + } + return mainSequenceUrl + "/"; + + } + + protected String getMainSequenceURLHttps() { + String mainSequenceUrl = amServer.getSecureServiceUrl(); + if (mainSequenceUrl.endsWith("/services")) { + mainSequenceUrl = mainSequenceUrl.replace("/services", ""); + } + return mainSequenceUrl + "/"; + + } + + protected String getServerURLHttp() { + return getServerBackendUrlHttp(); + } + + protected String getServerURLHttps() { + String serverUrl = FrameworkFactory.getFrameworkProperties(ProductConstant.AM_SERVER_NAME).getProductVariables().getBackendUrl(); + if (serverUrl.endsWith("/services")) { + serverUrl = serverUrl.replace("/services", ""); + } + if (serverUrl.endsWith("/")) { + serverUrl = serverUrl.substring(0, (serverUrl.length() - 1)); + } + return serverUrl; + } + + protected String getProxyServiceURLHttp(String proxyServiceName) { + return amServer.getServiceUrl() + "/" + proxyServiceName; + } + + protected String getApiInvocationURLHttp(String apiContext) { + if (isBuilderEnabled()) { + return getMainSequenceURL() + apiContext; + } else { + return getGatewayServerURLHttp() + apiContext; + } + } + + protected String getApiInvocationURLHttps(String apiContext) { + if (isBuilderEnabled()) { + return getMainSequenceURLHttps() + apiContext; + } else { + return getGatewayServerURLHttps() + apiContext; + } + } + + protected String getProxyServiceURLHttps(String proxyServiceName) { + return amServer.getSecureServiceUrl() + "/" + proxyServiceName; + } + + protected void loadSampleESBConfiguration(int sampleNo) throws Exception { + OMElement synapseSample = esbUtils.loadSampleESBConfiguration(sampleNo); + updateESBConfiguration(synapseSample); + + } + + protected void loadESBConfigurationFromClasspath(String relativeFilePath) throws Exception { + relativeFilePath = relativeFilePath.replaceAll("[\\\\/]", File.separator); + OMElement synapseConfig = esbUtils.loadClasspathResource(relativeFilePath); + updateESBConfiguration(synapseConfig); + + } + + protected void updateESBConfiguration(OMElement synapseConfig) throws Exception { + + if (synapseConfiguration == null) { + synapseConfiguration = synapseConfig; + } else { + Iterator itr = synapseConfig.cloneOMElement().getChildElements(); + while (itr.hasNext()) { + synapseConfiguration.addChild(itr.next()); + } + } + esbUtils.updateESBConfiguration(setEndpoints(synapseConfig), amServer.getBackEndUrl(), amServer.getSessionCookie()); + + if (ExecutionEnvironment.stratos.name().equalsIgnoreCase(getExecutionEnvironment()) || isClusterEnabled()) { + long deploymentDelay = FrameworkFactory.getFrameworkProperties( + ProductConstant.ESB_SERVER_NAME).getEnvironmentVariables().getDeploymentDelay(); + Thread.sleep(deploymentDelay); + Iterator proxies = synapseConfig.getChildrenWithLocalName("proxy"); + while (proxies.hasNext()) { + String proxy = proxies.next().getAttributeValue(new QName("name")); + + Assert.assertTrue(isProxyWSDlExist(getProxyServiceURLHttp(proxy), deploymentDelay) + , "Deployment Synchronizing failed in workers"); + Assert.assertTrue(isProxyWSDlExist(getProxyServiceURLHttp(proxy), deploymentDelay) + , "Deployment Synchronizing failed in workers"); + Assert.assertTrue(isProxyWSDlExist(getProxyServiceURLHttp(proxy), deploymentDelay) + , "Deployment Synchronizing failed in workers"); + } + } + } + + protected void addProxyService(OMElement proxyConfig) throws Exception { + String proxyName = proxyConfig.getAttributeValue(new QName("name")); + if (esbUtils.isProxyServiceExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), proxyName)) { + esbUtils.deleteProxyService(amServer.getBackEndUrl(), amServer.getSessionCookie(), proxyName); + } + if (proxyServicesList == null) { + proxyServicesList = new ArrayList(); + } + proxyServicesList.add(proxyName); + esbUtils.addProxyService(amServer.getBackEndUrl(), amServer.getSessionCookie(), setEndpoints(proxyConfig)); + + if (ExecutionEnvironment.stratos.name().equalsIgnoreCase(getExecutionEnvironment())) { + long deploymentDelay = FrameworkFactory.getFrameworkProperties( + ProductConstant.AM_SERVER_NAME).getEnvironmentVariables().getDeploymentDelay(); + + Assert.assertTrue(isProxyWSDlExist(getProxyServiceURLHttp(proxyName), deploymentDelay) + , "Deployment Synchronizing failed in workers"); + Assert.assertTrue(isProxyWSDlExist(getProxyServiceURLHttp(proxyName), deploymentDelay) + , "Deployment Synchronizing failed in workers"); + Assert.assertTrue(isProxyWSDlExist(getProxyServiceURLHttp(proxyName), deploymentDelay) + , "Deployment Synchronizing failed in workers"); + + } + } + + protected void isProxyDeployed(String proxyServiceName) throws Exception { + Assert.assertTrue(esbUtils.isProxyDeployed(amServer.getBackEndUrl(), amServer.getSessionCookie(), + proxyServiceName), "Proxy Deployment failed or time out"); + } + + protected void deleteProxyService(String proxyServiceName) throws Exception { + if (esbUtils.isProxyServiceExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), proxyServiceName)) { + esbUtils.deleteProxyService(amServer.getBackEndUrl(), amServer.getSessionCookie(), proxyServiceName); + Assert.assertTrue(esbUtils.isProxyUnDeployed(amServer.getBackEndUrl(), amServer.getSessionCookie(), + proxyServiceName), "Proxy Deletion failed or time out"); + } + if (proxyServicesList != null && proxyServicesList.contains(proxyServiceName)) { + proxyServicesList.remove(proxyServiceName); + } + } + + protected void deleteSequence(String sequenceName) + throws SequenceEditorException, RemoteException { + if (esbUtils.isSequenceExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), sequenceName)) { + esbUtils.deleteSequence(amServer.getBackEndUrl(), amServer.getSessionCookie(), sequenceName); + } + if (sequencesList != null && sequencesList.contains(sequenceName)) { + sequencesList.remove(sequenceName); + } + } + + protected void addSequence(OMElement sequenceConfig) throws Exception { + String sequenceName = sequenceConfig.getAttributeValue(new QName("name")); + if (esbUtils.isSequenceExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), sequenceName)) { + esbUtils.deleteSequence(amServer.getBackEndUrl(), amServer.getSessionCookie(), sequenceName); + } + esbUtils.addSequence(amServer.getBackEndUrl(), amServer.getSessionCookie(), setEndpoints(sequenceConfig)); + if (sequencesList == null) { + sequencesList = new ArrayList(); + } + sequencesList.add(sequenceName); + } + + protected void addEndpoint(OMElement endpointConfig) + throws Exception { + String endpointName = endpointConfig.getAttributeValue(new QName("name")); + if (esbUtils.isSequenceExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), endpointName)) { + esbUtils.deleteEndpoint(amServer.getBackEndUrl(), amServer.getSessionCookie(), endpointName); + } + esbUtils.addEndpoint(amServer.getBackEndUrl(), amServer.getSessionCookie(), setEndpoints(endpointConfig)); + if (endpointsList == null) { + endpointsList = new ArrayList(); + } + endpointsList.add(endpointName); + + } + + protected void addLocalEntry(OMElement localEntryConfig) throws Exception { + String localEntryName = localEntryConfig.getAttributeValue(new QName("key")); + if (esbUtils.isLocalEntryExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), localEntryName)) { + esbUtils.deleteLocalEntry(amServer.getBackEndUrl(), amServer.getSessionCookie(), localEntryName); + } + esbUtils.addLocalEntry(amServer.getBackEndUrl(), amServer.getSessionCookie(), localEntryConfig); + + if (localEntryList == null) { + localEntryList = new ArrayList(); + } + localEntryList.add(localEntryName); + } + + protected void addMessageProcessor(OMElement messageProcessorConfig) throws Exception { + String messageProcessorName = messageProcessorConfig.getAttributeValue(new QName("name")); + if (esbUtils.isMessageProcessorExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), messageProcessorName)) { + esbUtils.deleteMessageProcessor(amServer.getBackEndUrl(), amServer.getSessionCookie(), messageProcessorName); + } + esbUtils.addMessageProcessor(amServer.getBackEndUrl(), amServer.getSessionCookie(), setEndpoints(messageProcessorConfig)); + if (messageProcessorsList == null) { + messageProcessorsList = new ArrayList(); + } + messageProcessorsList.add(messageProcessorName); + } + + protected void addMessageStore(OMElement messageStoreConfig) throws Exception { + String messageStoreName = messageStoreConfig.getAttributeValue(new QName("name")); + if (esbUtils.isMessageStoreExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), messageStoreName)) { + esbUtils.deleteMessageStore(amServer.getBackEndUrl(), amServer.getSessionCookie(), messageStoreName); + } + esbUtils.addMessageStore(amServer.getBackEndUrl(), amServer.getSessionCookie(), setEndpoints(messageStoreConfig)); + if (messageStoresList == null) { + messageStoresList = new ArrayList(); + } + messageStoresList.add(messageStoreName); + } + + protected void addSequenceTemplate(OMElement sequenceTemplate) throws Exception { + String name = sequenceTemplate.getAttributeValue(new QName("name")); + if (esbUtils.isSequenceTemplateExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), name)) { + esbUtils.deleteSequenceTemplate(amServer.getBackEndUrl(), amServer.getSessionCookie(), name); + } + esbUtils.addSequenceTemplate(amServer.getBackEndUrl(), amServer.getSessionCookie(), setEndpoints(sequenceTemplate)); + + if (sequenceTemplateList == null) { + sequenceTemplateList = new ArrayList(); + } + sequenceTemplateList.add(name); + } + + protected void addApi(OMElement api) throws Exception { + String apiName = api.getAttributeValue(new QName("name")); + if (esbUtils.isApiExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), apiName)) { + esbUtils.deleteApi(amServer.getBackEndUrl(), amServer.getSessionCookie(), apiName); + } + esbUtils.addAPI(amServer.getBackEndUrl(), amServer.getSessionCookie(), api); + + if (apiList == null) { + apiList = new ArrayList(); + } + apiList.add(apiName); + } + + protected void addPriorityExecutor(OMElement priorityExecutor) throws Exception { + String executorName = priorityExecutor.getAttributeValue(new QName("name")); + if (esbUtils.isPriorityExecutorExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), executorName)) { + esbUtils.deletePriorityExecutor(amServer.getBackEndUrl(), amServer.getSessionCookie(), executorName); + } + esbUtils.addPriorityExecutor(amServer.getBackEndUrl(), amServer.getSessionCookie(), priorityExecutor); + + if (priorityExecutorList == null) { + priorityExecutorList = new ArrayList(); + } + priorityExecutorList.add(executorName); + } + + protected void applySecurity(String serviceName, int policyId, String[] userGroups) + throws SecurityAdminServiceSecurityConfigExceptionException, RemoteException, + InterruptedException { + SecurityAdminServiceClient securityAdminServiceClient = + new SecurityAdminServiceClient(amServer.getBackEndUrl(), amServer.getSessionCookie()); + if (FrameworkFactory.getFrameworkProperties(ProductConstant.ESB_SERVER_NAME).getEnvironmentSettings().is_runningOnStratos()) { + + securityAdminServiceClient.applySecurity(serviceName, policyId + "", userGroups, + new String[]{"service.jks"}, "service.jks"); + } else { + securityAdminServiceClient.applySecurity(serviceName, policyId + "", userGroups, + new String[]{"wso2carbon.jks"}, "wso2carbon.jks"); + } + log.info("Security Scenario " + policyId + " Applied"); + + Thread.sleep(1000); + + } + + protected OMElement replaceEndpoints(String relativePathToConfigFile, String serviceName, + String port) + throws XMLStreamException, FileNotFoundException { + String config = esbUtils.loadClasspathResource(relativePathToConfigFile).toString(); + config = config.replace("http://localhost:" + port + "/services/" + serviceName, + getBackEndServiceUrl(serviceName)); + + return AXIOMUtil.stringToOM(config); + } + + private void deleteMessageProcessors() { + if (messageProcessorsList != null) { + Iterator itr = messageProcessorsList.iterator(); + while (itr.hasNext()) { + String messageProcessor = itr.next(); + try { + if (esbUtils.isMessageProcessorExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), messageProcessor)) { + esbUtils.deleteMessageProcessor(amServer.getBackEndUrl(), amServer.getSessionCookie(), messageProcessor); + } + } catch (Exception e) { + Assert.fail("while undeploying Message Processor. " + e.getMessage()); + } + } + messageProcessorsList.clear(); + } + } + + private void deleteMessageStores() { + if (messageStoresList != null) { + Iterator itr = messageStoresList.iterator(); + while (itr.hasNext()) { + String messageStore = itr.next(); + try { + if (esbUtils.isMessageStoreExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), messageStore)) { + esbUtils.deleteMessageStore(amServer.getBackEndUrl(), amServer.getSessionCookie(), messageStore); + } + } catch (Exception e) { + Assert.fail("while undeploying Message store. " + e.getMessage()); + } + } + messageStoresList.clear(); + } + } + + private void deleteSequences() { + if (sequencesList != null) { + Iterator itr = sequencesList.iterator(); + while (itr.hasNext()) { + String sequence = itr.next(); + if (!sequence.equalsIgnoreCase("fault")) { + try { + if (esbUtils.isSequenceExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), sequence)) { + esbUtils.deleteSequence(amServer.getBackEndUrl(), amServer.getSessionCookie(), sequence); + } + } catch (Exception e) { + Assert.fail("while undeploying Sequence. " + e.getMessage()); + } + } + } + sequencesList.clear(); + } + } + + private void deleteProxyServices() { + if (proxyServicesList != null) { + Iterator itr = proxyServicesList.iterator(); + while (itr.hasNext()) { + String proxyName = itr.next(); + try { + if (esbUtils.isProxyServiceExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), proxyName)) { + esbUtils.deleteProxyService(amServer.getBackEndUrl(), amServer.getSessionCookie(), proxyName); + + if (ExecutionEnvironment.stratos.name().equalsIgnoreCase(getExecutionEnvironment())) { + long deploymentDelay = FrameworkFactory.getFrameworkProperties( + ProductConstant.AM_SERVER_NAME).getEnvironmentVariables().getDeploymentDelay(); + + Assert.assertTrue(isProxyWSDlNotExist(getProxyServiceURLHttp(proxyName), deploymentDelay) + , "Proxy UnDeployment Synchronizing failed in workers"); + Assert.assertTrue(isProxyWSDlNotExist(getProxyServiceURLHttp(proxyName), deploymentDelay) + , "Proxy UnDeployment Synchronizing failed in workers"); + Assert.assertTrue(isProxyWSDlNotExist(getProxyServiceURLHttp(proxyName), deploymentDelay) + , "Proxy UnDeployment Synchronizing failed in workers"); + + } + } + } catch (Exception e) { + Assert.fail("while undeploying Proxy. " + e.getMessage()); + } + } + proxyServicesList.clear(); + } + } + + private void deleteEndpoints() { + if (endpointsList != null) { + Iterator itr = endpointsList.iterator(); + while (itr.hasNext()) { + String endpoint = itr.next(); + try { + if (esbUtils.isEndpointExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), endpoint)) { + esbUtils.deleteEndpoint(amServer.getBackEndUrl(), amServer.getSessionCookie(), endpoint); + } + } catch (Exception e) { + Assert.fail("while undeploying Endpoint. " + e.getMessage()); + } + } + endpointsList.clear(); + } + } + + private void deleteLocalEntries() { + if (localEntryList != null) { + Iterator itr = localEntryList.iterator(); + while (itr.hasNext()) { + String localEntry = itr.next(); + try { + if (esbUtils.isLocalEntryExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), localEntry)) { + esbUtils.deleteLocalEntry(amServer.getBackEndUrl(), amServer.getSessionCookie(), localEntry); + } + } catch (Exception e) { + Assert.fail("while undeploying LocalEntry. " + e.getMessage()); + } + } + localEntryList.clear(); + } + } + + private void deleteSequenceTemplates() { + if (sequenceTemplateList != null) { + Iterator itr = sequenceTemplateList.iterator(); + while (itr.hasNext()) { + String localEntry = itr.next(); + try { + if (esbUtils.isSequenceTemplateExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), localEntry)) { + esbUtils.deleteSequenceTemplate(amServer.getBackEndUrl(), amServer.getSessionCookie(), localEntry); + } + } catch (Exception e) { + Assert.fail("while undeploying Sequence Template. " + e.getMessage()); + } + } + sequenceTemplateList.clear(); + } + } + + private void deleteApi() { + if (apiList != null) { + Iterator itr = apiList.iterator(); + while (itr.hasNext()) { + String api = itr.next(); + try { + if (esbUtils.isApiExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), api)) { + esbUtils.deleteApi(amServer.getBackEndUrl(), amServer.getSessionCookie(), api); + } + } catch (Exception e) { + Assert.fail("while undeploying Api. " + e.getMessage()); + } + } + apiList.clear(); + } + } + + private void deletePriorityExecutors() { + if (priorityExecutorList != null) { + Iterator itr = priorityExecutorList.iterator(); + while (itr.hasNext()) { + String executor = itr.next(); + try { + if (esbUtils.isPriorityExecutorExist(amServer.getBackEndUrl(), amServer.getSessionCookie(), executor)) { + esbUtils.deleteProxyService(amServer.getBackEndUrl(), amServer.getSessionCookie(), executor); + } + } catch (Exception e) { + Assert.fail("while undeploying Priority Executor. " + e.getMessage()); + } + } + priorityExecutorList.clear(); + } + } + + protected boolean isRunningOnStratos() { + return FrameworkFactory.getFrameworkProperties(ProductConstant.AM_SERVER_NAME).getEnvironmentSettings().is_runningOnStratos(); + } + + protected String getResourceLocation() { + return ProductConstant.getResourceLocations(ProductConstant.AM_SERVER_NAME); + } + + protected String getBackEndServiceUrl(String serviceName) { + return EndpointGenerator.getEndpointServiceUrl(serviceName); + } + + protected OMElement setEndpoints(OMElement synapseConfig) throws XMLStreamException { + if (isBuilderEnabled()) { + return synapseConfig; + } + String config = replaceEndpoints(synapseConfig.toString()); + return AXIOMUtil.stringToOM(config); + } + + protected DataHandler setEndpoints(DataHandler dataHandler) + throws XMLStreamException, IOException { + + String config = readInputStreamAsString(dataHandler.getInputStream()); + config = replaceEndpoints(config); + ByteArrayDataSource dbs = new ByteArrayDataSource(config.getBytes()); + return new DataHandler(dbs); + } + + protected String[] getUserRole(String userId) { + if (Integer.parseInt(userId) <= 1) { + return new String[]{ProductConstant.ADMIN_ROLE_NAME}; + } else { + return new String[]{ProductConstant.DEFAULT_PRODUCT_ROLE}; + } + + } + + public boolean isBuilderEnabled() { + return FrameworkFactory.getFrameworkProperties(ProductConstant.AM_SERVER_NAME).getEnvironmentSettings().is_builderEnabled(); + } + + private boolean isClusterEnabled() { + return FrameworkFactory.getFrameworkProperties(ProductConstant.AM_SERVER_NAME).getEnvironmentSettings().isClusterEnable(); + } + + private String getExecutionEnvironment() { + return FrameworkFactory.getFrameworkProperties(ProductConstant.AM_SERVER_NAME).getEnvironmentSettings().executionEnvironment(); + } + + private boolean isProxyWSDlExist(String serviceUrl, long synchronizingDelay) + throws Exception { + return new ServiceDeploymentUtil().isServiceWSDlExist(serviceUrl, synchronizingDelay); + + } + + private boolean isProxyWSDlNotExist(String serviceUrl, long synchronizingDelay) + throws Exception { + + return new ServiceDeploymentUtil().isServiceWSDlNotExist(serviceUrl, synchronizingDelay); + + } + + private String replaceEndpoints(String config) { + String service = getBackEndServiceUrl(""); + + config = config.replace("http://localhost:9000/services/" + , service); + config = config.replace("http://127.0.0.1:9000/services/" + , service); + return config; + } + + private String readInputStreamAsString(InputStream in) + throws IOException { + + BufferedInputStream bis = new BufferedInputStream(in); + ByteArrayOutputStream buf = new ByteArrayOutputStream(); + int result = bis.read(); + while (result != -1) { + byte b = (byte) result; + buf.write(b); + result = bis.read(); + } + return buf.toString(); + } + + private String getServerBackendUrlHttp() { + FrameworkProperties frameworkProperties = FrameworkFactory.getFrameworkProperties(ProductConstant.AM_SERVER_NAME); + boolean webContextEnabled = frameworkProperties.getEnvironmentSettings().isEnableCarbonWebContext(); + boolean portEnabled = frameworkProperties.getEnvironmentSettings().isEnablePort(); + + ProductVariables amServerInfo = frameworkProperties.getProductVariables(); + String webContextRoot = amServerInfo.getWebContextRoot(); + String httpPort = amServerInfo.getHttpPort(); + String hostName = amServerInfo.getHostName(); + + String url = "http://" + hostName; + if (portEnabled && httpPort != null) { + url = url + ":" + httpPort; + } + if (webContextEnabled && webContextRoot != null) { + url = url + "/" + webContextRoot; + } + + return url; + } + + protected String getStoreServerURLHttp() { + return ProductUrlGeneratorUtil.prop.get("am.distributed.store.http.url").toString(); + } + + protected String getStoreServerURLHttps() { + return ProductUrlGeneratorUtil.prop.get("am.distributed.store.https.url").toString(); + } + + protected String getPublisherServerURLHttp() { + return ProductUrlGeneratorUtil.prop.get("am.distributed.publisher.http.url").toString(); + } + + protected String getPublisherServerURLHttps() { + return ProductUrlGeneratorUtil.prop.get("am.distributed.publisher.https.url").toString(); + } + + protected String getGatewayServerURLHttp() { + return ProductUrlGeneratorUtil.prop.get("am.distributed.gateway.http.url").toString(); + } + + protected String getGatewayServerURLHttps() { + return ProductUrlGeneratorUtil.prop.get("am.distributed.gateway.https.url").toString(); + } + + protected String getTestApplicationUsagePublisherServerURLHttp() { + return ProductUrlGeneratorUtil.prop.get("am.test.application.usage.http.url").toString(); + } + + protected String getTestApplicationStoreServerURLHttp() { + return ProductUrlGeneratorUtil.prop.get("am.test.application.store.http.url").toString(); + } + + protected String getTestApplicationPublisherServerURLHttp() { + return ProductUrlGeneratorUtil.prop.get("am.test.application.publisher.http.url").toString(); + } + +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/ServerStartupTestCase.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/ServerStartupTestCase.java new file mode 100644 index 0000000000..7ff2c7f00f --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/ServerStartupTestCase.java @@ -0,0 +1,30 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests; + +import org.wso2.carbon.automation.core.ProductConstant; +import org.wso2.carbon.automation.core.tests.ServerStartupBaseTest; + +public class ServerStartupTestCase extends ServerStartupBaseTest { + + @Override + public String getProductName() { + return ProductConstant.AM_SERVER_NAME; + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/header/ContentLengthHeaderTestCase.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/header/ContentLengthHeaderTestCase.java new file mode 100644 index 0000000000..3a0a0db4a1 --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/header/ContentLengthHeaderTestCase.java @@ -0,0 +1,103 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF 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.carbon.am.tests.header; + +import org.apache.axiom.om.OMElement; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.am.tests.APIManagerIntegrationTest; +import org.wso2.carbon.am.tests.util.WireMonitorServer; +import org.wso2.carbon.automation.api.clients.stratos.tenant.mgt.TenantMgtAdminServiceClient; +import org.wso2.carbon.automation.core.annotations.ExecutionEnvironment; +import org.wso2.carbon.automation.core.annotations.SetEnvironment; +import org.wso2.carbon.automation.core.utils.HttpRequestUtil; +import org.wso2.carbon.automation.core.utils.LoginLogoutUtil; +import org.wso2.carbon.automation.core.utils.UserListCsvReader; +import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentBuilder; +import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentVariables; + +import java.io.*; +import java.net.URL; + +/** + * Property Mediator FORCE_HTTP_CONTENT_LENGTH Property Test + */ + +public class ContentLengthHeaderTestCase extends APIManagerIntegrationTest { + public WireMonitorServer wireServer; + private TenantMgtAdminServiceClient tenantMgtAdminServiceClient; + private EnvironmentVariables amServer; + + @BeforeClass(alwaysRun = true) + public void setEnvironment() throws Exception { + super.init(0); + + int userId = 16; + userInfo = UserListCsvReader.getUserInfo(userId); + EnvironmentBuilder builder = new EnvironmentBuilder().am(userId); + amServer = builder.build().getAm(); + + // UserInfo userInfo = UserListCsvReader.getUserInfo(16); + LoginLogoutUtil loginUtil = new LoginLogoutUtil(9443, "localhost"); + + String sessionCookieAdmin = loginUtil.login(userInfo.getUserName(), userInfo.getPassword(), + amServer.getBackEndUrl()); + + // https://localhost:9443/t/abc.com/services + + tenantMgtAdminServiceClient = new TenantMgtAdminServiceClient(amServer.getBackEndUrl(), sessionCookieAdmin); + tenantMgtAdminServiceClient.addTenant("abc.com", "abc123", "abc", "demo"); + + String apiMngrSynapseConfigPath = "/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml"; + String relativeFilePath = apiMngrSynapseConfigPath.replaceAll("[\\\\/]", File.separator); + OMElement apiMngrSynapseConfig = esbUtils.loadClasspathResource(relativeFilePath); + + esbUtils.updateESBConfiguration(setEndpoints(apiMngrSynapseConfig), amServer.getBackEndUrl(), + amServer.getSessionCookie()); + + wireServer = new WireMonitorServer(8991); + } + + @SetEnvironment(executionEnvironments = {ExecutionEnvironment.integration_all}) + @Test(groups = "wso2.am", description = "Test for reading the Content-Length header in the request") + public void testFORCE_HTTP_CONTENT_LENGTHPropertyTest() throws Exception { + + wireServer.start(); + + //axis2Client.sendSimpleStockQuoteRequest("http://localhost:8280/t/abc.com/helloabc/1.0.0", null, "WSO2"); + FileInputStream fis = new FileInputStream("/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml"); + InputStreamReader isr = new InputStreamReader(fis, "UTF8"); + Reader inputReader = new BufferedReader(isr); + + URL postEndpoint = new URL("http://localhost:8280/t/abc.com/stock/1.0.0"); + PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out"))); + HttpRequestUtil.sendPostRequest(inputReader, postEndpoint, out); + String response = wireServer.getCapturedMessage(); + Assert.assertTrue(response.contains("Content-Length"), "Content-Length not found in out going message"); + + } + + @AfterClass(alwaysRun = true) + public void stop() throws Exception { + cleanup(); + } +} + diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/rest/URLMappingRESTTestCase.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/rest/URLMappingRESTTestCase.java new file mode 100644 index 0000000000..6973a1594f --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/rest/URLMappingRESTTestCase.java @@ -0,0 +1,62 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.rest; + +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.am.tests.APIManagerIntegrationTest; +import org.wso2.carbon.automation.core.utils.HttpRequestUtil; +import org.wso2.carbon.automation.core.utils.HttpResponse; +import org.wso2.carbon.automation.utils.httpclient.HttpURLConnectionClient; + +import java.io.*; +import java.net.URL; + +/** + * Related to Patch Automation https://wso2.org/jira/browse/APIMANAGER-769 + * This test class test the Rest URI template patterns like uri-template="/view/*" + */ +public class URLMappingRESTTestCase extends APIManagerIntegrationTest { + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(); + loadESBConfigurationFromClasspath("artifacts" + File.separator + "AM" + + File.separator + "synapseconfigs" + File.separator + "rest" + + File.separator + "url-mapping-synapse.xml"); + } + + @Test(groups = {"wso2.am"}, description = "Sending a Message Via REST to test uri template fix") + public void testRESTURITemplate() throws Exception { + // Before apply this patch uri template not recognize localhost:8280/stockquote/test/ and localhost:8280/stockquote/test + //maps to same resource. It will return correct response only if request hits localhost:8280/stockquote/test + //after fixing issue both will work. + HttpResponse response = HttpRequestUtil.sendGetRequest(getApiInvocationURLHttp("stockquote") + "/test/", null); +// HttpResponse response = HttpRequestUtil.sendGetRequest(getApiInvocationURLHttp("stockquote") + "/test/", null); + Assert.assertEquals(response.getResponseCode(), 200, "Response code mismatch"); + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + super.cleanup(); + } +} + diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/APIApplicationLifeCycleITestCase.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/APIApplicationLifeCycleITestCase.java new file mode 100644 index 0000000000..f67274ba79 --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/APIApplicationLifeCycleITestCase.java @@ -0,0 +1,206 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.sample; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.am.tests.APIManagerIntegrationTest; +import org.wso2.carbon.am.tests.util.bean.APILifeCycleState; +import org.wso2.carbon.am.tests.util.APIMgtTestUtil; +import org.wso2.carbon.am.tests.util.APIPublisherRestClient; +import org.wso2.carbon.am.tests.util.APIStoreRestClient; +import org.wso2.carbon.am.tests.util.bean.*; +import org.wso2.carbon.automation.core.ProductConstant; +import org.wso2.carbon.automation.core.utils.HttpRequestUtil; +import org.wso2.carbon.automation.core.utils.HttpResponse; +import org.wso2.carbon.automation.core.utils.serverutils.ServerConfigurationManager; + +import java.io.File; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class APIApplicationLifeCycleITestCase extends APIManagerIntegrationTest { + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private ServerConfigurationManager serverConfigurationManager; + //move to base class + private String publisherURLHttp; + private String storeURLHttp; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(0); + if (isBuilderEnabled()) { + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + + } else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + apiPublisher = new APIPublisherRestClient(publisherURLHttp); + apiStore = new APIStoreRestClient(storeURLHttp); + } + + @Test(groups = {"wso2.am"}, description = "API Life cycle test case") + public void testAPIApplicationLifeCycleITestCase() throws Exception { + String APIName = "APILifeCycleTestAPI"; + String APIContext = "testAPI"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + //add all option methods + apiPublisher.login(userInfo.getUserName(), userInfo.getPassword()); + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiRequest.setWsdl("https://svn.wso2.org/repos/wso2/carbon/platform/trunk/products/bps/modules/samples/product/src/main/resources/bpel/2.0/MyRoleMexTestProcess/echo.wsdl"); + apiRequest.setVisibility("restricted"); + apiRequest.setRoles("admin"); + apiPublisher.addAPI(apiRequest); + apiPublisher.deleteApi(APIName, APIVersion, providerName); + //add assertion + apiPublisher.addAPI(apiRequest); + APIBean apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisher.getApi(APIName, providerName)); + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + //Test API properties + Assert.assertEquals(apiBean.getId().getApiName(), APIName, "API Name mismatch"); + Assert.assertEquals(apiBean.getContext().trim().substring(apiBean.getContext().indexOf("/") + 1), APIContext, "API context mismatch"); + Assert.assertEquals(apiBean.getId().getVersion(), APIVersion, "API version mismatch"); + Assert.assertEquals(apiBean.getId().getProviderName(), providerName, "Provider Name mismatch"); + for (String tag : apiBean.getTags()) { + Assert.assertTrue(tags.contains(tag), "API tag data mismatched"); + } + Assert.assertEquals(apiBean.getDescription(), description, "API description mismatch"); + apiStore.login(userInfo.getUserName(), userInfo.getPassword()); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, userInfo.getUserName()); + apiStore.subscribe(subscriptionRequest); + + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest("DefaultApplication"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + //Here add API tags and check same have in response. + //Here check same tags are there + //Add some comment to API + //check comment is there + //Add rating + //check rating + Thread.sleep(60000); + // for (int i = 0; i < 19; i++) { + + HttpResponse youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("testAPI/1.0.0/most_popular"), requestHeaders); + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched"); + Assert.assertTrue(youTubeResponse.getData().contains(""), "Response data mismatched"); + + // } + //Do get,post,put,delete all here + //HttpResponse youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("commentRating/1.0.0/most_popular"), requestHeaders); + //Assert.assertEquals(youTubeResponse.getResponseCode(), 503, "Response code mismatched"); + //Thread.sleep(60000); + HttpResponse youTubeResponse1 = HttpRequestUtil.doGet(getApiInvocationURLHttp("testAPI/1.0.0/most_popular"), null); + Assert.assertEquals(youTubeResponse1.getResponseCode(), 401, "Response code mismatched"); + requestHeaders.clear(); + requestHeaders.put("Authorization", "Bearer " + "-wrong-tokent-text-"); + HttpResponse youTubeResponseError = HttpRequestUtil.doGet(getApiInvocationURLHttp("testAPI/1.0.0/most_popular"), null); + Assert.assertEquals(youTubeResponseError.getResponseCode(), 401, "Response code mismatched"); + + apiStore.getAllPublishedAPIs(); + apiStore.getAllApplications(); + apiStore.getPublishedAPIsByApplication("DefaultApplication"); + apiStore.isRatingActivated(); + apiStore.addRatingToAPI(APIName, APIVersion, providerName, "4"); + apiStore.addRatingToAPI(APIName, APIVersion, providerName, "2"); + apiStore.addRatingToAPI(APIName, APIVersion, providerName, "1"); + apiStore.removeRatingFromAPI(APIName, APIVersion, providerName); + apiStore.getAllDocumentationOfApi(APIName, APIVersion, providerName); + //apiStore.getAllPaginatedPublishedAPIs("carbon.super","0","10"); + //Negative cases + apiStore.getPublishedAPIsByApplication("DefaultApplicationWrong"); + apiStore.isRatingActivated(); + apiStore.addRatingToAPI("NoAPI", APIVersion, providerName, "4"); + apiStore.removeRatingFromAPI("NoAPI", APIVersion, providerName); + apiStore.getAllDocumentationOfApi("NoAPI", APIVersion, providerName); + apiRequest.setTags("updated"); + apiRequest.setProvider("admin"); + Thread.sleep(1000); + apiPublisher.updateAPI(apiRequest); + //TODO need to reformat this code after we finalize new APIs + apiPublisher.addDocument(APIName, APIVersion, providerName, "Doc Name", "How To", "In-line", "url-no-need", "summary", ""); + apiPublisher.addDocument(APIName, APIVersion, providerName, "Doc Name", "How To", "URL", "http://www.businesstoday.lk/article.php?article=3549", "summary", ""); + apiPublisher.addDocument(APIName, APIVersion, providerName, "Doc Name", "How To", " File", "url-no-need", "summary", ProductConstant.getResourceLocations(ProductConstant.AM_SERVER_NAME) + + File.separator + "configFiles/tokenTest/" + "api-manager.xml"); + apiPublisher.removeDocumentation(APIName, APIVersion, providerName, "Doc Name", "How To"); + //create application + apiStore.addApplication("test-application", "Gold", "", "this-is-test"); + apiStore.getAllApplications(); + + //Test case to create new application and make subscriptions to that application + SubscriptionRequest subscriptionRequest1 = new SubscriptionRequest(APIName, userInfo.getUserName()); + subscriptionRequest1.setApplicationName("test-application"); + apiStore.subscribe(subscriptionRequest1); + GenerateAppKeyRequest generateAppKeyRequest1 = new GenerateAppKeyRequest("test-application"); + String responseString1 = apiStore.generateApplicationKey(generateAppKeyRequest1).getData(); + JSONObject response1 = new JSONObject(responseString1); + String accessToken1 = response1.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders1 = new HashMap(); + requestHeaders1.put("Authorization", "Bearer " + accessToken1); + HttpResponse youTubeResponseTestApp = HttpRequestUtil.doGet(getApiInvocationURLHttp("testAPI/1.0.0/most_popular"), requestHeaders1); + for (int i = 0; i < 40; i++) { + youTubeResponseTestApp = HttpRequestUtil.doGet(getApiInvocationURLHttp("testAPI/1.0.0/most_popular"), requestHeaders1); + } + Assert.assertEquals(youTubeResponseTestApp.getResponseCode(), 503, "Response code mismatched"); + + //Add comment + apiStore.isCommentActivated(); + apiStore.addComment(APIName, APIVersion, providerName, "this-is-comment"); + apiStore.getRecentlyAddedAPIs("carbon.super", "5"); + + + apiStore.updateApplication("test-application", "test-updated-application", "test-url", "this-is-updated", "bronze"); + apiStore.getAllApplications(); + apiStore.removeApplication("test-updated-application"); + apiStore.getAllSubscriptions(); + apiStore.getAllTags(); + + //Update role permissions + HttpResponse updateTierPermissionResponse = apiPublisher.updatePermissions("Gold", "Deny", "admin"); + JSONObject jsonObject = new JSONObject(updateTierPermissionResponse.getData()); + Assert.assertTrue(!(Boolean) jsonObject.get("error"), "Error while updating tier permission"); + + + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + super.cleanup(); + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/APIUsageBAMIntegrationTestCase.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/APIUsageBAMIntegrationTestCase.java new file mode 100644 index 0000000000..14dbc1ac0f --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/APIUsageBAMIntegrationTestCase.java @@ -0,0 +1,275 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.sample; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.am.tests.APIManagerIntegrationTest; +import org.wso2.carbon.am.tests.util.bean.APILifeCycleState; +import org.wso2.carbon.am.tests.util.APIMgtTestUtil; +import org.wso2.carbon.am.tests.util.APIPublisherRestClient; +import org.wso2.carbon.am.tests.util.APIStoreRestClient; +import org.wso2.carbon.am.tests.util.bean.*; +import org.wso2.carbon.automation.core.ProductConstant; +import org.wso2.carbon.automation.core.utils.HttpRequestUtil; +import org.wso2.carbon.automation.core.utils.HttpResponse; +import org.wso2.carbon.automation.core.utils.serverutils.ServerConfigurationManager; +import org.wso2.carbon.utils.FileManipulator; +import org.wso2.carbon.utils.ServerConstants; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.util.HashMap; +import java.util.Map; + +import static org.testng.Assert.assertNotNull; + +/* +This test case is not run with default API manager integration tests. To run this test we assume that BAM server +is running with port offset 1. If you have changed anything please update api-manager.xml file and master data source +properties file available in /resources/artifacts/AM/configFiles/usagemonitortest directory.For this test case we will +run API manager as a part of integration test and BAM server should up and run by user. In this test we will create API +and do basic API management related operations and usage data will push to BAM. User should deploy usage tool box inside +BAM server(ideally user should setup BAM as we described in statistics help document). And all API manager related +configurations listed on statistics help doc should apply to files available in above mentioned directory +(/resources/artifacts/AM/configFiles/usagemonitortest) + */ +public class APIUsageBAMIntegrationTestCase extends APIManagerIntegrationTest { + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private ServerConfigurationManager serverConfigurationManager; + private String publisherURLHttp; + private String storeURLHttp; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(0); + + if (isBuilderEnabled()) { + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + //If test run in external distributed deployment you need to copy following resources accordingly. + //configFiles/usagemonitortest/api-manager.xml + //configFiles/usagemonitortest/master-datasources.xml + //configFiles/tokenTest/log4j.properties + //Also need to copy the content of /resources/artifacts/AM/jaggery to servers following folder folder + ///repository/deployment/server/jaggeryapps/testapp + serverConfigurationManager = new ServerConfigurationManager(amServer.getBackEndUrl()); + serverConfigurationManager.applyConfiguration(new File(ProductConstant.getResourceLocations(ProductConstant.AM_SERVER_NAME) + + File.separator + "configFiles/usagemonitortest/" + "api-manager.xml")); + String dataSourceDestinationPath = computeDestinationPathForDataSource("master-datasources.xml"); + String dataSourceSourcePath = computeDataSourceResourcePath("master-datasources.xml"); + copyDataSourceFile(dataSourceSourcePath, dataSourceDestinationPath); + serverConfigurationManager.applyConfiguration(new File(ProductConstant.getResourceLocations(ProductConstant.AM_SERVER_NAME) + + File.separator + "configFiles/tokenTest/" + "log4j.properties")); + super.init(0); + + } else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + apiPublisher = new APIPublisherRestClient(publisherURLHttp); + apiStore = new APIStoreRestClient(storeURLHttp); + } + + private void copySampleFile(String sourcePath, String destinationPath) { + File sourceFile = new File(sourcePath); + File destinationFile = new File(destinationPath); + try { + FileManipulator.copyFile(sourceFile, destinationFile); + } catch (IOException e) { + log.error("Error while copying the sample into Jaggery server", e); + } + } + + private void copyDataSourceFile(String sourcePath, String destPath) { + File sourceFile = new File(sourcePath); + File destFile = new File(destPath); + try { + FileManipulator.copyFile(sourceFile, destFile); + } catch (IOException e) { + log.error("Error while copying the sample into Jaggery server", e); + } + } + + private String computeDestinationPath(String fileName) { + String serverRoot = System.getProperty(ServerConstants.CARBON_HOME); + String deploymentPath = serverRoot + "/repository/deployment/server/jaggeryapps/testapp"; + File depFile = new File(deploymentPath); + if (!depFile.exists() && !depFile.mkdir()) { + log.error("Error while creating the deployment folder : " + + deploymentPath); + } + return deploymentPath + File.separator + fileName; + } + + private String computeDestinationPathForDataSource(String fileName) { + String serverRoot = System.getProperty(ServerConstants.CARBON_HOME); + String deploymentPath = serverRoot + "/repository/conf/datasources"; + File depFile = new File(deploymentPath); + if (!depFile.exists() && !depFile.mkdir()) { + log.error("Error while creating the deployment folder : " + + deploymentPath); + } + return deploymentPath + File.separator + fileName; + } + + private String computeJaggeryResourcePath(String fileName) { + + String sourcePath = ProductConstant.getResourceLocations(ProductConstant.AM_SERVER_NAME) + + File.separator + "jaggery/" + fileName; + return sourcePath; + } + + private String computeDataSourceResourcePath(String fileName) { + + String sourcePath = ProductConstant.getResourceLocations(ProductConstant.AM_SERVER_NAME) + + File.separator + "configFiles/usagemonitortest/" + fileName; + return sourcePath; + } + + @Test(groups = {"wso2.am"}, description = "API Life cycle test case") + public void usageDataTestCase() throws Exception { + String APIName = "UsageTestAPI"; + String APIContext = "UsageTestAPI"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager usage integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + apiPublisher.login(userInfo.getUserName(), userInfo.getPassword()); + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiPublisher.addAPI(apiRequest); + apiPublisher.deleteApi(APIName, APIVersion, providerName); + apiPublisher.addAPI(apiRequest); + APIBean apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisher.getApi(APIName, providerName)); + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + apiStore.login(userInfo.getUserName(), userInfo.getPassword()); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, userInfo.getUserName()); + apiStore.subscribe(subscriptionRequest); + apiPublisher.addDocument(APIName, APIVersion, providerName, "Doc-Name", "How To", "In-line", "url-no-need", "summary", ""); + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest("DefaultApplication"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + HttpResponse youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("UsageTestAPI/1.0.0/most_popular"), requestHeaders); + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched"); + //Here will do 20 successful invocations + for (int i = 0; i < 20; i++) { + youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("UsageTestAPI/1.0.0/most_popular"), requestHeaders); + } + Thread.sleep(60000); + //Here will do 20 faulty invocations + String APINameFaultyAPI = "UsageTestAPIFaultyAPI"; + String APIContextFaultyAPI = "UsageTestAPIFaultyAPI"; + String tagsFaultyAPI = "youtube, video, media"; + //this url should not exists and then it will return with API fault invocation + String urlFaultyAPI = "http://thisiswrong.com/feeds/api/standardfeeds"; + String descriptionFaultyAPI = "This is test API create by API manager usage integration test"; + String APIVersionFaultyAPI = "1.0.0"; + APIRequest apiRequestFaultyAPI = new APIRequest(APINameFaultyAPI, APIContextFaultyAPI, new URL(urlFaultyAPI)); + apiRequestFaultyAPI.setTags(tagsFaultyAPI); + apiRequestFaultyAPI.setDescription(descriptionFaultyAPI); + apiRequestFaultyAPI.setVersion(APIVersionFaultyAPI); + apiPublisher.addAPI(apiRequestFaultyAPI); + APIBean apiBeanFaultyAPI = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisher.getApi(APINameFaultyAPI, providerName)); + APILifeCycleStateRequest updateRequestFaultyAPI = new APILifeCycleStateRequest(APINameFaultyAPI, providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequestFaultyAPI); + SubscriptionRequest subscriptionRequestFaultyAPI = new SubscriptionRequest(APINameFaultyAPI, userInfo.getUserName()); + apiStore.subscribe(subscriptionRequestFaultyAPI); + apiPublisher.addDocument(APINameFaultyAPI, APIVersionFaultyAPI, providerName, "Doc-Name", "How To", "In-line", "url-no-need", "summary", ""); + GenerateAppKeyRequest generateAppKeyRequestFaultyAPI = new GenerateAppKeyRequest("DefaultApplication"); + String responseStringFaultyAPI = apiStore.generateApplicationKey(generateAppKeyRequestFaultyAPI).getData(); + JSONObject responseFaultyAPI = new JSONObject(responseStringFaultyAPI); + String accessTokenFaultyAPI = responseFaultyAPI.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeadersFaultyAPI = new HashMap(); + requestHeadersFaultyAPI.put("Authorization", "Bearer " + accessTokenFaultyAPI); + HttpResponse youTubeResponseFaultyAPI = HttpRequestUtil.doGet(getApiInvocationURLHttp("UsageTestAPIFaultyAPI/1.0.0/most_popular"), requestHeadersFaultyAPI); + Assert.assertEquals(youTubeResponseFaultyAPI.getResponseCode(), 500, "Respofnse code mismatched"); + for (int i = 0; i < 20; i++) { + youTubeResponseFaultyAPI = HttpRequestUtil.doGet(getApiInvocationURLHttp("UsageTestAPIFaultyAPI/1.0.0/incorrect"), requestHeaders); + } + + //host object tests + String fileName = "testUsageWithBAM.jag"; + String sourcePath = computeJaggeryResourcePath(fileName); + String destinationPath = computeDestinationPath(fileName); + copySampleFile(sourcePath, destinationPath); + + Thread.sleep(240000); + String finalOutputUsageTest = null; + //ClientConnectionUtil.waitForPort(9763, ""); + try { + URL jaggeryURL = new URL(getTestApplicationUsagePublisherServerURLHttp()); + URLConnection jaggeryServerConnection = jaggeryURL.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader( + jaggeryServerConnection.getInputStream())); + + String inputLine; + while ((inputLine = in.readLine()) != null) { + finalOutputUsageTest = inputLine; + } + String[] arr = finalOutputUsageTest.split("=="); + System.out.println(finalOutputUsageTest); + validateUsageResponseArray(arr); + in.close(); + } catch (IOException e) { + log.error("Error while invoking test application to test publisher host object"); + } finally { + assertNotNull(finalOutputUsageTest, "Result cannot be null"); + } + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + super.cleanup(); + } + + //take exact count + public static boolean validateUsageResponseArray(String[] array) { + //This order is based on the operations of jaggery file operation order + //If we edit jaggary file we need to modify this as well + Assert.assertNotNull(array[1], "Error while getting API Usage for Subscriber from API publisher host object (getAPIUsageforSubscriber)"); + Assert.assertNotNull(array[2], "Error while getting API Faulty Analyze By Time from API publisher host object (getAPIFaultyAnalyzeByTime)"); + Assert.assertNotNull(array[3], "Error while getting API Response Fault Count from API publisher host object (getAPIResponseFaultCount)"); + Assert.assertNotNull(array[4], "Error while getting external api stores from API publisher host object (getAPIUsageByResourcePath)"); + Assert.assertNotNull(array[5], "Error while getting external api stores from API publisher host object (getAPIUsageByUser)"); + Assert.assertNotNull(array[6], "Error while getting external api stores from API publisher host object (getAllAPIUsageByProvider)"); + Assert.assertNotNull(array[7], "Error while getting external api stores from API publisher host object (getFirstAccessTime)"); + Assert.assertNotNull(array[8], "Error while getting external api stores from API publisher host object (getProviderAPIServiceTime)"); + Assert.assertNotNull(array[9], "Error while getting external api stores from API publisher host object (getProviderAPIUsage)"); + Assert.assertNotNull(array[10], "Error while getting external api stores from API publisher host object (getProviderAPIVersionUsage)"); + Assert.assertNotNull(array[11], "Error while getting external api stores from API publisher host object (getProviderAPIVersionUserUsage)"); + Assert.assertNotNull(array[12], "Error while getting external api stores from API publisher host object (getProviderAPIVersionUserLastAccess)"); + return true; + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/DAOTestCase.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/DAOTestCase.java new file mode 100644 index 0000000000..0e31746dc3 --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/DAOTestCase.java @@ -0,0 +1,196 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.sample; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.am.tests.APIManagerIntegrationTest; +import org.wso2.carbon.am.tests.util.bean.APILifeCycleState; +import org.wso2.carbon.am.tests.util.APIMgtTestUtil; +import org.wso2.carbon.am.tests.util.APIPublisherRestClient; +import org.wso2.carbon.am.tests.util.APIStoreRestClient; +import org.wso2.carbon.am.tests.util.bean.*; +import org.wso2.carbon.automation.core.ProductConstant; +import org.wso2.carbon.automation.core.utils.ClientConnectionUtil; +import org.wso2.carbon.automation.core.utils.serverutils.ServerConfigurationManager; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; + +import org.wso2.carbon.utils.FileManipulator; +import org.wso2.carbon.utils.ServerConstants; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +public class DAOTestCase extends APIManagerIntegrationTest { + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private ServerConfigurationManager serverConfigurationManager; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(0); + apiPublisher = new APIPublisherRestClient(getServerURLHttp()); + apiStore = new APIStoreRestClient(getServerURLHttp()); + + + } + private void copySampleFile(String sourcePath, String destPath) { + File sourceFile = new File(sourcePath); + File destFile = new File(destPath); + try { + FileManipulator.copyFile(sourceFile, destFile); + } catch (IOException e) { + log.error("Error while copying the sample into Jaggery server", e); + } + } + + private String computeDestPath(String fileName) { + String serverRoot = System.getProperty(ServerConstants.CARBON_HOME); + String deploymentPath = serverRoot + "/repository/deployment/server/jaggeryapps/testapp"; + File depFile = new File(deploymentPath); + if (!depFile.exists() && !depFile.mkdir()) { + log.error("Error while creating the deployment folder : " + + deploymentPath); + } + return deploymentPath + File.separator + fileName; + } + + private String computeSourcePath(String fileName) { + + String sourcePath = ProductConstant.getResourceLocations(ProductConstant.AM_SERVER_NAME) + + File.separator + "jaggery/" + fileName; + return sourcePath; + } + + @Test(groups = {"wso2.am"}, description = "API Life cycle test case") + public void testDAOTestCase() throws Exception { + String APIName = "DAOTestAPI"; + String APIContext = "DAOTestAPI"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + apiPublisher.login(userInfo.getUserName(), userInfo.getPassword()); + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiPublisher.addAPI(apiRequest); + apiPublisher.deleteApi(APIName, APIVersion, providerName); + apiPublisher.addAPI(apiRequest); + APIBean apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisher.getApi(APIName, providerName)); + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + //Test API properties + Assert.assertEquals(apiBean.getId().getApiName(), APIName, "API Name mismatch"); + Assert.assertEquals(apiBean.getContext().trim().substring(apiBean.getContext().indexOf("/") + 1), APIContext, "API context mismatch"); + Assert.assertEquals(apiBean.getId().getVersion(), APIVersion, "API version mismatch"); + Assert.assertEquals(apiBean.getId().getProviderName(), providerName, "Provider Name mismatch"); + for (String tag : apiBean.getTags()) { + Assert.assertTrue(tags.contains(tag), "API tag data mismatched"); + } + Assert.assertEquals(apiBean.getDescription(), description, "API description mismatch"); + apiStore.login(userInfo.getUserName(), userInfo.getPassword()); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, userInfo.getUserName()); + apiStore.subscribe(subscriptionRequest); + + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest("DefaultApplication"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + Thread.sleep(2000); + + } + + @Test(groups = {"wso2.am"} ,description = "Test application object") + public void testApplication() { + String fileName = "testPublisher.jag"; + String sourcePath = computeSourcePath(fileName); + String destinationPath = computeDestPath( fileName); + copySampleFile(sourcePath, destinationPath); + ClientConnectionUtil.waitForPort(9763,""); + + String finalOutput = null; + + try { + URL jaggeryURL = new URL("http://localhost:9763/testapp/testPublisher.jag"); + URLConnection jaggeryServerConnection = jaggeryURL.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader( + jaggeryServerConnection.getInputStream())); + + String inputLine; + while ((inputLine = in.readLine()) != null) { + finalOutput = inputLine; + } + + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + // assertNotNull(finalOutput, "Result cannot be null"); + } + + } + + @Test(groups = {"wso2.am"} , description = "Test application operations") + public void testApplicationOperations() { + ClientConnectionUtil.waitForPort(9763,""); + + String finalOutput = null; + + try { + URL jaggeryURL = new URL("http://localhost:9763/testapp/testPublisher.jag"); + URLConnection jaggeryServerConnection = jaggeryURL.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader( + jaggeryServerConnection.getInputStream())); + + String inputLine; + while ((inputLine = in.readLine()) != null) { + finalOutput = inputLine; + } + + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + // assertEquals(finalOutput, "test jaggery application value"); + } + + } + + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + super.cleanup(); + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/HostObjectTestCase.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/HostObjectTestCase.java new file mode 100644 index 0000000000..898bbcea5d --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/HostObjectTestCase.java @@ -0,0 +1,327 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.sample; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.automation.tools.jmeter.JMeterTest; +import org.wso2.automation.tools.jmeter.JMeterTestManager; +import org.wso2.carbon.am.tests.APIManagerIntegrationTest; +import org.wso2.carbon.am.tests.util.bean.APILifeCycleState; +import org.wso2.carbon.am.tests.util.APIMgtTestUtil; +import org.wso2.carbon.am.tests.util.APIPublisherRestClient; +import org.wso2.carbon.am.tests.util.APIStoreRestClient; +import org.wso2.carbon.am.tests.util.bean.*; +import org.wso2.carbon.automation.core.ProductConstant; +import org.wso2.carbon.automation.core.utils.serverutils.ServerConfigurationManager; +import org.wso2.carbon.utils.FileManipulator; +import org.wso2.carbon.utils.ServerConstants; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.util.HashMap; +import java.util.Map; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +public class HostObjectTestCase extends APIManagerIntegrationTest { + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private ServerConfigurationManager serverConfigurationManager; + private String publisherURLHttp; + private String storeURLHttp; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(0); + if (isBuilderEnabled()) { + /* + If test run in external distributed deployment you need to copy following resources accordingly. + configFiles/hostobjecttest/api-manager.xml + configFiles/tokenTest/log4j.properties + Also need to copy the content of /resources/artifacts/AM/jaggery to servers following folder folder + repository/deployment/server/jaggeryapps/testapp + */ + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + serverConfigurationManager = new ServerConfigurationManager(amServer.getBackEndUrl()); + serverConfigurationManager.applyConfiguration(new File(ProductConstant.getResourceLocations(ProductConstant.AM_SERVER_NAME) + + File.separator + "configFiles/hostobjecttest/" + "api-manager.xml")); + serverConfigurationManager.applyConfiguration(new File(ProductConstant.getResourceLocations(ProductConstant.AM_SERVER_NAME) + + File.separator + "configFiles/tokenTest/" + "log4j.properties")); + super.init(0); + } else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + apiPublisher = new APIPublisherRestClient(publisherURLHttp); + apiStore = new APIStoreRestClient(storeURLHttp); + } + + private void copySampleFile(String sourcePath, String destPath) { + File sourceFile = new File(sourcePath); + File destFile = new File(destPath); + try { + FileManipulator.copyFile(sourceFile, destFile); + } catch (IOException e) { + log.error("Error while copying the sample into Jaggery server", e); + } + } + + private String computeDestPath(String fileName) { + String serverRoot = System.getProperty(ServerConstants.CARBON_HOME); + String deploymentPath = serverRoot + "/repository/deployment/server/jaggeryapps/testapp"; + File depFile = new File(deploymentPath); + if (!depFile.exists() && !depFile.mkdir()) { + log.error("Error while creating the deployment folder : " + + deploymentPath); + } + return deploymentPath + File.separator + fileName; + } + + private String computeSourcePath(String fileName) { + + String sourcePath = ProductConstant.getResourceLocations(ProductConstant.AM_SERVER_NAME) + + File.separator + "jaggery/" + fileName; + return sourcePath; + } + + @Test(groups = {"wso2.am"}, description = "API Life cycle test case") + public void testHostObjectTestCase() throws Exception { + //Tenant Create test cases - This will create new tenant in the system + JMeterTest script = + new JMeterTest(new File(ProductConstant.SYSTEM_TEST_RESOURCE_LOCATION + File.separator + "artifacts" + + File.separator + "AM" + File.separator + "scripts" + + File.separator + "tenant_create.jmx")); + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(script); + //End of tenant creation + + + String APIName = "HostObjectTestAPI"; + String APIContext = "HostObjectTestAPI"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + apiPublisher.login(userInfo.getUserName(), userInfo.getPassword()); + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiPublisher.addAPI(apiRequest); + apiPublisher.deleteApi(APIName, APIVersion, providerName); + apiPublisher.addAPI(apiRequest); + APIBean apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisher.getApi(APIName, providerName)); + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + //Test API properties + Assert.assertEquals(apiBean.getId().getApiName(), APIName, "API Name mismatch"); + Assert.assertEquals(apiBean.getContext().trim().substring(apiBean.getContext().indexOf("/") + 1), APIContext, "API context mismatch"); + Assert.assertEquals(apiBean.getId().getVersion(), APIVersion, "API version mismatch"); + Assert.assertEquals(apiBean.getId().getProviderName(), providerName, "Provider Name mismatch"); + for (String tag : apiBean.getTags()) { + Assert.assertTrue(tags.contains(tag), "API tag data mismatched"); + } + Assert.assertEquals(apiBean.getDescription(), description, "API description mismatch"); + apiStore.login(userInfo.getUserName(), userInfo.getPassword()); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, userInfo.getUserName()); + apiStore.subscribe(subscriptionRequest); + apiPublisher.addDocument(APIName, APIVersion, providerName, "Doc-Name", "How To", "In-line", "url-no-need", "summary", ""); + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest("DefaultApplication"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + + //host object tests + String fileName = "testPublisher.jag"; + String sourcePath = computeSourcePath(fileName); + String destinationPath = computeDestPath(fileName); + copySampleFile(sourcePath, destinationPath); + + + fileName = "testStore.jag"; + sourcePath = computeSourcePath(fileName); + destinationPath = computeDestPath(fileName); + copySampleFile(sourcePath, destinationPath); + + + Thread.sleep(20000); + String finalOutputPublisher = null; + //ClientConnectionUtil.waitForPort(9763, ""); + try { + URL jaggeryURL = new URL(getTestApplicationPublisherServerURLHttp()); + URLConnection jaggeryServerConnection = jaggeryURL.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader( + jaggeryServerConnection.getInputStream())); + + String inputLine; + while ((inputLine = in.readLine()) != null) { + finalOutputPublisher = inputLine; + } + String[] arr = finalOutputPublisher.split("=="); + System.out.println(finalOutputPublisher); + validatePublisherResponseArray(arr); + in.close(); + } catch (IOException e) { + log.error("Error while invoking test application to test publisher host object"); + } finally { + assertNotNull(finalOutputPublisher, "Result cannot be null"); + } + + String finalOutputStore = null; + Thread.sleep(2000); + //ClientConnectionUtil.waitForPort(9763, ""); + try { + URL jaggeryURL = new URL(getTestApplicationStoreServerURLHttp()); + URLConnection jaggeryServerConnection = jaggeryURL.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader( + jaggeryServerConnection.getInputStream())); + + String inputLine; + while ((inputLine = in.readLine()) != null) { + finalOutputStore = inputLine; + } + String[] arr = finalOutputStore.split("=="); + validateStoreResponseArray(arr); + System.out.println(finalOutputStore); + in.close(); + } catch (IOException e) { + log.error("Error while invoking test application to test publisher host object"); + } finally { + assertNotNull(finalOutputStore, "Result cannot be null"); + } + } + + @Test(groups = {"wso2.am"}, description = "Test application object") + public void testApplication() { + } + + @Test(groups = {"wso2.am"}, description = "Test application operations") + public void testApplicationOperations() { + } + + + @Test(groups = {"wso2.am"}, description = "Test application operations") + public void testAPIProvider() { + } + + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + super.cleanup(); + } + + public static boolean validateStoreResponseArray(String[] array) { + //This order is based on the operations of jaggery file operation order + //If we edit jaggery file we need to modify this as well + Assert.assertTrue(array[1].contains("true"), "Error while getting status of billing system from API store host object (isBillingEnabled)"); + Assert.assertTrue(array[2].contains("https"), "Error while getting https url from API store host object (getHTTPsURL)"); + Assert.assertTrue(array[4].contains("http"), "Error while getting http url from API store host object (getHTTPURL)"); + Assert.assertTrue(array[3].contains("services"), "Error while getting auth service url from API store host object (getAuthServerURL)"); + Assert.assertTrue(array[5].contains("[{\"tierName\" : \"Gold\"}]"), "Error while getting denied tiers from API store host object (getDeniedTiers)"); + Assert.assertTrue(array[6].contains("tenantdomain1.com"), "Error while getting active tenant domains from API store host object (getActiveTenantDomains)"); + Assert.assertTrue(array[7].contains("true"), "Error while getting status of self sign in from API store host object (isSelfSignupEnabled)"); + Assert.assertTrue(array[8].contains("fieldName"), "Error while getting user fields from API store host object (getUserFields)"); + Assert.assertTrue(array[9].contains("HostObjectTestAPI"), "Error while search Paginated APIs By Type from API store host object (searchPaginatedAPIsByType)"); + Assert.assertTrue(array[10].contains("HostObjectTestAPI"), "Error while search Paginated APIs By Type with pattern * from API store host object (searchPaginatedAPIsByType)"); + Assert.assertTrue(array[11].contains("HostObjectTestAPI"), "Error while search API by Type with pattern * from API store host object (searchAPIbyType)"); + Assert.assertTrue(array[12].contains("HostObjectTestAPI"), "Error while search API by type from API store host object (searchAPIbyType)"); + Assert.assertTrue(array[13].contains("HostObjectTestAPI"), "Error while getting paginated APIs with tag from API store host object (getPaginatedAPIsWithTag)"); + //14 getPublishedAPIsByProvider + //15 getAllSubscriptions + Assert.assertTrue(array[16].contains("HostObjectTestAPI"), "Error while rating API from API store host object (rateAPI)"); + Assert.assertTrue(array[17].contains("[{\"newRating\" : \"0.0\"}]"), "Error while removing rating from API store host object (removeAPIRating)"); + Assert.assertTrue(array[18].contains("apis"), "Error while getting Paginated , published APIs from API store host object (getAllPaginatedPublishedAPIs)"); + Assert.assertTrue(array[19].contains("HostObjectTestAPI"), "Error while getting APIs With Tag from API store host object (getAPIsWithTag)"); + Assert.assertTrue(array[20].contains("HostObjectTestAPI"), "Error while getting all published APIs from API store host object (getAllPublishedAPIs)"); + //21 getComments + Assert.assertTrue(array[22].contains("true"), "Error while checking user in the system from API store host object (isUserExists)"); + Assert.assertTrue(array[23].contains("HostObjectTestAPI"), "Error while getting API from API store host object (getAPI)"); + Assert.assertTrue(array[24].contains("true"), "Error while checking subscription state from API store host object (isSubscribed)"); + Assert.assertTrue(array[25].contains("application"), "Error while getting subscriptions from API store host object (getSubscriptions)"); + //26 getSubscribedAPIs + Assert.assertTrue(array[27].contains("true"), "Error while checking user permission from API store host object (hasUserPermissions)"); + //28 getTiers + //29 getAPIUsageforSubscriber + //30 getDeniedTiers + //31 getRecentlyAddedAPIs + //32 getTopRatedAPIs + Assert.assertTrue(array[33].contains("true"), "Error while getting billing status from API store host object (isBillingEnabled)"); + Assert.assertTrue(array[34].contains("true"), "Error while checking Subscribe Permission from API store host object (hasSubscribePermission)"); + Assert.assertTrue(array[35].contains("false"), "Error while getting state of Email Username from API store host object (isEnableEmailUsername)"); + Assert.assertTrue(array[36].contains("true"), "Error while update Application Tier from API store host object (updateApplicationTier)"); + Assert.assertTrue(array[37].contains("true"), "Error while update Application from API store host object (updateApplication)"); + Assert.assertTrue(array[38].contains("200"), "Error while validate WF Permission from API store host object (validateWFPermission)"); + Assert.assertTrue(array[39].contains("/apimgt/applicationdata/api-docs/HostObjectTestAPI-1.0.0/api-doc.json"), "Error while getting Swagger Discovery Url from API store host object (getSwaggerDiscoveryUrl)"); + return true; + } + + + public static boolean validatePublisherResponseArray(String[] array) { + //This order is based on the operations of jaggery file operation order + //If we edit jaggary file we need to modify this as well + Assert.assertNotNull(array[1], "Error while getting external api stores from API store host object (getExternalAPIStores)"); + Assert.assertTrue(array[2].contains("true"), "Error while validating roles from API store host object (validateRoles)"); + Assert.assertTrue(array[3].contains("success"), "Error while checking url validity from API store host object (isURLValid)"); + Assert.assertTrue(array[4].contains("HostObjectTestAPI"), "Error while getting APIs by provider from API store host object (getAPIsByProvider)"); + Assert.assertTrue(array[5].contains("HostObjectTestAPI"), "Error while getting subscribed APIs from API store host object (getSubscribedAPIs)"); + Assert.assertTrue(array[6].contains("HostObjectTestAPI"), "Error while getting API from API store host object (getAPI)"); + Assert.assertTrue(array[7].contains("Bronze"), "Error while getting tier permission from API store host object (getTierPermissions)"); + Assert.assertTrue(array[8].contains("Bronze"), "Error while getting tiers from API store host object (getTiers)"); + Assert.assertTrue(array[9].contains("HostObjectTestAPI"), "Error while getting all APIs By Type from API store host object (getAllAPIs)"); + Assert.assertTrue(array[10].contains("HostObjectTestAPI"), "Error while getting APIs By provider with pattern * from API store host object (getAPIsByProvider)"); + Assert.assertTrue(array[11].contains("subscribedDate"), "Error while getting subscribers of API from API store host object (getSubscribersOfAPI)"); + Assert.assertTrue(array[12].contains("false"), "Error while checking contexts from API store host object (isContextExist)"); + Assert.assertTrue(array[13].contains("HostObjectTestAPI"), "Error while searching APIs from API store host object (searchAPIs)"); + Assert.assertTrue(array[14].contains("true"), "Error while checking create permission from API store host object (hasCreatePermission)"); + Assert.assertTrue(array[15].contains("true"), "Error while checking manage tier permission from API store host object (hasManageTierPermission)"); + Assert.assertTrue(array[16].contains("true"), "Error while checking user permission from API store host object (hasUserPermissions)"); + Assert.assertTrue(array[17].contains("true"), "Error while checking publisher permissions (hasPublishPermission)"); + Assert.assertTrue(array[18].contains("services"), "Error while getting auth server url from API store host object (getAuthServerURL)"); + Assert.assertTrue(array[19].contains("[\"log_in_message\"]"), "Error while getting in sequences from API store host object (getCustomInSequences)"); + Assert.assertTrue(array[20].contains("[\"log_out_message\"]"), "Error while getting out sequences from API store host object (getCustomOutSequences)"); + Assert.assertTrue(array[21].contains("https"), "Error while getting https url from API store host object (getHTTPsURL)"); + Assert.assertTrue(array[22].contains("true"), "Error while checking gateway type from API store host object (isSynapseGateway)"); + Assert.assertTrue(array[23].contains("null"), "Error while load Registry Of Tenant API store host object (loadRegistryOfTenant)"); + Assert.assertTrue(array[24].contains("true"), "Error while update Documentation from API store host object (updateDocumentation)"); + Assert.assertTrue(array[25].contains("null"), "Error while adding Inline Content from API store host object (addInlineContent)"); + Assert.assertTrue(array[26].contains("providerName"), "Error while getting Inline Content from API store host object (getInlineContent)"); + Assert.assertTrue(array[27].contains("docName"), "Error while getting All Documentation from API store host object (getAllDocumentation)"); + Assert.assertTrue(array[28].contains("token"), "Error while search Access Tokens from API store host object (searchAccessTokens)"); + //Assert.assertTrue(array[29].contains("true"), "Error while checking user permission from API store host object (getSubscriberCountByAPIs)"); + //Assert.assertTrue(array[30].contains("true"), "Error while checking user permission from API store host object (getSubscriberCountByAPIVersions)"); + //Assert.assertTrue(array[31].contains("null"), "Error while getting External API Stores from API store host object (getExternalAPIStores)"); + Assert.assertTrue(array[32].contains("false"), "Error while checking API Older Versions from API store host object (isAPIOlderVersionExist)"); + Assert.assertTrue(array[33].contains("true"), "Error while update Subscription Status from API store host object (updateSubscriptionStatus)"); + Assert.assertTrue(array[34].contains("true"), "Error while update Tier Permissions from API store host object (updateTierPermissions)"); + return true; + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/RefreshTokenTestCase.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/RefreshTokenTestCase.java new file mode 100644 index 0000000000..0f7c988a80 --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/RefreshTokenTestCase.java @@ -0,0 +1,157 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF 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.carbon.am.tests.sample; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.am.tests.APIManagerIntegrationTest; +import org.wso2.carbon.am.tests.util.APIPublisherRestClient; +import org.wso2.carbon.am.tests.util.APIStoreRestClient; +import org.wso2.carbon.am.tests.util.bean.*; +import org.wso2.carbon.automation.core.ProductConstant; +import org.wso2.carbon.automation.core.utils.HttpRequestUtil; +import org.wso2.carbon.automation.core.utils.HttpResponse; +import org.wso2.carbon.automation.core.utils.serverutils.ServerConfigurationManager; + +import java.io.File; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class RefreshTokenTestCase extends APIManagerIntegrationTest { + + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private ServerConfigurationManager serverConfigurationManager; + private String publisherURLHttp; + private String storeURLHttp; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + + super.init(0); + /* + If test run in external distributed deployment you need to copy following resources accordingly. + configFiles/hostobjecttest/api-manager.xml + configFiles/tokenTest/log4j.properties + */ + if (isBuilderEnabled()) { + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + serverConfigurationManager = new ServerConfigurationManager(amServer.getBackEndUrl()); + serverConfigurationManager.applyConfiguration(new File(ProductConstant.getResourceLocations(ProductConstant.AM_SERVER_NAME) + + File.separator + "configFiles/tokenTest/" + "api-manager.xml")); + serverConfigurationManager.applyConfiguration(new File(ProductConstant.getResourceLocations(ProductConstant.AM_SERVER_NAME) + + File.separator + "configFiles/tokenTest/" + "log4j.properties")); + super.init(0); + } else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + apiPublisher = new APIPublisherRestClient(publisherURLHttp); + apiStore = new APIStoreRestClient(storeURLHttp); + + } + + @Test(groups = {"wso2.am"}, description = "Token API Test sample") + public void testTokenAPITestCase() throws Exception { + String APIName = "TokenTestAPI"; + String APIContext = "tokenTestAPI"; + String tags = "youtube, token, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + apiPublisher.login(userInfo.getUserName(), userInfo.getPassword()); + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiRequest.setSandbox(url); + apiPublisher.addAPI(apiRequest); + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + + apiStore.login(userInfo.getUserName(), userInfo.getPassword()); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, userInfo.getUserName()); + subscriptionRequest.setTier("Gold"); + apiStore.subscribe(subscriptionRequest); + + //Generate production token and invoke with that + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest("DefaultApplication"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + + // get Consumer Key and Consumer Secret + String consumerKey = response.getJSONObject("data").getJSONObject("key").getString("consumerKey"); + String consumerSecret = response.getJSONObject("data").getJSONObject("key").getString("consumerSecret"); + + //Obtain user access token + Thread.sleep(2000); + String requestBody = "grant_type=password&username=admin&password=admin&scope=PRODUCTION"; + URL tokenEndpointURL = new URL("https://localhost:8243/token"); + JSONObject accessTokenGenerationResponse = new JSONObject(apiStore.generateUserAccessKey(consumerKey, consumerSecret, requestBody, tokenEndpointURL).getData()); + /* + Response would be like - + {"token_type":"bearer","expires_in":3600,"refresh_token":"736b6b5354e4cf24f217718b2f3f72b", + "access_token":"e06f12e3d6b1367d8471b093162f6729"} + */ + + // get Access Token and Refresh Token + String userAccessToken = accessTokenGenerationResponse.getString("access_token"); + String refreshToken = accessTokenGenerationResponse.getString("refresh_token"); + + Map requestHeaders = new HashMap(); + //Check Access Token + requestHeaders.put("Authorization", "Bearer " + userAccessToken); + Thread.sleep(2000); + HttpResponse youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("tokenTestAPI/1.0.0/most_popular"), requestHeaders); + //check JWT headers here + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched"); + Assert.assertTrue(youTubeResponse.getData().contains(""), "Response data mismatched"); + + // get a new access token using refresh token + String getAccessTokenFromRefreshTokenRequestBody = "grant_type=refresh_token&refresh_token=" + refreshToken + "&scope=PRODUCTION"; + accessTokenGenerationResponse = new JSONObject(apiStore.generateUserAccessKey(consumerKey, consumerSecret, getAccessTokenFromRefreshTokenRequestBody, tokenEndpointURL).getData()); + userAccessToken = accessTokenGenerationResponse.getString("access_token"); + + requestHeaders = new HashMap(); + //Check with new Access Token + requestHeaders.put("Authorization", "Bearer " + userAccessToken); + Thread.sleep(2000); + youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("tokenTestAPI/1.0.0/most_popular"), requestHeaders); + //check JWT headers here + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched"); + Assert.assertTrue(youTubeResponse.getData().contains(""), "Response data mismatched"); + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + super.cleanup(); + serverConfigurationManager.restoreToLastConfiguration(); + } +} \ No newline at end of file diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/TagsRatingCommentTestCase.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/TagsRatingCommentTestCase.java new file mode 100644 index 0000000000..8ccb1320ad --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/TagsRatingCommentTestCase.java @@ -0,0 +1,148 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.sample; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.am.tests.APIManagerIntegrationTest; +import org.wso2.carbon.am.tests.util.bean.APILifeCycleState; +import org.wso2.carbon.am.tests.util.APIMgtTestUtil; +import org.wso2.carbon.am.tests.util.APIPublisherRestClient; +import org.wso2.carbon.am.tests.util.APIStoreRestClient; +import org.wso2.carbon.am.tests.util.bean.*; +import org.wso2.carbon.automation.core.utils.HttpRequestUtil; +import org.wso2.carbon.automation.core.utils.HttpResponse; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class TagsRatingCommentTestCase extends APIManagerIntegrationTest { + + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private String publisherURLHttp; + private String storeURLHttp; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(0); + /* + This test can point to external API manager deployment without adding any resources to system + */ + if (isBuilderEnabled()) { + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + } else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + apiPublisher = new APIPublisherRestClient(publisherURLHttp); + apiStore = new APIStoreRestClient(storeURLHttp); + } + + @Test(groups = {"wso2.am"}, description = "Comment Rating Test case") + public void testTagsRatingCommentTestCase() throws Exception { + String APIName = "CommentRatingAPI"; + String APIContext = "commentRating"; + String tags = "youtube, video, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + apiPublisher.login(userInfo.getUserName(), userInfo.getPassword()); + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiPublisher.addAPI(apiRequest); + APIBean apiBean = APIMgtTestUtil.getAPIBeanFromHttpResponse(apiPublisher.getApi(APIName, providerName)); + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + //Test API properties + Assert.assertEquals(apiBean.getId().getApiName(), APIName, "API Name mismatch"); + Assert.assertEquals(apiBean.getContext().trim().substring(apiBean.getContext().indexOf("/") + 1), APIContext, "API context mismatch"); + Assert.assertEquals(apiBean.getId().getVersion(), APIVersion, "API version mismatch"); + Assert.assertEquals(apiBean.getId().getProviderName(), providerName, "Provider Name mismatch"); + for (String tag : apiBean.getTags()) { + Assert.assertTrue(tags.contains(tag), "API tag data mismatched"); + } + Assert.assertEquals(apiBean.getDescription(), description, "API description mismatch"); + apiStore.login(userInfo.getUserName(), userInfo.getPassword()); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, userInfo.getUserName()); + apiStore.subscribe(subscriptionRequest); + + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest("DefaultApplication"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + //Here add API tags and check same have in response. + //Here check same tags are there + //Add some comment to API + //check comment is there + //Add rating + //check rating + Thread.sleep(2000); + for (int i = 0; i < 19; i++) { + + HttpResponse youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("commentRating/1.0.0/most_popular"), requestHeaders); + System.out.println("==================================================================================" + i + "==========" + youTubeResponse.getResponseCode()); + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched"); + Assert.assertTrue(youTubeResponse.getData().contains(""), "Response data mismatched"); + + } + //Do get,post,put,delete all here + //HttpResponse youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("commentRating/1.0.0/most_popular"), requestHeaders); + //Assert.assertEquals(youTubeResponse.getResponseCode(), 503, "Response code mismatched"); + Thread.sleep(60000); + HttpResponse youTubeResponse1 = HttpRequestUtil.doGet(getApiInvocationURLHttp("commentRating/1.0.0/most_popular"), null); + Assert.assertEquals(youTubeResponse1.getResponseCode(), 401, "Response code mismatched"); + // URL url1 = new URL(url); + // HttpResponse youTubeResponse2 = HttpRequestUtil.doPost(url1,"-"); + //Remove subscription and then remove API + + apiStore.getAllPublishedAPIs(); + apiStore.getAllApplications(); + apiStore.getPublishedAPIsByApplication("DefaultApplication"); + apiStore.isRatingActivated(); + apiStore.addRatingToAPI(APIName, APIVersion, providerName, "4"); + apiStore.removeRatingFromAPI(APIName, APIVersion, providerName); + apiStore.getAllDocumentationOfApi(APIName, APIVersion, providerName); + //apiStore.getAllPaginatedPublishedAPIs("carbon.super","0","10"); + //Negative cases + //add assert + apiStore.getPublishedAPIsByApplication("DefaultApplicationWrong"); + apiStore.isRatingActivated(); + apiStore.addRatingToAPI("NoAPI", APIVersion, providerName, "4"); + apiStore.removeRatingFromAPI("NoAPI", APIVersion, providerName); + apiStore.getAllDocumentationOfApi("NoAPI", APIVersion, providerName); + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + super.cleanup(); + } + +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/ThrottlingTestCase.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/ThrottlingTestCase.java new file mode 100644 index 0000000000..195203c657 --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/ThrottlingTestCase.java @@ -0,0 +1,93 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.sample; + +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.am.tests.APIManagerIntegrationTest; +import org.wso2.carbon.am.tests.util.APIPublisherRestClient; +import org.wso2.carbon.am.tests.util.APIStoreRestClient; +import org.wso2.carbon.automation.api.clients.registry.ResourceAdminServiceClient; +import org.wso2.carbon.automation.core.ProductConstant; +import org.wso2.carbon.automation.core.utils.HttpRequestUtil; +import org.wso2.carbon.automation.core.utils.HttpResponse; +import org.wso2.carbon.automation.core.utils.serverutils.ServerConfigurationManager; + +import javax.activation.DataHandler; +import java.io.File; +import java.net.URL; + + +public class ThrottlingTestCase extends APIManagerIntegrationTest { + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private ServerConfigurationManager serverConfigurationManager; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + /* + Before run this test we need to add throttling tiers xml file to registry and also we need to deploy API + to gateway Server. + Deploy API available in AM/synapseconfigs/throttling/throttling-api-synapse.xml + Add throttling definition available in configFiles/throttling/throttle-policy.xml to /_system/governance/apimgt/applicationdata/test-tiers.xml + */ + super.init(0); + serverConfigurationManager = new ServerConfigurationManager(amServer.getBackEndUrl()); + super.init(0); + loadESBConfigurationFromClasspath("artifacts" + File.separator + "AM" + + File.separator + "synapseconfigs" + File.separator + "throttling" + + File.separator + "throttling-api-synapse.xml"); + //apiPublisher = new APIPublisherRestClient(getServerURLHttp()); + //apiStore = new APIStoreRestClient(getServerURLHttp()); + + } + + @Test(groups = {"wso2.am"}, description = "Token API Test sample") + public void throttlingTestCase() throws Exception { + //APIProviderHostObject test=new APIProviderHostObject("admin"); + //add client IP to tiers xml + ResourceAdminServiceClient resourceAdminServiceStub = + new ResourceAdminServiceClient(amServer.getBackEndUrl(), amServer.getSessionCookie()); + + //resourceAdminServiceStub.deleteResource("/_system/config/proxy"); + resourceAdminServiceStub.addCollection("/_system/config/", "proxy", "", + "Contains test proxy tests files"); + + Assert.assertTrue(resourceAdminServiceStub.addResource("/_system/governance/apimgt/applicationdata/test-tiers.xml", "application/xml", "xml files", + setEndpoints(new DataHandler(new URL("file:///" + ProductConstant.getResourceLocations(ProductConstant.AM_SERVER_NAME) + + File.separator + "configFiles/throttling/" + "throttle-policy.xml")))) + , "Adding Resource failed"); + Thread.sleep(2000); + HttpResponse response = HttpRequestUtil.sendGetRequest(getApiInvocationURLHttp("stockquote") + "/test/", null); + Assert.assertEquals(response.getResponseCode(), 200, "Response code mismatch"); + + + HttpResponse errorResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("stockquote") + "/test/", null); + Assert.assertEquals(errorResponse.getResponseCode(), 503, "Response code mismatch"); + //assert response + + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + super.cleanup(); + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/TokenAPITestCase.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/TokenAPITestCase.java new file mode 100644 index 0000000000..294121c544 --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/TokenAPITestCase.java @@ -0,0 +1,198 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.sample; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.am.tests.APIManagerIntegrationTest; +import org.wso2.carbon.am.tests.util.bean.APILifeCycleState; +import org.wso2.carbon.am.tests.util.APIPublisherRestClient; +import org.wso2.carbon.am.tests.util.APIStoreRestClient; +import org.wso2.carbon.am.tests.util.bean.APILifeCycleStateRequest; +import org.wso2.carbon.am.tests.util.bean.APIRequest; +import org.wso2.carbon.am.tests.util.bean.SubscriptionRequest; +import org.wso2.carbon.am.tests.util.bean.GenerateAppKeyRequest; +import org.wso2.carbon.automation.core.ProductConstant; +import org.wso2.carbon.automation.core.utils.HttpRequestUtil; +import org.wso2.carbon.automation.core.utils.HttpResponse; +import org.wso2.carbon.automation.core.utils.serverutils.ServerConfigurationManager; + +import java.io.File; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class TokenAPITestCase extends APIManagerIntegrationTest { + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private ServerConfigurationManager serverConfigurationManager; + private String publisherURLHttp; + private String storeURLHttp; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + + super.init(0); + /* + If test run in external distributed deployment you need to copy following resources accordingly. + configFiles/hostobjecttest/api-manager.xml + configFiles/tokenTest/log4j.properties + To tests issue mentioned in https://wso2.org/jira/browse/APIMANAGER-2065 please run this test against + WSo2 Load balancer fronted 2 gateways 2 key manager setup with WSClient mode. Please refer resource api-manager.xml file. + */ + if (isBuilderEnabled()) { + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + serverConfigurationManager = new ServerConfigurationManager(amServer.getBackEndUrl()); + serverConfigurationManager.applyConfiguration(new File(ProductConstant.getResourceLocations(ProductConstant.AM_SERVER_NAME) + + File.separator + "configFiles/tokenTest/" + "api-manager.xml")); + serverConfigurationManager.applyConfiguration(new File(ProductConstant.getResourceLocations(ProductConstant.AM_SERVER_NAME) + + File.separator + "configFiles/tokenTest/" + "log4j.properties")); + super.init(0); + } else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + apiPublisher = new APIPublisherRestClient(publisherURLHttp); + apiStore = new APIStoreRestClient(storeURLHttp); + + } + + @Test(groups = {"wso2.am"}, description = "Token API Test sample") + public void testTokenAPITestCase() throws Exception { + String APIName = "TokenTestAPI"; + String APIContext = "tokenTestAPI"; + String tags = "youtube, token, media"; + String url = "http://gdata.youtube.com/feeds/api/standardfeeds"; + String description = "This is test API create by API manager integration test"; + String providerName = "admin"; + String APIVersion = "1.0.0"; + apiPublisher.login(userInfo.getUserName(), userInfo.getPassword()); + APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); + apiRequest.setTags(tags); + apiRequest.setDescription(description); + apiRequest.setVersion(APIVersion); + apiRequest.setSandbox(url); + apiPublisher.addAPI(apiRequest); + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + + apiStore.login(userInfo.getUserName(), userInfo.getPassword()); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, userInfo.getUserName()); + subscriptionRequest.setTier("Gold"); + apiStore.subscribe(subscriptionRequest); + + //Generate sandbox Token and invoke with that + GenerateAppKeyRequest generateAppKeyRequestSandBox = new GenerateAppKeyRequest("DefaultApplication"); + generateAppKeyRequestSandBox.setKeyType("SANDBOX"); + String responseStringSandBox = apiStore.generateApplicationKey(generateAppKeyRequestSandBox).getData(); + JSONObject responseSandBOX = new JSONObject(responseStringSandBox); + String SANDbOXAccessToken = responseSandBOX.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeadersSandBox = new HashMap(); + requestHeadersSandBox.put("Authorization", "Bearer " + SANDbOXAccessToken); + HttpResponse youTubeResponseSandBox = HttpRequestUtil.doGet(getApiInvocationURLHttp("tokenTestAPI/1.0.0/most_popular"), requestHeadersSandBox); + // Assert.assertEquals(youTubeResponseSandBox.getResponseCode(), 200, "Response code mismatched"); + + //Generate production token and invoke with that + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest("DefaultApplication"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + /*Response would be like - + {"validityTime":"360000","consumerKey":"Ow2cGYBf3xlAPpG3Q51W_3qnoega", + "accessToken":"qo3oNebQaF16C6qw1a56aZn2nwEa","enableRegenarate":true,"accessallowdomains":"ALL"," + consumerSecret":"ctHfsc1jFR7ovUgZ0oeHK8i9F9oa"}*/ + + String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + String consumerKey = response.getJSONObject("data").getJSONObject("key").getString("consumerKey"); + String consumerSecret = response.getJSONObject("data").getJSONObject("key").getString("consumerSecret"); + //Obtain user access token + Thread.sleep(2000); + String requestBody = "grant_type=password&username=admin&password=admin&scope=PRODUCTION"; + URL tokenEndpointURL = new URL("https://localhost:8243/token"); + JSONObject accessTokenGenerationResponse = new JSONObject(apiStore.generateUserAccessKey(consumerKey, consumerSecret, requestBody, tokenEndpointURL).getData()); + /*Response would be like - + {"token_type":"bearer","expires_in":3600,"refresh_token":"736b6b5354e4cf24f217718b2f3f72b", + "access_token":"e06f12e3d6b1367d8471b093162f6729"} + */ + String userAccessToken = accessTokenGenerationResponse.getString("access_token"); + String refreshToken = accessTokenGenerationResponse.getString("refresh_token"); + Map requestHeaders = new HashMap(); + //Check User Access Token + requestHeaders.put("Authorization", "Bearer " + userAccessToken); + Thread.sleep(2000); + HttpResponse youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("tokenTestAPI/1.0.0/most_popular"), requestHeaders); + //check JWT headers here + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched"); + Assert.assertTrue(youTubeResponse.getData().contains(""), "Response data mismatched"); + + //Check Application Access Token + requestHeaders.clear(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + HttpResponse youTubeResponseWithApplicationToken = HttpRequestUtil.doGet(getApiInvocationURLHttp("tokenTestAPI/1.0.0/most_popular"), requestHeaders); + Assert.assertEquals(youTubeResponseWithApplicationToken.getResponseCode(), 200, "Response code mismatched"); + Assert.assertTrue(youTubeResponseWithApplicationToken.getData().contains(""), "Response data mismatched"); + + //Invoke Https end point + HttpResponse youTubeResponseWithApplicationTokenHttps = HttpRequestUtil.doGet(getApiInvocationURLHttps("tokenTestAPI/1.0.0/most_popular"), requestHeaders); + // Assert.assertEquals(youTubeResponseWithApplicationTokenHttps.getResponseCode(), 200, "Response code mismatched"); + + + HttpResponse errorResponse = null; + for (int i = 0; i < 40; i++) { + errorResponse = HttpRequestUtil.doGet(getApiInvocationURLHttps("tokenTestAPI/1.0.0/most_popular"), requestHeaders); + errorResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("tokenTestAPI/1.0.0/most_popular"), requestHeaders); + } + Assert.assertEquals(errorResponse.getResponseCode(), 503, "Response code mismatched while token API test case"); + Thread.sleep(60000); + errorResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("tokenTestAPI/1.0.0/most_popular"), requestHeaders); + + apiPublisher.revokeAccessToken(accessToken, consumerKey, providerName); + requestHeaders.clear(); + requestHeaders.put("Authorization", "Bearer " + "this-is-incorrect-token"); + errorResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("tokenTestAPI/1.0.0/most_popular"), requestHeaders); + Assert.assertEquals(errorResponse.getResponseCode(), 401, "Response code mismatched while token API test case"); + //TODO handle this in automation core level + try{ + StringBuilder soapRequest = new StringBuilder(""); + soapRequest.append("Sam"); + soapRequest.append(""); + errorResponse = HttpRequestUtil.doPost(new URL(getApiInvocationURLHttp("tokenTestAPI/1.0.0/most_popular")), soapRequest.toString(), requestHeaders); + } + catch (Exception e){ + //handle error + } + //Assert.assertEquals(errorResponse.getResponseCode(), 401, "Response code mismatched while token API test case"); + + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + super.cleanup(); + serverConfigurationManager.restoreToLastConfiguration(); + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/YouTubeAPITestCase.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/YouTubeAPITestCase.java new file mode 100644 index 0000000000..1bb35aee5b --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/sample/YouTubeAPITestCase.java @@ -0,0 +1,95 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.sample; + +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.am.tests.APIManagerIntegrationTest; +import org.wso2.carbon.am.tests.util.bean.APILifeCycleState; +import org.wso2.carbon.am.tests.util.APIPublisherRestClient; +import org.wso2.carbon.am.tests.util.APIStoreRestClient; +import org.wso2.carbon.am.tests.util.bean.APILifeCycleStateRequest; +import org.wso2.carbon.am.tests.util.bean.APIRequest; +import org.wso2.carbon.am.tests.util.bean.SubscriptionRequest; +import org.wso2.carbon.am.tests.util.bean.GenerateAppKeyRequest; +import org.wso2.carbon.automation.core.utils.HttpRequestUtil; +import org.wso2.carbon.automation.core.utils.HttpResponse; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class YouTubeAPITestCase extends APIManagerIntegrationTest { + private APIPublisherRestClient apiPublisher; + private APIStoreRestClient apiStore; + private String publisherURLHttp; + private String storeURLHttp; + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + super.init(0); + if (isBuilderEnabled()) { + publisherURLHttp = getServerURLHttp(); + storeURLHttp = getServerURLHttp(); + } + else { + publisherURLHttp = getPublisherServerURLHttp(); + storeURLHttp = getStoreServerURLHttp(); + } + apiPublisher = new APIPublisherRestClient(publisherURLHttp); + apiStore = new APIStoreRestClient(storeURLHttp); + } + + @Test(groups = {"wso2.am"}, description = "You Tube sample") + public void testYouTubeApiSample() throws Exception { + apiPublisher.login(userInfo.getUserName(), userInfo.getPassword()); + APIRequest apiRequest = new APIRequest("YoutubeFeeds", "youtube", new URL("http://gdata.youtube.com/feeds/api/standardfeeds")); + apiPublisher.addAPI(apiRequest); + + APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest("YoutubeFeeds", userInfo.getUserName(), APILifeCycleState.PUBLISHED); + apiPublisher.changeAPILifeCycleStatusTo(updateRequest); + + apiStore.login(userInfo.getUserName(), userInfo.getPassword()); + SubscriptionRequest subscriptionRequest = new SubscriptionRequest("YoutubeFeeds", userInfo.getUserName()); + apiStore.subscribe(subscriptionRequest); + + GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest("DefaultApplication"); + String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); + JSONObject response = new JSONObject(responseString); + String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + accessToken); + + Thread.sleep(2000); + HttpResponse youTubeResponse = HttpRequestUtil.doGet(getApiInvocationURLHttp("youtube/1.0.0/most_popular"), requestHeaders); + Assert.assertEquals(youTubeResponse.getResponseCode(), 200, "Response code mismatched when api invocation"); + Assert.assertTrue(youTubeResponse.getData().contains(""), "Response data mismatched when api invocation"); + + } + + @AfterClass(alwaysRun = true) + public void destroy() throws Exception { + super.cleanup(); + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/APIMgtTestUtil.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/APIMgtTestUtil.java new file mode 100644 index 0000000000..e312606688 --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/APIMgtTestUtil.java @@ -0,0 +1,89 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util; + + +import org.json.JSONException; +import org.json.JSONObject; +import org.wso2.carbon.am.tests.util.bean.APIBean; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; +import org.wso2.carbon.automation.core.utils.HttpResponse; + +import java.util.Date; + +public class APIMgtTestUtil { + + public static APIBean getAPIBeanFromHttpResponse(HttpResponse httpResponse) { + JSONObject jsonObject = null; + String APIName = null; + String APIProvider = null; + String APIVersion = null; + APIBean apiBean = null; + try { + jsonObject = new JSONObject(httpResponse.getData()); + APIName = ((JSONObject) jsonObject.get("api")).getString("name"); + APIVersion = ((JSONObject) jsonObject.get("api")).getString("version"); + APIProvider = ((JSONObject) jsonObject.get("api")).getString("provider"); + APIIdentifier identifier = new APIIdentifier(APIProvider, APIName, APIVersion); + apiBean = new APIBean(identifier); + apiBean.setContext(((JSONObject) jsonObject.get("api")).getString("context")); + apiBean.setDescription(((JSONObject) jsonObject.get("api")).getString("description")); + apiBean.setWsdlUrl(((JSONObject) jsonObject.get("api")).getString("wsdl")); + apiBean.setTags(((JSONObject) jsonObject.get("api")).getString("tags")); + apiBean.setAvailableTiers(((JSONObject) jsonObject.get("api")).getString("availableTiers")); + apiBean.setThumbnailUrl(((JSONObject) jsonObject.get("api")).getString("thumb")); + apiBean.setSandboxUrl(((JSONObject) jsonObject.get("api")).getString("sandbox")); + apiBean.setBusinessOwner(((JSONObject) jsonObject.get("api")).getString("bizOwner")); + apiBean.setBusinessOwnerEmail(((JSONObject) jsonObject.get("api")).getString("bizOwnerMail")); + apiBean.setTechnicalOwner(((JSONObject) jsonObject.get("api")).getString("techOwner")); + apiBean.setTechnicalOwnerEmail(((JSONObject) jsonObject.get("api")).getString("techOwnerMail")); + apiBean.setWadlUrl(((JSONObject) jsonObject.get("api")).getString("wadl")); + apiBean.setVisibility(((JSONObject) jsonObject.get("api")).getString("visibility")); + apiBean.setVisibleRoles(((JSONObject) jsonObject.get("api")).getString("roles")); + apiBean.setEndpointUTUsername(((JSONObject) jsonObject.get("api")).getString("epUsername")); + apiBean.setEndpointUTPassword(((JSONObject) jsonObject.get("api")).getString("epPassword")); + apiBean.setEndpointSecured((Boolean.getBoolean(((JSONObject) jsonObject.get("api")).getString("endpointTypeSecured")))); + apiBean.setTransports(((JSONObject) jsonObject.get("api")).getString("transport_http")); + apiBean.setTransports(((JSONObject) jsonObject.get("api")).getString("transport_https")); + apiBean.setInSequence(((JSONObject) jsonObject.get("api")).getString("inSequence")); + apiBean.setOutSequence(((JSONObject) jsonObject.get("api")).getString("outSequence")); + apiBean.setAvailableTiers(((JSONObject) jsonObject.get("api")).getString("availableTiersDisplayNames")); + //-----------Here are some of unused properties, if we need to use them add params to APIBean class + //((JSONObject) jsonObject.get("api")).getString("name"); + //((JSONObject) jsonObject.get("api")).getString("endpoint"); + //((JSONObject) jsonObject.get("api")).getString("subscriptionAvailability"); + //((JSONObject) jsonObject.get("api")).getString("subscriptionTenants"); + //((JSONObject) jsonObject.get("api")).getString("endpointConfig"); + //((JSONObject) jsonObject.get("api")).getString("responseCache"); + //(((JSONObject) jsonObject.get("api")).getString("cacheTimeout"); + //((JSONObject) jsonObject.get("api")).getString("endpointConfig"); + //((JSONObject) jsonObject.get("api")).getString("version"); + //((JSONObject) jsonObject.get("api")).getString("apiStores"); + // ((JSONObject) jsonObject.get("api")).getString("provider"); + //)((JSONObject) jsonObject.get("api")).getString("tierDescs"); + //((JSONObject) jsonObject.get("api")).getString("subs"); + //((JSONObject) jsonObject.get("api")).getString("context"); + // apiBean.setLastUpdated(Date.parse((JSONObject); jsonObject.get("api")).getString("lastUpdated"))); + // apiBean.setUriTemplates((JSONObject) jsonObject.get("api")).getString("templates")); + } catch (JSONException e) { + e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } + return apiBean; + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/APIPublisherRestClient.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/APIPublisherRestClient.java new file mode 100644 index 0000000000..3689a23c8a --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/APIPublisherRestClient.java @@ -0,0 +1,292 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util; + +import org.wso2.carbon.am.tests.util.bean.APILifeCycleStateRequest; +import org.wso2.carbon.am.tests.util.bean.APIRequest; +import org.wso2.carbon.automation.core.utils.HttpRequestUtil; +import org.wso2.carbon.automation.core.utils.HttpResponse; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class APIPublisherRestClient { + private String backEndUrl; + private static final String URL_SURFIX = "/publisher/site/blocks"; + private Map requestHeaders = new HashMap(); + + public APIPublisherRestClient(String backEndUrl) { + this.backEndUrl = backEndUrl; + if (requestHeaders.get("Content-Type") == null) { + this.requestHeaders.put("Content-Type", "application/x-www-form-urlencoded"); + } + } + + public HttpResponse login(String userName, String password) + throws Exception { + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + URL_SURFIX + "/user/login/ajax/login.jag") + , "action=login&username=" + userName + "&password=" + password + "", requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + String session = getSession(response.getHeaders()); + if (session == null) { + throw new Exception("No session cookie found with response"); + } + setSession(session); + return response; + } else { + throw new Exception("User Login failed> " + response.getData()); + } + + } + + public HttpResponse addAPI(APIRequest apiRequest) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + URL_SURFIX + "/item-add/ajax/add.jag") + , apiRequest.generateRequestParameters() + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Adding failed> " + response.getData()); + } + } + + public HttpResponse updateAPI(APIRequest apiRequest) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + URL_SURFIX + "/item-add/ajax/add.jag") + , apiRequest.generateRequestParameters("updateAPI") + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Adding failed> " + response.getData()); + } + } + + + public HttpResponse changeAPILifeCycleStatusTo(APILifeCycleStateRequest updateRequest) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/life-cycles/ajax/life-cycles.jag") + , updateRequest.generateRequestParameters() + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API LifeCycle Updating failed> " + response.getData()); + } + + } + + public HttpResponse getApi(String apiName, String provider) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/listing/ajax/item-list.jag") + , "action=getAPI&name=" + apiName + "&version=1.0.0&provider=" + provider + "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get API Information failed> " + response.getData()); + } + + /* name=YoutubeFeeds&version=1.0.0&provider=provider1&status=PUBLISHED&publishToGateway=true&action=updateStatus */ + + } + + public HttpResponse deleteApi(String name,String version,String provider) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/item-add/ajax/remove.jag") + , "action=removeAPI&name=" + name + "&version="+version+"&provider="+provider + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Deletion failed> " + response.getData()); + } + } + + public void setHttpHeader(String headerName, String value) { + this.requestHeaders.put(headerName, value); + } + + public String getHttpHeader(String headerName) { + return this.requestHeaders.get(headerName); + } + + public void removeHttpHeader(String headerName) { + this.requestHeaders.remove(headerName); + } + + private String getSession(Map responseHeaders) { + return responseHeaders.get("Set-Cookie"); + } + + private String setSession(String session) { + return requestHeaders.put("Cookie", session); + } + + private boolean checkAuthentication() throws Exception { + if (requestHeaders.get("Cookie") == null) { + throw new Exception("No Session Cookie found. Please login first"); + } + return true; + } + + /** + * @param apiName String name of the API that need to remove + * @param version String version of the API that need to remove + * @param provider String provider name of the API that need to remove + * @return + * @throws Exception when invocation does ont return 200 response + */ + public HttpResponse removeAPI(String apiName, String version, String provider) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/item-add/ajax/remove.jag") + , "action=removeAPI" + "&name=" + apiName + "&version=" + version + "&provider=" + provider + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + + public HttpResponse addDocument(String apiName, String version, String provider, String docName, String docType, String sourceType, String docUrl, String summary, String docLocation) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/documentation/ajax/docs.jag") + , "action=addDocumentation" + "&provider=" + provider + "&apiName=" + apiName + "&version=" + version + "&docName=" + docName + "&docType=" + docType + "&sourceType=" + sourceType + "&docUrl=" + docUrl + + summary + "&docLocation=" + docLocation + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + /* + docDetails.name = request.getParameter("docName"); + docDetails.content = request.getParameter("content"); + result = mod.addInlineContent(apiDetails, docDetails); + */ + public HttpResponse inlineContent(String apiName, String version, String provider, String docName, String content, String docDetails) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/documentation/ajax/docs.jag") + , "action=addInlineContent" + "&provider=" + provider + "&apiName=" + apiName + "&version=" + version + "&docName=" + docName + "&content=" + content + "&docDetails=" + docDetails + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse removeDocumentation(String apiName, String version, String provider, String docName, String docType) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/documentation/ajax/docs.jag") + , "action=removeDocumentation" + "&provider=" + provider + "&apiName=" + apiName + "&version=" + version + "&docName=" + docName + "&docType=" + docType + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse getAccessTokenData(String accessToken) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/tokens/ajax/token.jag") + , "action=getAccessTokenData" + "&accessToken=" + accessToken + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse revokeAccessToken(String accessToken, String consumerKey, String authUser) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/tokens/ajax/revokeToken.jag") + , "action=revokeAccessToken" + "&accessToken=" + accessToken+"&authUser="+authUser+"&consumerKey="+consumerKey + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + public HttpResponse revokeAccessTokenBySubscriber(String subscriberName) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/tokens/ajax/revokeToken.jag") + , "action=revokeAccessTokenBySubscriber" + "&subscriberName=" + subscriberName + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + public HttpResponse updatePermissions(String tierName, String permissionType, String roles) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/tiers/ajax/tiers.jag") + , "action=updatePermissions" + "&tierName=" + tierName + "&permissiontype=" + permissionType + "&roles=" + roles + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } + + + public HttpResponse createNewAPI(String provider, String apiName, String version, String newVersion) throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/overview/ajax/overview.jag") + , "action=createNewAPI" + "&provider=" + provider + "&apiName=" + apiName + "&version=" + version +"&newVersion="+newVersion + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/APIStoreRestClient.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/APIStoreRestClient.java new file mode 100644 index 0000000000..1c9d8787c0 --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/APIStoreRestClient.java @@ -0,0 +1,426 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util; + +import org.wso2.carbon.am.tests.util.bean.SubscriptionRequest; +import org.wso2.carbon.am.tests.util.bean.GenerateAppKeyRequest; +import org.wso2.carbon.automation.core.utils.HttpRequestUtil; +import org.wso2.carbon.automation.core.utils.HttpResponse; +import org.apache.commons.codec.binary.Base64; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class APIStoreRestClient { + private String backEndUrl; + private Map requestHeaders = new HashMap(); + + public APIStoreRestClient(String backEndUrl) { + this.backEndUrl = backEndUrl; + if (requestHeaders.get("Content-Type") == null) { + this.requestHeaders.put("Content-Type", "application/x-www-form-urlencoded"); + } + } + + public HttpResponse login(String userName, String password) + throws Exception { + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/user/login/ajax/login.jag") + , "action=login&username=" + userName + "&password=" + password + "", requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + String session = getSession(response.getHeaders()); + if (session == null) { + throw new Exception("No session cookie found with response"); + } + setSession(session); + return response; + } else { + throw new Exception("User Login failed> " + response.getData()); + } + + } + + public HttpResponse subscribe(SubscriptionRequest subscriptionRequest) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag") + , subscriptionRequest.generateRequestParameters() + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("API Subscription failed> " + response.getData()); + } + + } + + public HttpResponse generateApplicationKey(GenerateAppKeyRequest generateAppKeyRequest) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag") + , generateAppKeyRequest.generateRequestParameters() + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + + } + + public HttpResponse getAPI(String apiName) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/api/listing/ajax/list.jag?action=getAllPublishedAPIs") + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + + public void setHttpHeader(String headerName, String value) { + this.requestHeaders.put(headerName, value); + } + + public String getHttpHeader(String headerName) { + return this.requestHeaders.get(headerName); + } + + public void removeHttpHeader(String headerName) { + this.requestHeaders.remove(headerName); + } + + private String getSession(Map responseHeaders) { + return responseHeaders.get("Set-Cookie"); + } + + private String setSession(String session) { + return requestHeaders.put("Cookie", session); + } + + private boolean checkAuthentication() throws Exception { + if (requestHeaders.get("Cookie") == null) { + throw new Exception("No Session Cookie found. Please login first"); + } + return true; + } + + + public HttpResponse generateUserAccessKey(String consumeKey, String consumerSecret, String body, URL tokenEndpointURL) + throws Exception { + checkAuthentication(); + Map authenticationRequestHeaders = new HashMap(); + String basicAuthHeader = consumeKey + ":" +consumerSecret; + byte[] encodedBytes = Base64.encodeBase64(basicAuthHeader.getBytes()); + authenticationRequestHeaders.put("Content-Type", "application/x-www-form-urlencoded"); + authenticationRequestHeaders.put("Authorization", "Basic " + new String(encodedBytes)); + HttpResponse response = HttpRequestUtil.doPost(tokenEndpointURL + , body + , authenticationRequestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + + public HttpResponse getAllPublishedAPIs() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl+"/store/site/blocks/api/listing/ajax/list.jag?action=getAllPublishedAPIs" + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + + public HttpResponse getAllApplications() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl+"/store/site/blocks/application/application-list/ajax/application-list.jag?action=getApplications" + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + public HttpResponse getPublishedAPIsByApplication(String applicationName) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl+"/store/site/blocks/subscription/subscription-list/ajax/subscription-list.jag?action=getSubscriptionByApplication&app="+applicationName + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + + public HttpResponse addRatingToAPI(String apiName, String version, String provider, String rating) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl+"/store/site/blocks/api/api-info/ajax/api-info.jag?" + + "action=addRating&name=" + apiName + "&version=" + version + "&provider=" + provider + "&rating=" + rating + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + public HttpResponse removeRatingFromAPI(String apiName, String version, String provider) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl+"/store/site/blocks/api/api-info/ajax/api-info.jag?" + + "action=removeRating&name=" + apiName + "&version=" + version + "&provider=" + provider + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + + public HttpResponse isRatingActivated() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl+"/store/site/blocks/api/api-info/ajax/api-info.jag?" + + "action=isRatingActivated" + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + /* + apiData.name = request.getParameter("name"); + apiData.version = request.getParameter("version"); + apiData.provider = request.getParameter("provider") + */ + public HttpResponse getAllDocumentationOfApi(String apiName, String version, String provider) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl+"/store/site/blocks/api/listing/ajax/list.jag?" + + "action=getAllDocumentationOfApi&name=" + apiName + "&version=" + version + "&provider=" + provider + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + /* + tenant = request.getParameter("tenant"); + var start=request.getParameter("start"); + var end=request.getParameter("end"); + */ + public HttpResponse getAllPaginatedPublishedAPIs(String tenant, String start, String end) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl+"/store/site/blocks/api/listing/ajax/list.jag?" + + "action=getAllPaginatedPublishedAPIs&tenant=" + tenant + "&start=" + start + "&end=" + end + , requestHeaders); + if (response.getResponseCode() == 200) { + return response; + } else { + throw new Exception("Generating Application Key failed> " + response.getData()); + } + } + + public HttpResponse getAllPublishedAPIs(String tenant) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/api/listing/ajax/list.jag?action=getAllPublishedAPIs&tenant=" + tenant) + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse addApplication(String application, String tier, String callbackUrl, String description) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/application/application-add/ajax/application-add.jag?action=addApplication&tier=" + tier + "&callbackUrl="+callbackUrl+"&description="+description+"&application="+application) + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse getApplications() + throws Exception { + checkAuthentication(); + + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/application/application-list/ajax/application-list.jag?action=getApplications") + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse removeApplication(String application) + throws Exception { + checkAuthentication(); + + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/application/application-remove/ajax/application-remove.jag?action=removeApplication&application=" + application) + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse updateApplication(String applicationOld, String applicationNew, String callbackUrlNew, String descriptionNew, String tier) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/application/application-update/ajax/application-update.jag?" + + "action=updateApplication&applicationOld=" + applicationOld + "&applicationNew="+applicationNew+"&callbackUrlNew="+callbackUrlNew+ + "&descriptionNew="+descriptionNew+"&tier="+tier) + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + public HttpResponse getAllSubscriptions() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/subscription/subscription-list/ajax/subscription-list.jag?" + + "action=getAllSubscriptions") + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse getAllTags() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/tag/tag-cloud/ajax/list.jag?action=getAllTags") + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + /* + name = request.getParameter("name"); + version = request.getParameter("version"); + provider = request.getParameter("provider"); + comment = request.getParameter("comment"); + /home/sanjeewa/carbon/turing/components/apimgt/api-store-web/1.2.0/src/site/blocks/comment/comment-add/ajax/comment-add.jag + */ + public HttpResponse addComment(String name, String version, String provider, String comment) + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl + "/store/site/blocks/comment/comment-add/ajax/comment-add.jag?" + + "action=addComment&name=" + name + "&version="+version+"&provider="+provider+"&comment="+comment + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse isCommentActivated() + throws Exception { + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doGet(backEndUrl + "/store/site/blocks/comment/comment-add/ajax/comment-add.jag?" + + "action=isCommentActivated" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } + + public HttpResponse getRecentlyAddedAPIs(String tenant, String limit) + throws Exception { + ///home/sanjeewa/carbon/turing/components/apimgt/api-store-web/1.2.0/src/site/blocks/api/recently-added/ajax/list.jag + checkAuthentication(); + HttpResponse response = HttpRequestUtil.doPost(new URL(backEndUrl + "/store/site/blocks/api/recently-added/ajax/list.jag?action=getRecentlyAddedAPIs"+ + "&tenant="+tenant+"&limit="+limit) + , "" + , requestHeaders); + if (response.getResponseCode() == 200) { + VerificationUtil.checkErrors(response); + return response; + } else { + throw new Exception("Get Api Information failed> " + response.getData()); + } + + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/VerificationUtil.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/VerificationUtil.java new file mode 100644 index 0000000000..fca97b338e --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/VerificationUtil.java @@ -0,0 +1,31 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util; + +import org.json.JSONObject; +import org.wso2.carbon.automation.core.utils.HttpResponse; + +public class VerificationUtil { + public static void checkErrors(HttpResponse response) throws Exception { + JSONObject jsonObject = new JSONObject(response.getData()); + if ((Boolean) jsonObject.get("error")) { + throw new Exception("Operation not successful: " + jsonObject.get("message").toString()); + } + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/WireMonitor.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/WireMonitor.java new file mode 100644 index 0000000000..dbb71dcacb --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/WireMonitor.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2005-2010, 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.carbon.am.tests.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; + +class WireMonitor extends Thread { + private Log log = LogFactory.getLog(WireMonitor.class); + private static final int TIMEOUT_VALUE = 60000; + private int port; + private ServerSocket providerSocket; + private Socket connection = null; + public String message = ""; + private WireMonitorServer trigger; + + public void run() { + try { + + // creating a server socket + providerSocket = new ServerSocket(port, 10); + + log.info("Waiting for connection"); + connection = providerSocket.accept(); + log.info("Connection received from " + + connection.getInetAddress().getHostName()); + InputStreamReader in = new InputStreamReader(connection.getInputStream()); + BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String line = ""; + Long time = System.currentTimeMillis(); + while ((line = rd.readLine()) != null && !line.equals("")) { + message = message + line; + // In this case no need of reading more than timeout value + if (System.currentTimeMillis() > (time + TIMEOUT_VALUE)) { + break; + } + } + + // Signaling Main thread to continue + trigger.response = message; + trigger.isFinished = true; + + //Sending default response + PrintWriter out = new PrintWriter(connection.getOutputStream()); + String responseText = "[Response] Request Received. This is the default Response."; + String httpResponse = "HTTP/1.1 200 OK\n" + + "Content-Type: text/xml;charset=utf-8\n" + + "Content-Length: " + responseText.length() + "\n" + + "\n" + + responseText; + out.write(httpResponse); + out.flush(); + + in.close(); + rd.close(); + out.close(); + + } catch (IOException ioException) { + ioException.printStackTrace(); + } finally { + try { + connection.close(); + providerSocket.close(); + } catch (Exception e) { + + } + } + + } + + public WireMonitor(int listenPort, WireMonitorServer trigger) { + port = listenPort; + this.trigger = trigger; + } + +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/WireMonitorServer.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/WireMonitorServer.java new file mode 100644 index 0000000000..c7a98bc874 --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/WireMonitorServer.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2005-2010, 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.carbon.am.tests.util; + +/** + * This class can be used to capture wire messages + * + */ +public class WireMonitorServer { + private static final int TIMEOUT_VALUE = 60000; + boolean isFinished = false; + String response; + int port; + + /** + * Start listening to a port + * + * @param port + * to be listened + */ + public WireMonitorServer(int port) { + this.port = port; + } + + public void start() { + response = ""; + isFinished = false; + Thread thread = new WireMonitor(port, this); + thread.start(); + } + + + /** + * Wait until response is received and returns + * @return will return null if response is not received + */ + public String getCapturedMessage() { + Long time = System.currentTimeMillis(); + while (!isFinished) { + // If wire monitor is not responding than 2min this will continue + if (System.currentTimeMillis() > (time + TIMEOUT_VALUE)) { + break; + } + } + return response; + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/APIBean.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/APIBean.java new file mode 100644 index 0000000000..fd63bc60b2 --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/APIBean.java @@ -0,0 +1,46 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util.bean; + +import org.wso2.carbon.apimgt.api.model.*; + +import java.util.HashSet; +import java.util.Set; + +public class APIBean extends API { + private String tags; + private String availableTiers; + public APIBean(APIIdentifier id) { + super(id); + } + + public void setAvailableTiers(String availableTiers) { + this.availableTiers = availableTiers; + } + + public void setTags(String tags) { + this.tags = tags; + Set stringSet = new HashSet(); + String[] strings =tags.split(","); + for (String str :strings){ + stringSet.add(str); + } + super.addTags(stringSet); + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/APILifeCycleState.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/APILifeCycleState.java new file mode 100644 index 0000000000..e72188bdcc --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/APILifeCycleState.java @@ -0,0 +1,33 @@ +package org.wso2.carbon.am.tests.util.bean; +/* +*Copyright (c) 2005-2010, 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. +*/ + +public enum APILifeCycleState { + + PUBLISHED("PUBLISHED"), CREATED("CREATED"), DEPRECATED("DEPRECATED"), BLOCKED("BLOCKED"); + + private String state; + + APILifeCycleState(String state) { + this.state = state; + } + + public String getState() { + return state; + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/APILifeCycleStateRequest.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/APILifeCycleStateRequest.java new file mode 100644 index 0000000000..f1049864b6 --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/APILifeCycleStateRequest.java @@ -0,0 +1,83 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util.bean; + + +/** + * action=updateStatus&name=YoutubeFeeds&version=1.0.0&provider=provider1&status=PUBLISHED&publishToGateway=true + */ +public class APILifeCycleStateRequest extends AbstractRequest { + private String name; + private String status; + private String provider; + private String version = "1.0.0"; + private String publishToGateway = "true"; + + public APILifeCycleStateRequest(String apiName, String provider, APILifeCycleState status) { + this.name = apiName; + this.status = status.getState(); + this.provider = provider; + } + @Override + public void setAction() { + setAction("updateStatus"); + } + + @Override + public void init() { + addParameter("name",name); + addParameter("status", status); + addParameter("provider", provider); + + addParameter("version", version); + addParameter("publishToGateway", publishToGateway); + } + + public String getName() { + return name; + } + + public String getState() { + return status; + } + + public void setState(APILifeCycleState status) { + this.status = status.getState(); + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getProvider() { + return provider; + } + + public boolean getPublishToGateway() { + return Boolean.valueOf(publishToGateway); + } + + public void setPublishToGateway(boolean publishToGateway) { + this.publishToGateway = String.valueOf(publishToGateway); + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/APIRequest.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/APIRequest.java new file mode 100644 index 0000000000..1cc5802a7d --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/APIRequest.java @@ -0,0 +1,283 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util.bean; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.net.URL; + +/** + * action=addAPI&name=YoutubeFeeds&visibility=public&version=1.0.0&description=Youtube Live Feeds&endpointType=nonsecured + * &http_checked=http&https_checked=https&endpoint=http://gdata.youtube.com/feeds/api/standardfeeds&wsdl=& + * tags=youtube,gdata,multimedia&tier=Silver&thumbUrl=http://www.10bigideas.com.au/www/573/files/pf-thumbnail-youtube_logo.jpg + * &context=/youtube&tiersCollection=Gold&resourceCount=0&resourceMethod-0=GET + * &resourceMethodAuthType-0=Application&resourceMethodThrottlingTier-0=Unlimited&uriTemplate-0=/* + */ + +public class APIRequest extends AbstractRequest { + + private String name; + private String context; + private JSONObject endpoint; + + private String visibility = "public"; + private String version = "1.0.0"; + private String description = "description"; + private String endpointType = "nonsecured"; + private String http_checked = "http"; + private String https_checked = "https"; + private String tags = "tags"; + private String tier = "Silver"; + private String thumbUrl = ""; + private String tiersCollection = "Gold"; + private String resourceCount = "0"; + private String resourceMethod = "GET,POST"; + private String resourceMethodAuthType = "Application & Application User,Application & Application User"; + private String resourceMethodThrottlingTier = "Unlimited,Unlimited"; + private String uriTemplate = "/*"; + private String roles = ""; + private String wsdl = ""; + + public String getSandbox() { + return sandbox; + } + + public void setSandbox(String sandbox) { + this.sandbox = sandbox; + } + + private String sandbox = ""; + + public String getRoles() { + return roles; + } + + public void setRoles(String roles) { + this.roles = roles; + } + + public String getWsdl() { + return wsdl; + } + + public void setWsdl(String wsdl) { + this.wsdl = wsdl; + } + + + + private String provider ="admin"; + + public APIRequest(String apiName, String context, URL endpointUrl) { + this.name = apiName; + this.context = context; + try { + this.endpoint = new JSONObject("{\"production_endpoints\":{\"url\":\"" + + endpointUrl + "\",\"config\":null},\"endpoint_type\":\"" + + endpointUrl.getProtocol() + "\"}"); + } catch (JSONException e) { + //ignore + } + + } + + @Override + public void setAction() { + setAction("addAPI"); + } + + public void setAction(String action) { + super.setAction(action); + } + + @Override + public void init() { + addParameter("name", name); + addParameter("context", context); + addParameter("endpoint_config", endpoint.toString()); + addParameter("provider",getProvider()); + addParameter("visibility", getVisibility()); + addParameter("version", getVersion()); + addParameter("description", getDescription()); + addParameter("endpointType", getEndpointType()); + addParameter("http_checked", getHttp_checked()); + addParameter("https_checked", getHttps_checked()); + addParameter("tags", getTags()); + addParameter("tier", getTier()); + addParameter("thumbUrl", getThumbUrl()); + addParameter("tiersCollection", getTiersCollection()); + addParameter("resourceCount", getResourceCount()); + addParameter("resourceMethod-0", getResourceMethod()); + addParameter("resourceMethodAuthType-0", getResourceMethodAuthType()); + addParameter("resourceMethodThrottlingTier-0", getResourceMethodThrottlingTier()); + addParameter("uriTemplate-0", getUriTemplate()); + if(roles.length()>1){ + addParameter("roles", getRoles()); + } + if(wsdl.length()>1) { + addParameter("wsdl", getWsdl()); + } + if(sandbox.length()>1) { + addParameter("sandbox", getSandbox()); + } + + } + + public String getProvider() { + return provider; + } + + public void setProvider(String provider) { + this.provider = provider; + } + + public String getName() { + return name; + } + + public JSONObject getEndpointConfig() { + return endpoint; + } + + public String getContext() { + return context; + } + + public String getVisibility() { + return visibility; + } + + public void setVisibility(String visibility) { + this.visibility = visibility; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getEndpointType() { + return endpointType; + } + + public void setEndpointType(String endpointType) { + this.endpointType = endpointType; + } + + public String getHttp_checked() { + return http_checked; + } + + public void setHttp_checked(String http_checked) { + this.http_checked = http_checked; + } + + public String getHttps_checked() { + return https_checked; + } + + public void setHttps_checked(String https_checked) { + this.https_checked = https_checked; + } + + public String getTags() { + return tags; + } + + public void setTags(String tags) { + this.tags = tags; + } + + public String getTier() { + return tier; + } + + public void setTier(String tier) { + this.tier = tier; + } + + public String getThumbUrl() { + return thumbUrl; + } + + public void setThumbUrl(String thumbUrl) { + this.thumbUrl = thumbUrl; + } + + public String getTiersCollection() { + return tiersCollection; + } + + public void setTiersCollection(String tiersCollection) { + this.tiersCollection = tiersCollection; + } + + public String getResourceCount() { + return resourceCount; + } + + public void setResourceCount(String resourceCount) { + this.resourceCount = resourceCount; + } + + public String getResourceMethod() { + return resourceMethod; + } + + public void setResourceMethod(String resourceMethod) { + this.resourceMethod = resourceMethod; + } + + public String getResourceMethodAuthType() { + return resourceMethodAuthType; + } + + public void setResourceMethodAuthType(String resourceMethodAuthType) { + this.resourceMethodAuthType = resourceMethodAuthType; + } + + public String getResourceMethodThrottlingTier() { + return resourceMethodThrottlingTier; + } + + public void setResourceMethodThrottlingTier(String resourceMethodThrottlingTier) { + this.resourceMethodThrottlingTier = resourceMethodThrottlingTier; + } + + public String getUriTemplate() { + return uriTemplate; + } + + public void setUriTemplate(String uriTemplate) { + this.uriTemplate = uriTemplate; + } + +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/AbstractRequest.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/AbstractRequest.java new file mode 100644 index 0000000000..3da20dc478 --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/AbstractRequest.java @@ -0,0 +1,67 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util.bean; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +public abstract class AbstractRequest { + public String action; + private Map parameterMap = new HashMap(); + private static final String ACTION_PARAMETER_VALUE = "action"; + + public String generateRequestParameters() { + parameterMap.clear(); + setAction(); + init(); + String requestParams = ACTION_PARAMETER_VALUE + "=" + action; + Iterator irt = parameterMap.keySet().iterator(); + while (irt.hasNext()) { + String key = irt.next(); + requestParams = requestParams + "&" + key + "=" + parameterMap.get(key); + } + return requestParams; + } + + public String generateRequestParameters(String actionName) { + parameterMap.clear(); + setAction(); + init(); + String requestParams = ACTION_PARAMETER_VALUE + "=" + actionName; + Iterator irt = parameterMap.keySet().iterator(); + while (irt.hasNext()) { + String key = irt.next(); + requestParams = requestParams + "&" + key + "=" + parameterMap.get(key); + } + return requestParams; + } + + public void addParameter(String key, String value) { + parameterMap.put(key, value); + } + + public abstract void setAction(); + + public abstract void init(); + + public void setAction(String actionName) { + this.action = actionName; + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/GenerateAppKeyRequest.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/GenerateAppKeyRequest.java new file mode 100644 index 0000000000..951b17c523 --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/GenerateAppKeyRequest.java @@ -0,0 +1,81 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util.bean; + +/** + * action=generateApplicationKey&application=DefaultApplication&keytype=PRODUCTION&callbackUrl=&authorizedDomains=ALL&validityTime=360000 + */ +public class GenerateAppKeyRequest extends AbstractRequest { + + private String application ="DefaultApplication"; + private String keyType = "PRODUCTION"; + private String callbackUrl = "some-url"; + private String authorizedDomains = "ALL"; + private int validityTime = 360000; + + public GenerateAppKeyRequest(String application) { + this.application = application; + } + + @Override + public void setAction() { + setAction("generateApplicationKey"); + } + + @Override + public void init() { + addParameter("application", application); + addParameter("keytype", keyType); + addParameter("callbackUrl", callbackUrl); + addParameter("authorizedDomains", authorizedDomains); + addParameter("validityTime", String.valueOf(validityTime)); + } + + public String getKeyType() { + return keyType; + } + + public void setKeyType(String keyType) { + this.keyType = keyType; + } + + public String getCallbackUrl() { + return callbackUrl; + } + + public void setCallbackUrl(String callbackUrl) { + this.callbackUrl = callbackUrl; + } + + public String getAuthorizedDomains() { + return authorizedDomains; + } + + public void setAuthorizedDomains(String authorizedDomains) { + this.authorizedDomains = authorizedDomains; + } + + public int getValidityTime() { + return validityTime; + } + + public void setValidityTime(int validityTime) { + this.validityTime = validityTime; + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/SubscriptionRequest.java b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/SubscriptionRequest.java new file mode 100644 index 0000000000..92cd2697ba --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/carbon/am/tests/util/bean/SubscriptionRequest.java @@ -0,0 +1,82 @@ +/* +*Copyright (c) 2005-2010, 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.carbon.am.tests.util.bean; + +/** + * action=addAPISubscription&name=apiName&version=1.0.0&provider=provider&tier=Gold&applicationName=DefaultApplication + */ +public class SubscriptionRequest extends AbstractRequest { + + private String name; + private String provider; + private String version = "1.0.0"; + private String applicationName = "DefaultApplication"; + private String tier = "Gold"; + + public SubscriptionRequest(String apiName, String provider) { + this.name = apiName; + this.provider = provider; + } + + @Override + public void setAction() { + setAction("addAPISubscription"); + } + + @Override + public void init() { + addParameter("name", name); + addParameter("provider", provider); + addParameter("version", version); + addParameter("applicationName", applicationName); + addParameter("tier", tier); + } + + public String getName() { + return name; + } + + public String getProvider() { + return provider; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getApplicationName() { + return applicationName; + } + + public void setApplicationName(String applicationName) { + this.applicationName = applicationName; + } + + public String getTier() { + return tier; + } + + public void setTier(String tier) { + this.tier = tier; + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/JmeterDomainRestrictionTestCase.java b/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/JmeterDomainRestrictionTestCase.java new file mode 100644 index 0000000000..a5a8908610 --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/JmeterDomainRestrictionTestCase.java @@ -0,0 +1,68 @@ +/* +*Copyright (c) 2005-2010, 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.jmeter.tests; + +import org.apache.axiom.om.OMElement; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.automation.tools.jmeter.JMeterTest; +import org.wso2.automation.tools.jmeter.JMeterTestManager; +import org.wso2.carbon.automation.core.ProductConstant; +import org.wso2.carbon.automation.core.utils.UserInfo; +import org.wso2.carbon.automation.core.utils.UserListCsvReader; +import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentBuilder; +import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentVariables; + +import java.io.File; + +/** + * This jmeter based test case added to automate test for issue + * https://wso2.org/jira/browse/APIMANAGER-850 + */ +public class JmeterDomainRestrictionTestCase { + + protected Log log = LogFactory.getLog(getClass()); + protected EnvironmentVariables amServer; + protected UserInfo userInfo; + protected OMElement synapseConfiguration = null; + + @BeforeClass(alwaysRun = true) + public void testChangeTransportMechanism() throws Exception { + init(0); + } + + protected void init(int userId) throws Exception { + userInfo = UserListCsvReader.getUserInfo(userId); + EnvironmentBuilder builder = new EnvironmentBuilder().am(userId); + amServer = builder.build().getAm(); + } + + @Test(groups = "wso2.am", description = "Login to api manager as user2") + public void testListServices() throws Exception { + JMeterTest script = + new JMeterTest(new File(ProductConstant.SYSTEM_TEST_RESOURCE_LOCATION + File.separator + "artifacts" + + File.separator + "AM" + File.separator + "scripts" + + File.separator + "DomainRestrictionTest.jmx")); + + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(script); + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/JmeterLoginTestCase.java b/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/JmeterLoginTestCase.java new file mode 100644 index 0000000000..89b7afaf6a --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/JmeterLoginTestCase.java @@ -0,0 +1,71 @@ +/* +*Copyright (c) 2005-2010, 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.jmeter.tests; + +import org.apache.axiom.om.OMElement; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.automation.tools.jmeter.JMeterTest; +import org.wso2.automation.tools.jmeter.JMeterTestManager; +import org.wso2.carbon.automation.core.ProductConstant; +import org.wso2.carbon.automation.core.annotations.ExecutionEnvironment; +import org.wso2.carbon.automation.core.annotations.SetEnvironment; +import org.wso2.carbon.automation.core.utils.UserInfo; +import org.wso2.carbon.automation.core.utils.UserListCsvReader; +import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentBuilder; +import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentVariables; +import org.wso2.carbon.automation.core.utils.serverutils.ServerConfigurationManager; +import org.wso2.carbon.utils.ServerConstants; + +import java.io.File; +import java.io.IOException; + +public class JmeterLoginTestCase { + + protected Log log = LogFactory.getLog(getClass()); + protected EnvironmentVariables amServer; + protected UserInfo userInfo; + protected OMElement synapseConfiguration = null; + + @BeforeClass(alwaysRun = true) + public void testChangeTransportMechanism() throws Exception { + init(0); + } + + protected void init(int userId) throws Exception { + userInfo = UserListCsvReader.getUserInfo(userId); + EnvironmentBuilder builder = new EnvironmentBuilder().am(userId); + amServer = builder.build().getAm(); + } + + @Test(groups = "wso2.am", description = "Login to api manager as user2") + public void testListServices() throws Exception { + JMeterTest script = + new JMeterTest(new File(ProductConstant.SYSTEM_TEST_RESOURCE_LOCATION + File.separator + "artifacts" + + File.separator + "AM" + File.separator + "scripts" + + File.separator + "API_Manager_Login_Test.jmx")); + + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(script); + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/JmeterSuperTenantTestCase.java b/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/JmeterSuperTenantTestCase.java new file mode 100644 index 0000000000..655d74efed --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/JmeterSuperTenantTestCase.java @@ -0,0 +1,64 @@ +/* +*Copyright (c) 2005-2010, 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.jmeter.tests; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.automation.tools.jmeter.JMeterTest; +import org.wso2.automation.tools.jmeter.JMeterTestManager; +import org.wso2.carbon.automation.core.ProductConstant; +import org.wso2.carbon.automation.core.utils.UserInfo; +import org.wso2.carbon.automation.core.utils.UserListCsvReader; +import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentBuilder; +import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentVariables; + +import java.io.File; + +public class JmeterSuperTenantTestCase { + protected Log log = LogFactory.getLog(JmeterSuperTenantTestCase.class); + protected EnvironmentVariables amServer; + protected UserInfo userInfo; + + @BeforeClass(alwaysRun = true) + public void testChangeTransportMechanism() throws Exception { + init(0); + } + + protected void init(int userId) throws Exception { + userInfo = UserListCsvReader.getUserInfo(userId); + EnvironmentBuilder builder = new EnvironmentBuilder().am(userId); + amServer = builder.build().getAm(); + } + + @Test(groups = "wso2.am", description = "Covers API creation, publish api get default app id," + + " subscribe users to default app, invoke api - On a" + + " super tenant setup") + public void testListServices() throws Exception { + JMeterTest script = + new JMeterTest(new File(ProductConstant.SYSTEM_TEST_RESOURCE_LOCATION + File.separator + "artifacts" + + File.separator + "AM" + File.separator + "scripts" + + File.separator + "basic_functionality_test.jmx")); + + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(script); + } +} + diff --git a/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/JmeterTestCases.java b/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/JmeterTestCases.java new file mode 100644 index 0000000000..bbc39be067 --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/JmeterTestCases.java @@ -0,0 +1,82 @@ +package org.wso2.jmeter.tests; + +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; + +import org.apache.axiom.om.OMElement; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.automation.tools.jmeter.JMeterTest; +import org.wso2.automation.tools.jmeter.JMeterTestManager; +import org.wso2.carbon.automation.core.ProductConstant; +import org.wso2.carbon.automation.core.annotations.ExecutionEnvironment; +import org.wso2.carbon.automation.core.annotations.SetEnvironment; +import org.wso2.carbon.automation.core.utils.UserInfo; +import org.wso2.carbon.automation.core.utils.UserListCsvReader; +import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentBuilder; +import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentVariables; +import org.wso2.carbon.automation.core.utils.serverutils.ServerConfigurationManager; +import org.wso2.carbon.automation.utils.esb.StockQuoteClient; +import org.wso2.carbon.h2.osgi.utils.CarbonUtils; +import org.wso2.carbon.utils.ServerConstants; + +public class JmeterTestCases { + + private ServerConfigurationManager serverConfigurationManager; + + protected Log log = LogFactory.getLog(getClass()); + protected EnvironmentVariables amServer; + protected UserInfo userInfo; + protected OMElement synapseConfiguration = null; + + @SetEnvironment(executionEnvironments = {ExecutionEnvironment.integration_all}) + @BeforeClass(alwaysRun = true) + public void testChangeTransportMechanism() throws Exception, AxisFault { + init(2); + serverConfigurationManager = new ServerConfigurationManager(amServer.getBackEndUrl()); + String carbonHome = System.getProperty(ServerConstants.CARBON_HOME); + + File axis2xmlFile = new File(carbonHome + File.separator + "repository" + File.separator + "conf" + + File.separator + "axis2" + File.separator + "axis2.xml"); + + File sourceAxis2xmlFile = new File(carbonHome + File.separator + "repository" + File.separator + + "conf" + File.separator + "axis2" + File.separator + "axis2.xml_NHTTP"); + + if (!axis2xmlFile.exists() || !sourceAxis2xmlFile.exists()) { + throw new IOException("File not found in given location"); + } + + serverConfigurationManager.applyConfiguration(sourceAxis2xmlFile, axis2xmlFile); + } + + protected void init(int userId) throws Exception { + userInfo = UserListCsvReader.getUserInfo(userId); + EnvironmentBuilder builder = new EnvironmentBuilder().am(userId); + amServer = builder.build().getAm(); + } + + @SetEnvironment(executionEnvironments = {ExecutionEnvironment.integration_all}) + @Test(groups = "wso2.am", description = "Covers tenant creation, role creation, API creation, publish api," + + "get default app id, subscribe users to default app, invoke api") + public void testListServices() throws Exception { + JMeterTest script = + new JMeterTest(new File(ProductConstant.SYSTEM_TEST_RESOURCE_LOCATION + File.separator + "artifacts" + + File.separator + "AM" + File.separator + "scripts" + + File.separator + "API_Manager_functionality_and_loadTest.jmx")); + + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(script); + } + + @SetEnvironment(executionEnvironments = {ExecutionEnvironment.integration_all}) + @AfterClass(alwaysRun = true) + public void testCleanup() throws Exception { + serverConfigurationManager.restoreToLastConfiguration(); + serverConfigurationManager = null; + } +} diff --git a/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/JmeterTransportRestrictionTestCase.java b/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/JmeterTransportRestrictionTestCase.java new file mode 100644 index 0000000000..79dee53152 --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/JmeterTransportRestrictionTestCase.java @@ -0,0 +1,43 @@ +/* +*Copyright (c) 2005-2010, 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.jmeter.tests; + +import org.testng.annotations.Test; +import org.wso2.automation.tools.jmeter.JMeterTest; +import org.wso2.automation.tools.jmeter.JMeterTestManager; +import org.wso2.carbon.automation.core.ProductConstant; + +import java.io.File; + +public class JmeterTransportRestrictionTestCase { + + @Test(groups = "wso2.am", description = "Covers API creation, publish api get default app id," + + " subscribe users to default app, invoke api - On a" + + " super tenant setup") + public void testListServices() throws Exception { + JMeterTest script = + new JMeterTest(new File(ProductConstant.SYSTEM_TEST_RESOURCE_LOCATION + File.separator + "artifacts" + + File.separator + "AM" + File.separator + "scripts" + + File.separator + "transport_restriction_check.jmx")); + + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(script); + } +} + diff --git a/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/PassthroughTestCase.java b/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/PassthroughTestCase.java new file mode 100644 index 0000000000..95b77bd1fb --- /dev/null +++ b/modules/integration/tests/src/test/java/org/wso2/jmeter/tests/PassthroughTestCase.java @@ -0,0 +1,120 @@ +package org.wso2.jmeter.tests; + +import org.apache.axiom.om.OMElement; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.automation.tools.jmeter.JMeterTest; +import org.wso2.automation.tools.jmeter.JMeterTestManager; +import org.wso2.carbon.am.tests.util.WireMonitorServer; +import org.wso2.carbon.automation.core.ProductConstant; +import org.wso2.carbon.automation.core.annotations.ExecutionEnvironment; +import org.wso2.carbon.automation.core.annotations.SetEnvironment; +import org.wso2.carbon.automation.core.utils.UserInfo; +import org.wso2.carbon.automation.core.utils.UserListCsvReader; +import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentBuilder; +import org.wso2.carbon.automation.core.utils.environmentutils.EnvironmentVariables; +import org.wso2.carbon.automation.core.utils.serverutils.ServerConfigurationManager; +import org.wso2.carbon.utils.ServerConstants; + +import java.io.File; +import java.io.IOException; + +public class PassthroughTestCase { + + private ServerConfigurationManager serverConfigurationManager; + + private Log log = LogFactory.getLog(getClass()); + private EnvironmentVariables amServer; + private UserInfo userInfo; + private OMElement synapseConfiguration = null; + + @SetEnvironment(executionEnvironments = {ExecutionEnvironment.integration_all}) + @BeforeClass(alwaysRun = true) + public void testChangeTransportMechanism() throws Exception, AxisFault { + int userId = 2; + userInfo = UserListCsvReader.getUserInfo(userId); + EnvironmentBuilder builder = new EnvironmentBuilder().am(userId); + amServer = builder.build().getAm(); + } + + + @SetEnvironment(executionEnvironments = {ExecutionEnvironment.integration_all}) + @Test(groups = "wso2.am", description = "Covers tenant creation, role creation, API creation, publish api," + + "get default app id, subscribe users to default app, invoke api") + public void testListServices() throws Exception { + JMeterTest script = + new JMeterTest(new File(ProductConstant.SYSTEM_TEST_RESOURCE_LOCATION + File.separator + "artifacts" + + File.separator + "AM" + File.separator + "scripts" + + File.separator + "API_Manager_functionality_and_loadTest_new_tenant.jmx")); + + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(script); + } + + @SetEnvironment(executionEnvironments = {ExecutionEnvironment.integration_all}) + @Test(groups = "wso2.am", description = "creates and API, subscribe to it and send GET and DELETE requests without " + + "Content-Type header and checks for if the Content-Type header is forcefully added by APIM, " + + "which should not happen") + public void JIRA_APIMANAGER_1397_testContentTypeHeaderInsertionCheck() throws Exception { + JMeterTest publishScript = new JMeterTest(new File(ProductConstant.SYSTEM_TEST_RESOURCE_LOCATION + File.separator + + "artifacts" + File.separator + "AM" + File.separator + "scripts" + + File.separator + "content_type_check_publish_and_subscribe_script.jmx")); + + JMeterTestManager manager = new JMeterTestManager(); + manager.runTest(publishScript); + + WireMonitorServer wireMonitorServer = new WireMonitorServer(6789); + + wireMonitorServer.start(); + + Thread.sleep(1000); + + JMeterTest scriptGET = new JMeterTest(new File(ProductConstant.SYSTEM_TEST_RESOURCE_LOCATION + File.separator + + "artifacts" + File.separator + "AM" + File.separator + "scripts" + + File.separator + "content_type_check_for_GET_script.jmx")); + + manager.runTest(scriptGET); + + while (true) { + String reply = wireMonitorServer.getCapturedMessage(); + if(reply.length()>1) + if(reply.contains("ThisParamIsRequiredForTest_GET")){ + /** + * Assert for the Content-Type header + */ + Assert.assertTrue(!reply.contains("Content-Type"), "Content-Type header has been added to GET request forcefully!!"); + } + break; + } + + wireMonitorServer = new WireMonitorServer(6789); + + wireMonitorServer.start(); + + Thread.sleep(1000); + + JMeterTest scriptDELETE = new JMeterTest(new File(ProductConstant.SYSTEM_TEST_RESOURCE_LOCATION + File.separator + + "artifacts" + File.separator + "AM" + File.separator + "scripts" + + File.separator + "content_type_check_for_DELETE_script.jmx")); + + manager.runTest(scriptDELETE); + + while (true) { + String reply = wireMonitorServer.getCapturedMessage(); + if(reply.length()>1) + if(reply.contains("ThisParamIsRequiredForTest_DELETE")){ + /** + * Assert for the Content-Type header + */ + Assert.assertTrue(!reply.contains("Content-Type"), "Content-Type header has been added to DELETE request forcefully!!"); + } + break; + } + + } +} diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/hostobjecttest/api-manager.xml b/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/hostobjecttest/api-manager.xml new file mode 100755 index 0000000000..a7cbbc3a14 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/hostobjecttest/api-manager.xml @@ -0,0 +1,537 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + admin + + admin + + + + + + X-JWT-Assertion + + + org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever + + + http://wso2.org/claims + + + SHA256withRSA + + + true + + + true + + + + + + + + + + + + Production and Sandbox + + 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} + + + + + true + + + referer + + + + + true + + + + + + false + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + 7612 + + + tcp://localhost:7612/ + + + admin + + + admin + + + + + + + + false + + + UA-XXXXXXXX-X + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + + admin + + + admin + + true + + + + true + + + + WSClient + 10397 + 10000 + 10397 + + true + + + + + + + + /oauth2/token + + + false + + + + + + + true + + + + + + true + + + subscriber + + + true + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/store + + true + + true + + + true + + + true + + + + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/publisher + + + + + + + + + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + + + + + + + + + + true + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + /resource + http://localhost:9764/resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + Store1 + http://localhost:9763/store + user1@tenantdomain1.com + test123 + + + + + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + GET,POST,PUT,DELETE,OPTIONS + + + + diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/jaggery/test.jag b/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/jaggery/test.jag new file mode 100644 index 0000000000..48d3201391 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/jaggery/test.jag @@ -0,0 +1,5 @@ +<% + application.put("wso2", "test artifacts.AM.configFiles.jaggery application value"); + print(application.get("wso2")); + application.remove("wso2"); +%> \ No newline at end of file diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/throttling/throttle-policy.xml b/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/throttling/throttle-policy.xml new file mode 100755 index 0000000000..aa5de6f71d --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/throttling/throttle-policy.xml @@ -0,0 +1,34 @@ + + + + 127.0.0.1 + + + + 1 + 60000 + + + + + + + other + + + + 2 + 60000 + + + + + + + 1000 + + other + + + \ No newline at end of file diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/tokenTest/api-manager.xml b/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/tokenTest/api-manager.xml new file mode 100755 index 0000000000..628b9aad19 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/tokenTest/api-manager.xml @@ -0,0 +1,556 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + admin + + admin + + + + + + X-JWT-Assertion + + + org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever + + + http://wso2.org/claims + + + SHA256withRSA + + + true + + + true + + + + + + + + + + + + Production and Sandbox + + 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} + + + + + true + + + referer + + + + + true + + + + + + false + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + 7612 + + + tcp://localhost:7612/ + + + admin + + + admin + + + + + + + + false + + + UA-XXXXXXXX-X + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + + admin + + + admin + + true + + + + true + + + + WSClient + 10397 + 10000 + 10397 + + true + + + + + + + + /oauth2/token + + + false + + + + + + + true + + + + + + true + + + subscriber + + + true + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/store + + true + + true + + + true + + + true + + + + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/publisher + + + + + + + + + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + + + + + + + + + + true + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + /resource + http://localhost:9764/resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + + + + + + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + GET,POST,PUT,DELETE,OPTIONS + + + + diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/tokenTest/log4j.properties b/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/tokenTest/log4j.properties new file mode 100755 index 0000000000..76c7eb5251 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/tokenTest/log4j.properties @@ -0,0 +1,180 @@ +# +# 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.category.org.apache.synapse=INFO +log4j.category.org.apache.synapse.transport=INFO +log4j.category.org.apache.axis2=INFO +log4j.category.org.apache.axis2.transport=INFO +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 +#log4j.logger.org.wso2.carbon.apimgt.gateway.handlers=DEBUG +#log4j.logger.org.wso2.carbon.apimgt.gateway.handlers.throttling=DEBUG +log4j.logger.org.wso2.carbon.apimgt=DEBUG + +# 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 + +# 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 + +# The console appender is used to display general information at console +log4j.appender.CARBON_CONSOLE=org.wso2.carbon.logging.appenders.CarbonConsoleAppender +log4j.appender.CARBON_CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CARBON_CONSOLE.layout.ConversionPattern=[%d{ISO8601}] %5p - %c{1} %m%n + +# 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-apigw-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-apigw-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.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.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-apigw-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.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 + +# LOGEVENT is set to be a LogEventAppender using a PatternLayout to send logs to LOGEVENT +log4j.appender.LOGEVENT=org.wso2.carbon.logging.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 + + +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 + +# LOGEVENT is set to be a LogEventAppender using a PatternLayout to send logs to LOGEVENT +log4j.appender.LOGEVENT=org.wso2.carbon.logging.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,%H,%I,%Stacktrace +log4j.appender.LOGEVENT.userName=admin +log4j.appender.LOGEVENT.password=admin + +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 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 + diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/usagemonitortest/api-manager.xml b/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/usagemonitortest/api-manager.xml new file mode 100755 index 0000000000..406151fa75 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/usagemonitortest/api-manager.xml @@ -0,0 +1,537 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + admin + + admin + + + + + + X-JWT-Assertion + + + org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever + + + http://wso2.org/claims + + + SHA256withRSA + + + true + + + true + + + + + + + + + + + + Production and Sandbox + + 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} + + + + + true + + + referer + + + + + true + + + + + + true + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + 7612 + + + tcp://localhost:7612/ + + + admin + + + admin + + + + + + + + false + + + UA-XXXXXXXX-X + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + + admin + + + admin + + true + + + + true + + + + WSClient + 10397 + 10000 + 10397 + + true + + + + + + + + /oauth2/token + + + false + + + + + + + true + + + + + + true + + + subscriber + + + true + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/store + + true + + true + + + true + + + true + + + + + + + + + false + https://${carbon.local.ip}:${mgt.transport.https.port}/publisher + + + + + + + + + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + http://localhost:9765/services/ApplicationRegistrationWorkFlowProcess/ + admin + admin + https://localhost:8243/services/WorkflowCallbackService + + + + + + + + + + + + + true + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + /resource + http://localhost:9764/resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + Store1 + http://localhost:9763/store + user1@tenantdomain1.com + test123 + + + + + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + GET,POST,PUT,DELETE,OPTIONS + + + + diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/usagemonitortest/master-datasources.xml b/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/usagemonitortest/master-datasources.xml new file mode 100755 index 0000000000..8cc23ee0b4 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/configFiles/usagemonitortest/master-datasources.xml @@ -0,0 +1,109 @@ + + + + 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 + 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 + + + + + + WSO2AM_STATS_DB + The datasource used for getting statistics to API Manager + + jdbc/WSO2AM_STATS_DB + + + + jdbc:h2:;AUTO_SERVER=TRUE + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/jaggery/testPublisher.jag b/modules/integration/tests/src/test/resources/artifacts/AM/jaggery/testPublisher.jag new file mode 100644 index 0000000000..bbd5eec078 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/jaggery/testPublisher.jag @@ -0,0 +1,96 @@ +<% +//Order of these operations are important as we fetch results based on order. +//If you add new test add them to bottom of this file and update validate response method +//available in host object test class. +var publisher = require('apipublisher'); +var publisherHostObj = new publisher.APIProvider("admin"); +print("=="); +print(publisherHostObj.getExternalAPIStores()); +print("=="); +print(publisherHostObj.validateRoles('admin', 'admin')); +print("=="); +print(publisherHostObj.isURLValid("https","https://www.google.com")); +print("=="); +print(publisherHostObj.getAPIsByProvider("admin")); +print("=="); +print(publisherHostObj.getSubscribedAPIs("admin")); +print("=="); +print(publisherHostObj.getAPI("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.getTierPermissions()); +print("=="); +print(publisherHostObj.getTiers()); +print("=="); +print(publisherHostObj.getAllAPIs()); +print("=="); +print(publisherHostObj.getAPIsByProvider("admin")); +print("=="); +print(publisherHostObj.getSubscribersOfAPI("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.isContextExist("HostObjectTestAPI","HostObjectTestAPI")); +print("=="); +print(publisherHostObj.searchAPIs("admin","name:HostObjectTestAPI")); +print("=="); +print(publisherHostObj.hasCreatePermission()); +print("=="); +print(publisherHostObj.hasManageTierPermission()); +print("=="); +print(publisherHostObj.hasUserPermissions("admin")); +print("=="); +print(publisherHostObj.hasPublishPermission("admin")); +print("=="); +print(publisherHostObj.getAuthServerURL()); +print("=="); +print(publisherHostObj.getCustomInSequences()); +print("=="); +print(publisherHostObj.getCustomOutSequences()); +print("=="); +print(publisherHostObj.getHTTPsURL()); +print("=="); +print(publisherHostObj.isSynapseGateway()); +print("=="); +print(publisherHostObj.loadRegistryOfTenant("carbon.super")); +print("=="); +print(publisherHostObj.updateDocumentation("admin","HostObjectTestAPI","1.0.0","Doc-Name", "How To", "summary","In-line")); +print("=="); +print(publisherHostObj.addInlineContent("admin","HostObjectTestAPI","1.0.0","help","this is helpe")); +print("=="); +print(publisherHostObj.getInlineContent("admin","HostObjectTestAPI","1.0.0","help")); +print("=="); +print(publisherHostObj.getAllDocumentation("admin@carbon.super","HostObjectTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.searchAccessTokens("*:*")); +print("=="); +print(publisherHostObj.getSubscriberCountByAPIs("admin@carbon.super")); +print("=="); +print(publisherHostObj.getSubscriberCountByAPIVersions("admin@carbon.super")); +print("=="); +print(publisherHostObj.getExternalAPIStores()); +print("=="); +var apiData = {}; +apiData["provider"] = "admin"; +apiData["name"] = "HostObjectTestAPI"; +apiData["version"] = "1.0.0"; +apiData["apiName"] = "HostObjectTestAPI"; +print(publisherHostObj.isAPIOlderVersionExist(apiData)); +print("=="); +print(publisherHostObj.updateSubscriptionStatus(apiData,"BLOCKED","1")); +print("=="); + +var tierData = {}; +tierData["tierName"] = "Gold"; +tierData["permissiontype"] = "Deny"; +tierData["roles"] = "admin"; +print(publisherHostObj.updateTierPermissions(tierData)); +print("=="); +//print(publisherHostObj.updateExternalAPIStores(apiData)); +//print(publisherHostObj.createNewAPIVersion("admin","HostObjectTestAPI","1.0.0","1.0.1")); +//print(publisherHostObj.searchAccessTokens("admin")); +//print(publisherHostObj.getSubscriberCountByAPIVersions()); +var apiData1 = {}; +apiData1["provider"] = "admin"; +apiData1["name"] = "HostObjectTestAPI"; +apiData1["version"] = "1.0.0"; +apiData1["apiName"] = "HostObjectTestAPI"; +//print(publisherHostObj.updateExternalAPIStores(apiData1)); +%> \ No newline at end of file diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/jaggery/testStore.jag b/modules/integration/tests/src/test/resources/artifacts/AM/jaggery/testStore.jag new file mode 100644 index 0000000000..3c307b619e --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/jaggery/testStore.jag @@ -0,0 +1,93 @@ +<% +<% +//Order of these operations are important as we fetch results based on order + //If you add new test add them to bottom of this file and update validate response method + //available in host object test class +store = require('apistore'); +var storeHostObj = new store.APIStore("admin"); +print("=="); +print(storeHostObj.isBillingEnabled()); +print("=="); +print(storeHostObj.getHTTPsURL("localhost")); +print("=="); +print(storeHostObj.getAuthServerURL()); +print("=="); +print(storeHostObj.getHTTPURL("localhost")); +print("=="); +print(storeHostObj.getDeniedTiers()); +print("=="); +print(storeHostObj.getActiveTenantDomains()); +print("=="); +print(storeHostObj.isSelfSignupEnabled()); +print("=="); +print(storeHostObj.getUserFields()); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("HostObjectTestAPI","carbon.super","0","10")); +print("=="); +print(storeHostObj.searchPaginatedAPIsByType("name:*","carbon.super","0","10")); +print("=="); +print(storeHostObj.searchAPIbyType("name:*","carbon.super")); +print("=="); +print(storeHostObj.searchAPIbyType("HostObjectTestAPI","carbon.super")); +print("=="); +print(storeHostObj.getPaginatedAPIsWithTag("youtube","0","10")); +print("=="); +print(storeHostObj.getPublishedAPIsByProvider("admin@carbon.super","admin")); +print("=="); +print(storeHostObj.getAllSubscriptions("admin@carbon.super")); +print("=="); +print(storeHostObj.rateAPI("admin","HostObjectTestAPI","1.0.0","3")); +print("=="); +print(storeHostObj.removeAPIRating("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(storeHostObj.getAllPaginatedPublishedAPIs("carbon.super","0","10")); +print("=="); +print(storeHostObj.getAPIsWithTag("youtube")); +print("=="); +print(storeHostObj.getAllPublishedAPIs("carbon.super")); +print("=="); +print(storeHostObj.getComments("admin","HostObjectTestAPI","1.0.0")); +print("=="); +print(storeHostObj.isUserExists("admin")); +print("=="); +print(storeHostObj.getAPI("admin","HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.isSubscribed("admin","HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.getSubscriptions("admin","HostObjectTestAPI","1.0.0","admin")); +print("=="); +print(storeHostObj.getSubscribedAPIs("3")); +print("=="); +print(storeHostObj.hasUserPermissions("admin")); +print("=="); +print(storeHostObj.getTiers("admin")); +print("=="); +print(storeHostObj.getAPIUsageforSubscriber("admin")); +print("=="); +print(storeHostObj.getDeniedTiers("admin")); +print("=="); +print(storeHostObj.getRecentlyAddedAPIs("5","carbon.super")); +print("=="); +print(storeHostObj.getTopRatedAPIs("5")); +print("=="); +print(storeHostObj.isBillingEnabled()); +print("=="); +print(storeHostObj.hasSubscribePermission()); +print("=="); +print(storeHostObj.isEnableEmailUsername()); +print("=="); +print(storeHostObj.updateApplicationTier("DefaultApplication","gold","admin")); +print("=="); +print(storeHostObj.updateApplication("DefaultApplicationTest","DefaultApplication","admin","gold","test-url","updated-application")); +print("=="); +print(storeHostObj.validateWFPermission("Basic YWRtaW46YWRtaW4=")); +print("=="); +print(storeHostObj.getSwaggerDiscoveryUrl("HostObjectTestAPI","1.0.0","admin")); +print("=="); +//print(storeHostObj.removeSubscriber("admin","HostObjectTestAPI","1.0.0","DefaultApplication","1")); +//print(storeHostObj.removeSubscription("admin","HostObjectTestAPI","1.0.0","DefaultApplication","1")); +//print(storeHostObj.rateAPI("admin","HostObjectTestAPI","1.0.0","3")); +//print("=="); +//print(storeHostObj.getTopRatedAPIs("3")); +%> +%> \ No newline at end of file diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/jaggery/testUsageWithBAM.jag b/modules/integration/tests/src/test/resources/artifacts/AM/jaggery/testUsageWithBAM.jag new file mode 100644 index 0000000000..e43384478b --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/jaggery/testUsageWithBAM.jag @@ -0,0 +1,36 @@ +<% +//Order of these operations are important as we fetch results based on order. +//If you add new test add them to bottom of this file and update validate response method +//available in host object test class. +var publisher = require('apipublisher'); +var publisherHostObj = new publisher.APIProvider("admin"); +print("=="); +print(publisherHostObj.getAPIUsageforSubscriber("admin")); +print("=="); +print(publisherHostObj.getAPIFaultyAnalyzeByTime("admin")); +print("=="); +var start=new Date(); +start.setFullYear(2014,0,14); +var end = new Date(); +end.setFullYear(2015,0,14); +print(publisherHostObj.getAPIResponseFaultCount("admin",start,end)); +print("=="); +print(publisherHostObj.getAPIUsageByResourcePath("admin",start,end)); +print("=="); +print(publisherHostObj.getAPIUsageByUser("admin",start,end)); +print("=="); +print(publisherHostObj.getAllAPIUsageByProvider("admin")); +print("=="); +print(publisherHostObj.getFirstAccessTime("admin")); +print("=="); +print(publisherHostObj.getProviderAPIServiceTime("admin",start,end)); +print("=="); +print(publisherHostObj.getProviderAPIUsage("admin","UsageTestAPI")); +print("=="); +print(publisherHostObj.getProviderAPIVersionUsage("admin","UsageTestAPI")); +print("=="); +print(publisherHostObj.getProviderAPIVersionUserUsage("admin","UsageTestAPI","1.0.0")); +print("=="); +print(publisherHostObj.getProviderAPIVersionUserLastAccess("admin",start,end)); +print("=="); +%> \ No newline at end of file diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/scripts/API_Manager_Login_Test.jmx b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/API_Manager_Login_Test.jmx new file mode 100644 index 0000000000..6e46aeeaee --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/API_Manager_Login_Test.jmx @@ -0,0 +1,356 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + Youtube + = + + + context + /youtube + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + Tester_Acc2 + = + + + publisherName + admin + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://localhost:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + 200 + + Assertion.response_code + false + 2 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/aggregate_report.jtl + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + + + + diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest.jmx b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest.jmx new file mode 100644 index 0000000000..0852fe5dd7 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest.jmx @@ -0,0 +1,2902 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + GOOG_Stock_API + = + + + context + /GStock + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + userPrefix + tenant + = + + + resourceMethods + POST + = + + + authTypes + Application & Application User + = + + + throttlingTiers + Unlimited + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_number + # + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <ser:getTenant> + <!--Optional:--> + <ser:tenantDomain>domain${tenant_number}.com</ser:tenantDomain> + </ser:getTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:getTenant + true + false + + + + undefined + tenant_exists + //*[local-name()='active']/text() + false + false + true + tenant_exists + + + + false + true + true + false + + + + + ${tenant_exists}==false + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org" xmlns:xsd="http://beans.common.stratos.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <ser:addTenant> + <!--Optional:--> + <ser:tenantInfoBean> + <!--Optional:--> + <xsd:active>1</xsd:active> + <!--Optional:--> + <xsd:admin>${userPrefix}${tenant_number}</xsd:admin> + <!--Optional:--> + <xsd:adminPassword>1qaz2wsx@</xsd:adminPassword> + <!--Optional:--> + <xsd:createdDate>2013-02-22T08:22:54</xsd:createdDate> + <!--Optional:--> + <xsd:email>ruwany@wso2.com</xsd:email> + <!--Optional:--> + <xsd:firstname>User1</xsd:firstname> + <!--Optional:--> + <xsd:lastname>LastName1</xsd:lastname> + <!--Optional:--> + <xsd:tenantDomain>domain${tenant_number}.com</xsd:tenantDomain> + <!--Optional:--> + <xsd:tenantId>0</xsd:tenantId> + <!--Optional:--> + <xsd:usagePlan>Demo</xsd:usagePlan> + </ser:tenantInfoBean> + </ser:addTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:addTenant + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + 202 + + Assertion.response_code + false + 1 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + + 1363957740000 + 1363957740000 + false + + + + + + + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_counter + # + false + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>${userPrefix}${tenant_counter}@domain${tenant_counter}.com</aut:username> + <!--Optional:--> + <aut:password>1qaz2wsx@</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <xsd:getAllRolesNames> + <!--Optional:--> + <xsd:filter>*</xsd:filter> + <!--Optional:--> + <xsd:limit>100</xsd:limit> + </xsd:getAllRolesNames> + </soapenv:Body> +</soapenv:Envelope> + + urn:getAllRolesNames + true + false + + + + undefined + role_exists + //*[local-name()='itemName']/text()='subscriber_role' + false + false + true + + + + false + true + true + false + + + + + ${role_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addRole> + <!--Optional:--> + <mgt:roleName>subscriber_role</mgt:roleName> + <mgt:permissions>/permission/admin/login</mgt:permissions> + <mgt:permissions>/permission/admin/manage/api/subscribe</mgt:permissions> + <mgt:isSharedRole>false</mgt:isSharedRole> + </mgt:addRole> + </soapenv:Body> +</soapenv:Envelope> + + urn:addRole + true + false + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + user_ref + # + false + + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:listUsers> + <!--Optional:--> + <mgt:filter>${userPrefix}${tenant_counter}_user${user_ref}</mgt:filter> + <mgt:limit>10</mgt:limit> + </mgt:listUsers> + </soapenv:Body> +</soapenv:Envelope> + + urn:listUsers + true + false + + + + false + user_exists + //*[local-name()='return']/text()='${userPrefix}${tenant_counter}_user${user_ref}' + false + false + true + + + + false + true + true + false + + + + + ${user_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd" xmlns:xsd="http://common.mgt.user.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addUser> + <!--Optional:--> + <mgt:userName>${userPrefix}${tenant_counter}_user${user_ref}</mgt:userName> + <!--Optional:--> + <mgt:password>1qaz2wsx@</mgt:password> + <mgt:roles>subscriber_role</mgt:roles> + </mgt:addUser> + </soapenv:Body> +</soapenv:Envelope> + + urn:addUser + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy_report.jtl + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + String currentDir = System.getProperty("user.dir"); +FileOutputStream f = new FileOutputStream(currentDir + "/results.csv"); + + + false + + + + + + false + rfc2109 + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}@domain${input_value}.com + = + true + username + + + false + ${publisherPass} + = + true + password + + + false + null + = + true + tenant + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${numberOfAPIs} + + + + 1 + ${numberOfAPIs} + 1 + api_id + # + false + + + + + + + false + addAPI + = + true + action + + + false + ${apinm}${api_id} + = + true + name + + + false + ${context}${api_id} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + /* + = + true + uriTemplate-0 + + + false + ${resourceMethods} + = + true + resourceMethod-0 + + + false + ${authTypes} + = + true + resourceMethodAuthType-0 + + + false + ${throttlingTiers} + = + true + resourceMethodThrottlingTier-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + http + = + true + http_checked + + + false + https + = + true + https_checked + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm}${api_id} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + false + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${numberOfAPIs} + + + + 1 + ${numberOfAPIs} + 1 + api_id + # + false + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm}${api_id} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + Unlimited + = + true + tier + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com&password=1qaz2wsx@&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + +String tenant_count = vars.get("input_value"); +String user_count = vars.get("subsCount"); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + +String currentDir = System.getProperty("user.dir"); + +vars.put("current_directory" , currentDir); + +String context = vars.get("context"); +String apiID = vars.get("api_id"); + +f = new FileOutputStream(currentDir + "/results.csv", true); + +p = new PrintStream(f); + +this.interpreter.setOut(p); + +print("domain"+ tenant_count+".com" + "@@@" + accessToken +"@@@" + context+apiID); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + /t/domain${input_value}.com${context}${api_id}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getAllPublishedAPIs + = + true + action + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/api/listing/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + true + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getRecentlyAddedAPIs + = + true + action + + + false + 2000 + = + true + limit + + + false + domain1.com + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + store/site/blocks/api/recently-added/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getAllTags + = + true + action + + + + ${storeIP} + ${storePort} + + + + + store/site/blocks/tag/tag-cloud/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 10 + 1 + 1365001797000 + 1365001797000 + false + + + + + + + + import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.LineNumberReader; + +String currentDir = System.getProperty("user.dir"); + +LineNumberReader lnr = new LineNumberReader(new FileReader(new File(currentDir + "/results.csv"))); +lnr.skip(Long.MAX_VALUE); + +int min = 1; +int max = lnr.getLineNumber(); + +Random r = new Random(); +int i1 = r.nextInt(max - min + 1) + min; + +vars.put("random_value",""+i1); + +String lineConcerened = ""; + +BufferedReader br = new BufferedReader(new FileReader(new File(currentDir + "/results.csv"))); + +String strLine =""; + +for(int i=0; i<max; i++){ + strLine = br.readLine(); + if(i==i1-1){ + System.out.println(strLine); + lineConcerened = strLine; + } +} + +String[] splitVals = lineConcerened.split("@@@"); +String userName = splitVals[0]; +String token = splitVals[1]; +String contextAndAPIId = splitVals[2]; + +vars.put("line_count",""+i1); +vars.put("domain",userName); +vars.put("token",token); +vars.put("contextAndAPIId",contextAndAPIId); + + + false + + + + false + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + /t/${domain}${contextAndAPIId}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${token} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + false + true + true + false + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/aggregate_report.jtl + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + + + + diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest_new_tenant.jmx b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest_new_tenant.jmx new file mode 100644 index 0000000000..eb187dda28 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/API_Manager_functionality_and_loadTest_new_tenant.jmx @@ -0,0 +1,2671 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + GOOG_Stock_API_New + = + + + context + /GStocknew + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + userPrefix + tenant + = + + + resourceMethods + POST + = + + + authTypes + Application & Application User + = + + + throttlingTiers + Unlimited + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_number + # + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <ser:getTenant> + <!--Optional:--> + <ser:tenantDomain>domain${tenant_number}.com</ser:tenantDomain> + </ser:getTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:getTenant + true + false + + + + undefined + tenant_exists + //*[local-name()='active']/text() + false + false + true + tenant_exists + + + + false + true + true + false + + + + + ${tenant_exists}==false + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org" xmlns:xsd="http://beans.common.stratos.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <ser:addTenant> + <!--Optional:--> + <ser:tenantInfoBean> + <!--Optional:--> + <xsd:active>1</xsd:active> + <!--Optional:--> + <xsd:admin>${userPrefix}${tenant_number}</xsd:admin> + <!--Optional:--> + <xsd:adminPassword>1qaz2wsx@</xsd:adminPassword> + <!--Optional:--> + <xsd:createdDate>2013-02-22T08:22:54</xsd:createdDate> + <!--Optional:--> + <xsd:email>ruwany@wso2.com</xsd:email> + <!--Optional:--> + <xsd:firstname>User1</xsd:firstname> + <!--Optional:--> + <xsd:lastname>LastName1</xsd:lastname> + <!--Optional:--> + <xsd:tenantDomain>domain${tenant_number}.com</xsd:tenantDomain> + <!--Optional:--> + <xsd:tenantId>0</xsd:tenantId> + <!--Optional:--> + <xsd:usagePlan>Demo</xsd:usagePlan> + </ser:tenantInfoBean> + </ser:addTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:addTenant + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + 202 + + Assertion.response_code + false + 1 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + + 1363957740000 + 1363957740000 + false + + + + + + + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_counter + # + false + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>${userPrefix}${tenant_counter}@domain${tenant_counter}.com</aut:username> + <!--Optional:--> + <aut:password>1qaz2wsx@</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <xsd:getAllRolesNames> + <!--Optional:--> + <xsd:filter>*</xsd:filter> + <!--Optional:--> + <xsd:limit>100</xsd:limit> + </xsd:getAllRolesNames> + </soapenv:Body> +</soapenv:Envelope> + + urn:getAllRolesNames + true + false + + + + undefined + role_exists + //*[local-name()='itemName']/text()='subscriber_role_new' + false + false + true + + + + false + true + true + false + + + + + ${role_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addRole> + <!--Optional:--> + <mgt:roleName>subscriber_role_new</mgt:roleName> + <mgt:permissions>/permission/admin/login</mgt:permissions> + <mgt:permissions>/permission/admin/manage/api/subscribe</mgt:permissions> + <mgt:isSharedRole>false</mgt:isSharedRole> + </mgt:addRole> + </soapenv:Body> +</soapenv:Envelope> + + urn:addRole + true + false + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + user_ref + # + false + + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:listUsers> + <!--Optional:--> + <mgt:filter>${userPrefix}${tenant_counter}_user${user_ref}</mgt:filter> + <mgt:limit>10</mgt:limit> + </mgt:listUsers> + </soapenv:Body> +</soapenv:Envelope> + + urn:listUsers + true + false + + + + false + user_exists + //*[local-name()='return']/text()='${userPrefix}${tenant_counter}_user${user_ref}' + false + false + true + + + + false + true + true + false + + + + + ${user_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd" xmlns:xsd="http://common.mgt.user.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addUser> + <!--Optional:--> + <mgt:userName>${userPrefix}${tenant_counter}_user${user_ref}</mgt:userName> + <!--Optional:--> + <mgt:password>1qaz2wsx@</mgt:password> + <mgt:roles>subscriber_role_new</mgt:roles> + </mgt:addUser> + </soapenv:Body> +</soapenv:Envelope> + + urn:addUser + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy_report.jtl + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + String currentDir = System.getProperty("user.dir"); +FileOutputStream f = new FileOutputStream(currentDir + "/results.csv"); + + + false + + + + + + false + rfc2109 + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}@domain${input_value}.com + = + true + username + + + false + ${publisherPass} + = + true + password + + + false + null + = + true + tenant + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${numberOfAPIs} + + + + 1 + ${numberOfAPIs} + 1 + api_id + # + false + + + + + + + false + addAPI + = + true + action + + + false + ${apinm}${api_id} + = + true + name + + + false + ${context}${api_id} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + /* + = + true + uriTemplate-0 + + + false + ${resourceMethods} + = + true + resourceMethod-0 + + + false + ${authTypes} + = + true + resourceMethodAuthType-0 + + + false + ${throttlingTiers} + = + true + resourceMethodThrottlingTier-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + http + = + true + http_checked + + + false + https + = + true + https_checked + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm}${api_id} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + false + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${numberOfAPIs} + + + + 1 + ${numberOfAPIs} + 1 + api_id + # + false + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm}${api_id} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + Unlimited + = + true + tier + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${userPrefix}${input_value}-AT-domain${input_value}.com + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com&password=1qaz2wsx@&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + +String tenant_count = vars.get("input_value"); +String user_count = vars.get("subsCount"); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + +String currentDir = System.getProperty("user.dir"); + +vars.put("current_directory" , currentDir); + +String context = vars.get("context"); +String apiID = vars.get("api_id"); + +f = new FileOutputStream(currentDir + "/results.csv", true); + +p = new PrintStream(f); + +this.interpreter.setOut(p); + +print("domain"+ tenant_count+".com" + "@@@" + accessToken +"@@@" + context+apiID); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + /t/domain${input_value}.com${context}${api_id}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getAllPublishedAPIs + = + true + action + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/api/listing/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + true + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getRecentlyAddedAPIs + = + true + action + + + false + 2000 + = + true + limit + + + false + domain1.com + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + store/site/blocks/api/recently-added/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + 2 + 1342532280000 + 1342532280000 + false + + + + + + true + 1 + + + + 1 + ${numberOfTenants} + 1 + input_value + # + false + + + + + true + rfc2109 + + + + + + true + 1 + + + + 1 + ${numberOfUsers} + 1 + subsCount + # + true + + + + + + + false + login + = + true + action + + + false + ${userPrefix}${input_value}_user${subsCount}@domain${input_value}.com + = + true + username + + + false + 1qaz2wsx@ + = + true + password + + + false + null + = + true + tenant + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getAllTags + = + true + action + + + + ${storeIP} + ${storePort} + + + + + store/site/blocks/tag/tag-cloud/ajax/list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +String appid = resp.substring(def+6, resp.indexOf("," )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + false + + + String outPath = (String)vars.get("scriptFolder")+"location.txt"; +String location = (String)vars.get("reportFolder"); +String pluginLocation = (String)vars.get("jmeterHome"); +FileWriter writer = new FileWriter(outPath); + BufferedWriter bufferedWriter = new BufferedWriter(writer); + bufferedWriter.write(location); + bufferedWriter.newLine(); + bufferedWriter.write(pluginLocation); + bufferedWriter.newLine(); + bufferedWriter.close(); + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + true + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + true + false + false + false + false + 0 + true + + + + true + + + + + continue + + false + 1 + + 10 + 1 + 1365001797000 + 1365001797000 + false + + + + + + + + import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.LineNumberReader; + +String currentDir = System.getProperty("user.dir"); + +LineNumberReader lnr = new LineNumberReader(new FileReader(new File(currentDir + "/results.csv"))); +lnr.skip(Long.MAX_VALUE); + +int min = 1; +int max = lnr.getLineNumber(); + +Random r = new Random(); +int i1 = r.nextInt(max - min + 1) + min; + +vars.put("random_value",""+i1); + +String lineConcerened = ""; + +BufferedReader br = new BufferedReader(new FileReader(new File(currentDir + "/results.csv"))); + +String strLine =""; + +for(int i=0; i<max; i++){ + strLine = br.readLine(); + if(i==i1-1){ + System.out.println(strLine); + lineConcerened = strLine; + } +} + +String[] splitVals = lineConcerened.split("@@@"); +String userName = splitVals[0]; +String token = splitVals[1]; +String contextAndAPIId = splitVals[2]; + +vars.put("line_count",""+i1); +vars.put("domain",userName); +vars.put("token",token); +vars.put("contextAndAPIId",contextAndAPIId); + + + false + + + + false + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + /t/${domain}${contextAndAPIId}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${token} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + false + true + true + false + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/scripts/DomainRestrictionTest.jmx b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/DomainRestrictionTest.jmx new file mode 100644 index 0000000000..55821fa75b --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/DomainRestrictionTest.jmx @@ -0,0 +1,1202 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + basic_functions_api_domain + = + + + context + /basic_functions_api_domain + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + super_tenant_user + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + https://lh6.ggpht.com/RNc8dD2hXG_rWGzlj09ZwAe1sXVvLWkeYT3ePx7zePCy4ZVV2XMGIxAzup4cKM85NFtL=w124 + = + true + apiThumb + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + POST + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Unlimited, Unlimited, Unlimited, Unlimited, Unlimited + = + true + resourceMethodThrottlingTier-0 + + + false + http + = + true + http_checked + + + false + https + = + true + https_checked + + + false + Application User + = + true + resourceMethodAuthType-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${noOfSubscribers} + + + + 1 + 10000 + 1 + subsCount + # + false + + + + + + + false + addUser + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + false + ${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}@test.com|| + = + true + allFieldsValues + + + false + + = + true + + + false + + = + true + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/sign-up/ajax/user-add.jag + POST + true + false + true + false + Java + false + + + + + 50 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//int eq = resp.indexOf("=", def - 8); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println("APP ID : " + appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + true + true + true + false + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + true + true + true + false + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + wso2.org + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + refreshToken + = + true + action + + + false + application + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${token} + = + true + oldAccessToken + + + false + ${consumerKey} + = + true + clientId + + + false + ${consumerSecret} + = + true + clientSecret + + + false + 5000 + = + true + validityTime + + + false + wso2.org + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${subsPrefix}_${subsCount}&password=subscriber@123&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + referer + wso2.org + + + + + + + 200 + + Assertion.response_data + false + 6 + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + + diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/scripts/basic_functionality_test.jmx b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/basic_functionality_test.jmx new file mode 100644 index 0000000000..dd959572bf --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/basic_functionality_test.jmx @@ -0,0 +1,1198 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + basic_functions_api + = + + + context + /basic_functions_api + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + super_tenant_user + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + https://lh6.ggpht.com/RNc8dD2hXG_rWGzlj09ZwAe1sXVvLWkeYT3ePx7zePCy4ZVV2XMGIxAzup4cKM85NFtL=w124 + = + true + apiThumb + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + POST + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Unlimited, Unlimited, Unlimited, Unlimited, Unlimited + = + true + resourceMethodThrottlingTier-0 + + + false + http + = + true + http_checked + + + false + https + = + true + https_checked + + + false + Application User + = + true + resourceMethodAuthType-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${noOfSubscribers} + + + + 1 + 10000 + 1 + subsCount + # + false + + + + + + + false + addUser + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + false + ${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}@test.com|| + = + true + allFieldsValues + + + false + + = + true + + + false + + = + true + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/sign-up/ajax/user-add.jag + POST + true + false + true + false + Java + false + + + + + 50 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//int eq = resp.indexOf("=", def - 8); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println("APP ID : " + appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + true + true + true + false + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + true + true + true + false + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + refreshToken + = + true + action + + + false + application + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${token} + = + true + oldAccessToken + + + false + ${consumerKey} + = + true + clientId + + + false + ${consumerSecret} + = + true + clientSecret + + + false + 5000 + = + true + validityTime + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${subsPrefix}_${subsCount}&password=subscriber@123&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + No data found + + Assertion.response_data + false + 6 + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + + diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/scripts/content_type_check_for_DELETE_script.jmx b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/content_type_check_for_DELETE_script.jmx new file mode 100644 index 0000000000..3b6fa90f65 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/content_type_check_for_DELETE_script.jmx @@ -0,0 +1,491 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + testContentTypeHeaderAPI + = + + + context + /testContentTypeHeaderAPI + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + + + + + false + rfc2109 + + + + + + + false + login + = + true + action + + + false + admin + = + true + username + + + false + admin + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + +System.out.println("####################################################################### Access Token Response: " + jsonResponse); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=admin&password=admin&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + false + ThisParamIsRequiredForTest_DELETE + = + true + param + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version}/ + DELETE + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/scripts/content_type_check_for_GET_script.jmx b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/content_type_check_for_GET_script.jmx new file mode 100644 index 0000000000..6385a2ed19 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/content_type_check_for_GET_script.jmx @@ -0,0 +1,498 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + testContentTypeHeaderAPI + = + + + context + /testContentTypeHeaderAPI + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + + + + + false + rfc2109 + + + + + + + false + login + = + true + action + + + false + admin + = + true + username + + + false + admin + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + false + 5600 + = + true + validityTime + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + +System.out.println("####################################################################### Access Token Response: " + jsonResponse); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=admin&password=admin&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + false + ThisParamIsRequiredForTest_GET + = + true + param + + + + ${gatewayServer} + ${gatewayPort} + + + + + ${context}/${version}/ + GET + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/scripts/content_type_check_publish_and_subscribe_script.jmx b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/content_type_check_publish_and_subscribe_script.jmx new file mode 100644 index 0000000000..f194dc87e4 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/content_type_check_publish_and_subscribe_script.jmx @@ -0,0 +1,665 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + testContentTypeHeaderAPI + = + + + context + /testContentTypeHeaderAPI + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + + + + + false + rfc2109 + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + 127.0.0.1:6789 + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + DELETE,GET + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + Application User,Application User + = + true + resourceMethodAuthType-0 + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Unlimited, Unlimited, Unlimited, Unlimited, Unlimited + = + true + resourceMethodThrottlingTier-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + admin + = + true + username + + + false + admin + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + admin + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//String appid = resp.substring(def+6, resp.indexOf("," )); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println("AppId: " + appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + 1.0.0 + = + true + version + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/scripts/tenant_create.jmx b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/tenant_create.jmx new file mode 100644 index 0000000000..976581f9ad --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/tenant_create.jmx @@ -0,0 +1,634 @@ + + + + + + false + true + + + + + + + + + + numberOfTenants + 1 + No of tenants + = + + + numberOfAPIs + 1 + = + + + numberOfUsers + 1 + = + + + search_arg_gateway + 10 + = + + + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + GOOG_Stock_API_New + = + + + context + /GStocknew + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + publisherPass + 1qaz2wsx@ + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + noOfSubscribers + 1 + = + + + userPrefix + user + = + + + resourceMethods + POST + = + + + authTypes + Application & Application User + = + + + throttlingTiers + Unlimited + = + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>admin</aut:username> + <!--Optional:--> + <aut:password>admin</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_number + # + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <ser:getTenant> + <!--Optional:--> + <ser:tenantDomain>tenantdomain${tenant_number}.com</ser:tenantDomain> + </ser:getTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:getTenant + true + false + + + + undefined + tenant_exists + //*[local-name()='active']/text() + false + false + true + tenant_exists + + + + false + true + true + false + + + + + ${tenant_exists}==false + false + + + + + + + https://${server}:9443/services/TenantMgtAdminService.TenantMgtAdminServiceHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.mgt.tenant.carbon.wso2.org" xmlns:xsd="http://beans.common.stratos.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <ser:addTenant> + <!--Optional:--> + <ser:tenantInfoBean> + <!--Optional:--> + <xsd:active>1</xsd:active> + <!--Optional:--> + <xsd:admin>${userPrefix}${tenant_number}</xsd:admin> + <!--Optional:--> + <xsd:adminPassword>test123</xsd:adminPassword> + <!--Optional:--> + <xsd:createdDate>2013-02-22T08:22:54</xsd:createdDate> + <!--Optional:--> + <xsd:email>ruwany@wso2.com</xsd:email> + <!--Optional:--> + <xsd:firstname>User1</xsd:firstname> + <!--Optional:--> + <xsd:lastname>LastName1</xsd:lastname> + <!--Optional:--> + <xsd:tenantDomain>tenantdomain${tenant_number}.com</xsd:tenantDomain> + <!--Optional:--> + <xsd:tenantId>0</xsd:tenantId> + <!--Optional:--> + <xsd:usagePlan>Demo</xsd:usagePlan> + </ser:tenantInfoBean> + </ser:addTenant> + </soapenv:Body> +</soapenv:Envelope> + + urn:addTenant + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + 202 + + Assertion.response_code + false + 1 + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy.jtl + + + + + continue + + false + 1 + + 1 + + 1363957740000 + 1363957740000 + false + + + + + + + false + + + + true + ${numberOfTenants} + + + + 1 + ${numberOfTenants} + 1 + tenant_counter + # + false + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:login> + <!--Optional:--> + <aut:username>${userPrefix}${tenant_counter}@tenantdomain${tenant_counter}.com</aut:username> + <!--Optional:--> + <aut:password>test123</aut:password> + <!--Optional:--> + <aut:remoteAddress>127.0.0.1</aut:remoteAddress> + </aut:login> + </soapenv:Body> +</soapenv:Envelope> + + urn:login + true + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <xsd:getAllRolesNames> + <!--Optional:--> + <xsd:filter>*</xsd:filter> + <!--Optional:--> + <xsd:limit>100</xsd:limit> + </xsd:getAllRolesNames> + </soapenv:Body> +</soapenv:Envelope> + + urn:getAllRolesNames + true + false + + + + undefined + role_exists + //*[local-name()='itemName']/text()='subscriber_role_new' + false + false + true + + + + false + true + true + false + + + + + ${role_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addRole> + <!--Optional:--> + <mgt:roleName>subscriber_role_new</mgt:roleName> + <mgt:permissions>/permission/admin/login</mgt:permissions> + <mgt:permissions>/permission/admin/manage/api/subscribe</mgt:permissions> + <mgt:isSharedRole>false</mgt:isSharedRole> + </mgt:addRole> + </soapenv:Body> +</soapenv:Envelope> + + urn:addRole + true + false + + + + + true + ${numberOfUsers} + + + + 1 + ${numberOfUsers} + 1 + user_ref + # + false + + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:listUsers> + <!--Optional:--> + <mgt:filter>${userPrefix}${tenant_counter}_user${user_ref}</mgt:filter> + <mgt:limit>10</mgt:limit> + </mgt:listUsers> + </soapenv:Body> +</soapenv:Envelope> + + urn:listUsers + true + false + + + + false + user_exists + //*[local-name()='return']/text()='${userPrefix}${tenant_counter}_user${user_ref}' + false + false + true + + + + false + true + true + false + + + + + ${user_exists}==false + false + + + + + + + https://${server}:9443/services/UserAdmin.UserAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mgt="http://org.apache.axis2/xsd" xmlns:xsd="http://common.mgt.user.carbon.wso2.org/xsd"> + <soapenv:Header/> + <soapenv:Body> + <mgt:addUser> + <!--Optional:--> + <mgt:userName>${userPrefix}${tenant_counter}_user${user_ref}</mgt:userName> + <!--Optional:--> + <mgt:password>1qaz2wsx@</mgt:password> + <mgt:roles>subscriber_role_new</mgt:roles> + </mgt:addUser> + </soapenv:Body> +</soapenv:Envelope> + + urn:addUser + true + false + + + + + + + + + https://${server}:9443/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://authentication.services.core.carbon.wso2.org"> + <soapenv:Header/> + <soapenv:Body> + <aut:logout/> + </soapenv:Body> +</soapenv:Envelope> + + urn:logout + true + false + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user_multi_tenancy_report.jtl + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/scripts/transport_restriction_check.jmx b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/transport_restriction_check.jmx new file mode 100644 index 0000000000..f45a4bcbe8 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/scripts/transport_restriction_check.jmx @@ -0,0 +1,1135 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 1 + + 1342532280000 + 1342532280000 + false + + + + + + + false + rfc2109 + + + + + + server + localhost + = + + + port + 9763 + = + + + sslport + 9443 + = + + + apinm + restricted_api + = + + + context + restricted_api + = + + + storeIP + localhost + = + + + storePort + 9763 + = + + + subsPrefix + transport_users + = + + + publisherName + admin + = + + + publisherPass + admin + = + + + csvPath + /home/ace/Desktop/test.csv + = + + + gatewayServer + localhost + = + + + gatewayPort + 8280 + = + + + gatewayHttpsPort + 8243 + = + + + version + 1.0.0 + = + + + apiServer + where.yahooapis.com + = + + + apiPath + /geocode + = + + + noOfSubscribers + 1 + = + + + + + + + + + + + false + login + = + true + action + + + false + ${publisherName} + = + true + username + + + false + ${publisherPass} + = + true + password + + + + ${server} + ${port} + + + + + /publisher/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addAPI + = + true + action + + + false + ${apinm} + = + true + name + + + false + ${context} + = + true + context + + + false + 1.0.0 + = + true + version + + + false + This API has been added by Jmeter Test + = + true + description + + + false + public + = + true + visibility + + + false + http://www.google.com/ig + = + true + endpoint + + + false + finder,open,social + = + true + tags + + + false + Unlimited + = + true + tier + + + false + https://lh6.ggpht.com/RNc8dD2hXG_rWGzlj09ZwAe1sXVvLWkeYT3ePx7zePCy4ZVV2XMGIxAzup4cKM85NFtL=w124 + = + true + apiThumb + + + false + Unlimited,Gold + = + true + tiersCollection + + + false + 0 + = + true + resourceCount + + + false + POST + = + true + resourceMethod-0 + + + false + /* + = + true + uriTemplate-0 + + + false + nonsecured + = + true + endpointType + + + false + /* + = + true + resourceTemplate + + + false + Create + = + true + addNewAPIButton + + + false + public + = + true + roles + + + false + Unlimited, Unlimited, Unlimited, Unlimited, Unlimited + = + true + resourceMethodThrottlingTier-0 + + + false + + = + true + http_checked + + + false + https + = + true + https_checked + + + false + Application User + = + true + resourceMethodAuthType-0 + + + + ${server} + ${port} + + + + + /publisher/site/blocks/item-add/ajax/add.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + false + regEx_message + "message" : "(.+?)" + $1$ + REGEX_FAILED + 0 + + + + false + regEx_error + "error" : (.+)\b + $1$ + REGEX_FAILED + 0 + + + + String message = vars.get("regEx_message"); +String error = vars.get("regEx_error"); + +if(error.equalsIgnoreCase("false") || (error.equalsIgnoreCase("true") && message.contains("A duplicate API already exists"))){ +Failure=false; +}else{ +Failure=true; +} + + + false + + + + false + true + true + false + + + + + + + + false + ${apinm} + = + true + name + + + false + 1.0.0 + = + true + version + + + false + ${publisherName} + = + true + provider + + + false + PUBLISHED + = + true + status + + + false + true + = + true + publishToGateway + + + false + updateStatus + = + true + action + + + + ${server} + ${port} + + + + + /publisher/site/blocks/life-cycles/ajax/life-cycles.jag + POST + true + false + true + false + Java + false + + + + + 500 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + true + ${noOfSubscribers} + + + + 1 + 10000 + 1 + subsCount + # + false + + + + + + + false + addUser + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + false + ${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}|${subsPrefix}_${subsCount}@test.com|| + = + true + allFieldsValues + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/sign-up/ajax/user-add.jag + POST + true + false + true + false + Java + false + + + + + 50 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + login + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + false + subscriber@123 + = + true + password + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/user/login/ajax/login.jag + GET + true + false + true + false + Java + false + + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + getApplications + = + true + action + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + + + /store/site/blocks/application/application-list/ajax/application-list.jag + GET + true + false + true + false + Java + false + + + + + true + + + String resp = prev.getResponseDataAsString(); + +int def = resp.indexOf("id"); +//int eq = resp.indexOf("=", def - 8); +String appid = resp.substring(def+6, resp.indexOf(", \"callbackUrl\"" )); +System.out.println(appid); +vars.put("appid", appid); + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + addSubscription + = + true + action + + + false + ${appid} + = + true + applicationId + + + false + ${apinm} + = + true + name + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + 1.0.0 + = + true + version + + + false + ${subsPrefix}_${subsCount} + = + true + username + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + GET + true + false + true + false + Java + false + + + + + 100 + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + generateApplicationKey + = + true + action + + + false + DefaultApplication + = + true + application + + + false + PRODUCTION + = + true + keytype + + + false + ${publisherName} + = + true + provider + + + false + Unlimited + = + true + tier + + + false + ${version} + = + true + version + + + false + + = + true + callbackUrl + + + false + + = + true + authorizedDomains + + + + ${storeIP} + ${storePort} + + + http + + /store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag + POST + true + false + true + false + Java + false + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int acc = jsonResponse.indexOf("accessToken"); + int col = jsonResponse.indexOf(":", acc); + String token = jsonResponse.substring(col+3, jsonResponse.indexOf("\"",col+10 )); + + int consumerKeyIndex = jsonResponse.indexOf("consumerKey"); + int consumerKeyStart =jsonResponse.indexOf(":",consumerKeyIndex); + String consumerKey = jsonResponse.substring(consumerKeyStart+3,consumerKeyStart+31); + + int consumerSecretIndex = jsonResponse.indexOf("consumerSecret"); + int consumerSecretStart =jsonResponse.indexOf(":",consumerSecretIndex); + String consumerSecret = jsonResponse.substring(consumerSecretStart+3,consumerSecretStart+31); + + System.out.println(token); +vars.put("token", token); +vars.put("consumerKey",consumerKey); +vars.put("consumerSecret",consumerSecret); + + + + + + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function encode64(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; +} + +function _utf8_encode(string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; +} + +var combinedKey = vars.get("consumerKey")+":"+vars.get("consumerSecret"); +vars.put("combinedKey",combinedKey); +var encodedKey = encode64(combinedKey); +vars.put("encodedKey",encodedKey); + javascript + + + + true + true + true + false + + + + + "error" : false + + Assertion.response_data + false + 2 + + + + + + + + false + grant_type=password&username=${subsPrefix}_${subsCount}&password=subscriber@123&scope=PRODUCTION + = + true + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + /token + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${encodedKey} + + + Content-Type + application/x-www-form-urlencoded + + + + + + + + false + String jsonResponse = prev.getResponseDataAsString(); + + int accessTokenIndex = jsonResponse.indexOf("access_token"); + int accessTokenStart =jsonResponse.indexOf(":",accessTokenIndex); + String accessToken =jsonResponse.substring(jsonResponse.indexOf("\"",accessTokenStart)+1,jsonResponse.indexOf("\"",accessTokenStart+10 )); + +vars.put("accessToken", accessToken); + + + + true + true + true + false + + + + + + + + ${gatewayServer} + ${gatewayPort} + + + http + + ${context}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + Unsupported Transport + + Assertion.response_data + true + 2 + + + + + + + + ${gatewayServer} + ${gatewayHttpsPort} + + + https + + ${context}/${version}/api?stock=AAPL + POST + true + false + true + false + Java + false + + + + + + + Authorization + Bearer ${accessToken} + + + Content-Type + application/xml + + + + + + + <no_data_message data="No data found"/> + + Assertion.response_data + false + 6 + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + true + false + false + false + false + false + 0 + true + + + /home/ace/Desktop/results_multi_user.jtl + + + + + + diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml b/modules/integration/tests/src/test/resources/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml new file mode 100644 index 0000000000..4e06ac5885 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/synapseconfigs/property/FORCE_HTTP_CONTENT_LENGTH.xml @@ -0,0 +1,271 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $1 + Status report + Runtime Error + $2 + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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. + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + The default main sequence for API manager - Returns 404 Not Found + + + + + + + + + + + + + + + + 30000 + fault + + + -1 + 0 + 1.0 + 0 + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30000 + fault + + + -1 + 0 + 1.0 + 0 + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/synapseconfigs/property/placeOrder.xml b/modules/integration/tests/src/test/resources/artifacts/AM/synapseconfigs/property/placeOrder.xml new file mode 100644 index 0000000000..de239abdb6 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/synapseconfigs/property/placeOrder.xml @@ -0,0 +1,7 @@ + + + 50 + 10 + IBM + + \ No newline at end of file diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/synapseconfigs/rest/url-mapping-synapse.xml b/modules/integration/tests/src/test/resources/artifacts/AM/synapseconfigs/rest/url-mapping-synapse.xml new file mode 100644 index 0000000000..a29656ba16 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/synapseconfigs/rest/url-mapping-synapse.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + +
    + + + + + + + 4.212070096051944 + -9.567415587431361 + -148.1740146577308 + IBM + + + + + + + + + + + + + diff --git a/modules/integration/tests/src/test/resources/artifacts/AM/synapseconfigs/throttling/throttling-api-synapse.xml b/modules/integration/tests/src/test/resources/artifacts/AM/synapseconfigs/throttling/throttling-api-synapse.xml new file mode 100644 index 0000000000..8e4f3c60b7 --- /dev/null +++ b/modules/integration/tests/src/test/resources/artifacts/AM/synapseconfigs/throttling/throttling-api-synapse.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + +
    + + + + + + + 4.212070096051944 + -9.567415587431361 + -148.1740146577308 + IBM + + + + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests/src/test/resources/automation.properties b/modules/integration/tests/src/test/resources/automation.properties new file mode 100644 index 0000000000..386f3354dc --- /dev/null +++ b/modules/integration/tests/src/test/resources/automation.properties @@ -0,0 +1,111 @@ +# Testing server details +#--------------------------------------------------------------------------------------------------- +stratos.test=false +port.enable=true +carbon.web.context.enable=false +service.deployment.delay=30000 +cluster.enable=false +product.list=AM +deployment.framework.enable=false +deployment.framework.home=/home/krishantha/automation/deployment-framework +#builder.enable=true +builder.enable=true +coverage.enable=true +execution.environment=integration +#execution.environment=distributed +execution.mode=user + +am.host.name=localhost +am.http.port=9763 +am.https.port=9443 +am.nhttp.port=8280 +am.nhttps.port=8243 + +#If deployment is distributed use these parameters after setting execution.mode property to distributed. +#Please note that to run some of test cases you might need to copy some resources to distributed deployment +#You will find more information about it inside class's init method comments +#Also note that if you are planning to run JMeter test you have to edit host/port definitions of jmeter scripts +am.distributed.store.http.url=http://localhost:9763 +am.distributed.store.https.url=https://localhost:9443 +am.distributed.publisher.http.url=http://localhost:9763 +am.distributed.publisher.https.url=https://localhost:9443 +am.distributed.gateway.http.url=http://localhost:8280/ +am.distributed.gateway.https.url=https://localhost:8243/ +am.test.application.usage.http.url=http://localhost:9763/testapp/testUsageWithBAM.jag +am.test.application.store.http.url=http://localhost:9763/testapp/testStore.jag +am.test.application.publisher.http.url=http://localhost:9763/testapp/testPublisher.jag + + +ravana.framework.path=/home/krishantha/new-machine/svn/ravana/ravana2 +ravana.test=true + +#(chrome|firefox|opera|ie|htmlUnit) +browser.name=firefox +path.to.chrome.driver="/home/krishantha/Downloads/chromedriver" + +#run selenium test on remote browser or not. (true|false) +remote.selenium.web.driver.start=false +remote.webdirver.url=http://10.100.2.51:4444/wd/hub/ + +#this database configuration is used for data service test in product testing. configuration used as a data source in dbs files +#database.driver.name=com.mysql.jdbc.Driver +#jdbc.url=jdbc:mysql://127.0.0.1:3306 +database.driver.name=org.h2.Driver +jdbc.url=jdbc:h2: +db.user=dbuser1 +db.password=dbuser123 +db.name=testDb + +#RSS Data Source configuration in Stratos. this user name and password are used to create a user on RSS Manager in stratos and used in .dbs file as well +#user name should be limited to 7 characters +rss.database.user = tstusr1 +rss.database.password =test123 + +ravana.jdbc.url=jdbc:mysql://127.0.0.1:3306 +ravana.db.user=root +ravana.db.password=root + + +#this database configuration is used for test result dashboard. +dashboard.enable=false +dashboard.database.driver.name=com.mysql.jdbc.Driver +dashboard.jdbc.url=jdbc:mysql://127.0.0.1:3306 +dashboard.db.user=root +dashboard.db.password=root +dashboard.db.name=FRAMEWORK_DB + + +#Stratos server details +#---------------------------------------------------------------------------------------------------- +app.service.host.name=appserver.stratosdev.private.wso2.com +esb.service.host.name=esb.stratosdev.private.wso2.com +greg.service.host.name=governance.stratosdev.private.wso2.com +dss.service.host.name=data.stratosdev.private.wso2.comso2.comso2.com +gs.service.host.name=gadget.stratosdev.private.wso2.comso2.com +brs.service.host.name=rule.stratosdev.private.wso2.com +bps.service.host.name=process.stratosdev.private.wso2.com +manager.service.host.name=stratosdev.private.wso2.com +ms.service.host.name=mashup.stratosdev.private.wso2.com +mb.service.host.name=messaging.stratosdev.private.wso2.com +cep.service.host.name=cep.stratosdev.private.wso2.com +bam.service.host.name=monitor.stratosdev.private.wso2.comso2.com +is.service.host.name=identity.stratosdev.private.wso2.com + + +#stratosliveqa.private.wso2.com + +#app.service.host.name=appserver.stratosliveqa.private.wso2.com +#esb.service.host.name=esb.stratosliveqa.private.wso2.com +#greg.service.host.name=governance.stratosliveqa.private.wso2.com +#dss.service.host.name=data.stratosliveqa.private.wso2.com +#gs.service.host.name=gadget.stratosliveqa.private.wso2.com +#brs.service.host.name=rule.stratosliveqa.private.wso2.com +#bps.service.host.name=process.stratosliveqa.private.wso2.com +#manager.service.host.name=stratosliveqa.private.wso2.com +#ms.service.host.name=mashup.stratosliveqa.private.wso2.com +#mb.service.host.name=messaging.stratosliveqa.private.wso2.com +#cep.service.host.name=cep.stratosliveqa.private.wso2.com +#bam.service.host.name=monitor.stratosliveqa.private.wso2.com +#is.service.host.name=identity.stratosliveqa.private.wso2.com + + diff --git a/modules/integration/tests/src/test/resources/axis2config/axis2_client.xml b/modules/integration/tests/src/test/resources/axis2config/axis2_client.xml new file mode 100644 index 0000000000..db07954a47 --- /dev/null +++ b/modules/integration/tests/src/test/resources/axis2config/axis2_client.xml @@ -0,0 +1,299 @@ + + + + + + + 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/integration/tests/src/test/resources/client/modules/addressing-1.6.1-wso2v9.mar b/modules/integration/tests/src/test/resources/client/modules/addressing-1.6.1-wso2v9.mar new file mode 100644 index 0000000000..d3871a1586 Binary files /dev/null and b/modules/integration/tests/src/test/resources/client/modules/addressing-1.6.1-wso2v9.mar differ diff --git a/modules/integration/tests/src/test/resources/keystores/products/client-truststore.jks b/modules/integration/tests/src/test/resources/keystores/products/client-truststore.jks new file mode 100644 index 0000000000..9e3a51db3e Binary files /dev/null and b/modules/integration/tests/src/test/resources/keystores/products/client-truststore.jks differ diff --git a/modules/integration/tests/src/test/resources/keystores/products/wso2carbon.jks b/modules/integration/tests/src/test/resources/keystores/products/wso2carbon.jks new file mode 100644 index 0000000000..7942c53cf9 Binary files /dev/null and b/modules/integration/tests/src/test/resources/keystores/products/wso2carbon.jks differ diff --git a/modules/integration/tests/src/test/resources/tenantList.csv b/modules/integration/tests/src/test/resources/tenantList.csv new file mode 100644 index 0000000000..23439d5f25 --- /dev/null +++ b/modules/integration/tests/src/test/resources/tenantList.csv @@ -0,0 +1,16 @@ +"0","admin","admin" +"1","admin123@wso2autoQA0999.org","admin123" +"2","testuser2@wso2autoQA0999.org","admin123" +"3","testuser3@wso2autoQA0999.org","admin123" +"4","testuser4@wso2autoQA0999.org","admin123" +"5","testuser5@wso2autoQA0999.org","admin123" +"6","testuser6@wso2autoQA0999.org","admin123" +"7","testuser7@wso2autoQA0999.org","admin123" +"8","testuser8@wso2autoQA0999.org","admin123" +"9","testuser9@wso2autoQA0999.org","admin123" +"10","testuser10@wso2autoQA0999.org","admin123" +"11","testuser11@wso2autoQA0999.org","admin123" +"12","testuser12@wso2autoQA0999.org","admin123" +"13","testuser13@wso2autoQA0999.org","admin123" +"14","testuser14@wso2autoQA0999.org","admin123" +"15","testuser15@wso2autoQA0999.org","admin123" diff --git a/modules/integration/tests/src/test/resources/testng-server-mgt.xml b/modules/integration/tests/src/test/resources/testng-server-mgt.xml new file mode 100644 index 0000000000..5e8092e484 --- /dev/null +++ b/modules/integration/tests/src/test/resources/testng-server-mgt.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests/src/test/resources/testng.xml b/modules/integration/tests/src/test/resources/testng.xml new file mode 100644 index 0000000000..82a532ee54 --- /dev/null +++ b/modules/integration/tests/src/test/resources/testng.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/integration/tests/src/test/resources/userList.csv b/modules/integration/tests/src/test/resources/userList.csv new file mode 100644 index 0000000000..fdcba6bd9c --- /dev/null +++ b/modules/integration/tests/src/test/resources/userList.csv @@ -0,0 +1,17 @@ +"0","admin","admin" +"1","adminuser","adminuser" +"2","testuser2","testuser2" +"3","testuser3","testuser3" +"4","testuser4","testuser4" +"5","testuser5","testuser5" +"6","testuser6","testuser6" +"7","testuser7","testuser7" +"8","testuser8","testuser8" +"9","testuser9","testuser9" +"10","testuser10","testuser10" +"11","testuser11","testuser12" +"12","testuser12","testuser12" +"13","testuser13","testuser13" +"14","testuser14","testuser14" +"15","testuser15","testuser15" +"16", "abc@abc.com","abc123" diff --git a/modules/jaggery/encode/module.xml b/modules/jaggery/encode/module.xml new file mode 100644 index 0000000000..15a9762513 --- /dev/null +++ b/modules/jaggery/encode/module.xml @@ -0,0 +1,7 @@ + + + org.wso2.carbon.apimgt.hostobjects.EncodeHostObject + Encode + + + diff --git a/modules/jaggery/sso/module.xml b/modules/jaggery/sso/module.xml new file mode 100644 index 0000000000..15682e7284 --- /dev/null +++ b/modules/jaggery/sso/module.xml @@ -0,0 +1,7 @@ + + + org.wso2.carbon.hostobjects.sso.SAMLSSORelyingPartyObject + SSORelyingParty + + + \ No newline at end of file diff --git a/modules/jaggery/tenantmanager/module.xml b/modules/jaggery/tenantmanager/module.xml new file mode 100644 index 0000000000..1afbf02540 --- /dev/null +++ b/modules/jaggery/tenantmanager/module.xml @@ -0,0 +1,7 @@ + + + org.wso2.carbon.apimgt.hostobjects.TenantManagerHostObject + TenantManager + + + diff --git a/modules/org.wso2.stratos.apimgt.dashboard.ui/pom.xml b/modules/org.wso2.stratos.apimgt.dashboard.ui/pom.xml new file mode 100644 index 0000000000..7f5a018a94 --- /dev/null +++ b/modules/org.wso2.stratos.apimgt.dashboard.ui/pom.xml @@ -0,0 +1,97 @@ + + + + org.wso2.am + am-parent + 1.7.0-SNAPSHOT + ../../pom.xml + + + 4.0.0 + org.wso2.stratos.apimgt.dashboard.ui + ${stratos.version} + bundle + WSO2 Stratos API Manager - Dashboard UI + + + + + + org.apache.felix + maven-scr-plugin + + + org.apache.felix + maven-bundle-plugin + + true + + + ${project.artifactId} + ${project.artifactId} + + org.wso2.stratos.apimgt.dashboard.ui.*, + + + !javax.xml.namespace, + javax.xml.namespace; version=0.0.0, + javax.servlet; version="${imp.pkg.version.javax.servlet}", + javax.servlet.http; version="${imp.pkg.version.javax.servlet}", + *;resolution:=optional + + UIBundle + + + + + + + + + org.apache.axis2.wso2 + axis2 + + + + log4j + log4j + + + org.wso2.carbon + org.wso2.carbon.registry.core + ${carbon.kernel.version} + + + org.wso2.carbon + org.wso2.carbon.ui + ${carbon.kernel.version} + + + org.wso2.carbon + org.wso2.carbon.statistics.ui + ${carbon.platform.version} + + + commons-logging + commons-logging + + + + + diff --git a/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/css/dashboard-common.css b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/css/dashboard-common.css new file mode 100644 index 0000000000..c241d78116 --- /dev/null +++ b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/css/dashboard-common.css @@ -0,0 +1,66 @@ +.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/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/docs/userguide.html b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/docs/userguide.html new file mode 100644 index 0000000000..1dd6aec676 --- /dev/null +++ b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/docs/userguide.html @@ -0,0 +1,39 @@ + + + + + + Cloud API Manager Home - User Guide + + + + +

    Cloud API Manager Home

    + +

    +The WSO2 API Manager The WSO2 API Manager is an enterprise-ready, fully-open source, +complete solution for creating, publishing and managing all aspects of an API and its life cycle, catering for the +needs of both API publisher and API consumer requirements. +

    + + +

    Figure1: Cloud API Manager Home

    + + + diff --git a/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/dashboard-title-bg.gif b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/dashboard-title-bg.gif new file mode 100644 index 0000000000..15a5406554 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/dashboard-title-bg.gif differ diff --git a/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/java2wsdl.png b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/java2wsdl.png new file mode 100644 index 0000000000..12ecb14be2 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/java2wsdl.png differ diff --git a/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/message-tracing.png b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/message-tracing.png new file mode 100644 index 0000000000..4ccd15dba8 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/message-tracing.png differ diff --git a/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/modules.png b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/modules.png new file mode 100644 index 0000000000..9e4b5d2b26 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/modules.png differ diff --git a/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/service-hosting.png b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/service-hosting.png new file mode 100644 index 0000000000..ee0a4a4016 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/service-hosting.png differ diff --git a/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/service-testing.png b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/service-testing.png new file mode 100644 index 0000000000..d04d57c4e8 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/service-testing.png differ diff --git a/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/tip-back.png b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/tip-back.png new file mode 100644 index 0000000000..b19ac2f8ab Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/tip-back.png differ diff --git a/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/tip-bottom.png b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/tip-bottom.png new file mode 100644 index 0000000000..3159c0ec53 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/tip-bottom.png differ diff --git a/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/web-applications.png b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/web-applications.png new file mode 100644 index 0000000000..91e82aca5e Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/web-applications.png differ diff --git a/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/wsdl-validator.png b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/wsdl-validator.png new file mode 100644 index 0000000000..10b7d91d56 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/wsdl-validator.png differ diff --git a/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/wsdl2java.png b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/wsdl2java.png new file mode 100644 index 0000000000..b825d36bcf Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/images/wsdl2java.png differ diff --git a/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/index.jsp b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/index.jsp new file mode 100644 index 0000000000..3186b81f35 --- /dev/null +++ b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/index.jsp @@ -0,0 +1,143 @@ + +<%@ 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 API Manager quick start dashboard

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

    Web Applications


    + <% + } + %> +

    Web Application hosting features in API Manager supports deployment of Jaggery Applications. Deployed Webapps can be easily managed using the Webapp management facilities available in the management console.

    + +
    +
    +
    + <% + if (hasServiceMgtPermission) { + %> + Service Testing
    + <% + } else { + %> +

    Service Testing


    + <% + } + %> +

    Tryit tool can be used as a simple Web Service client which can be used to try your services within Server itself.

    + +
    +
    +
    + <% + if (hasServiceMgtPermission) { + %> + Message Tracing
    + <% + } else { + %> +

    Message Tracing


    + <% + } + %> +

    Trace the request and responses to your service. Message Tracing is a vital debugging tool when you have clients from heterogeneous platforms.

    + +
    +
    + + + + +

    +
    +

    +
    diff --git a/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/system_stats_ajaxprocessor.jsp b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/system_stats_ajaxprocessor.jsp new file mode 100644 index 0000000000..72ce2a263b --- /dev/null +++ b/modules/org.wso2.stratos.apimgt.dashboard.ui/src/main/resources/web/tenant-dashboard/system_stats_ajaxprocessor.jsp @@ -0,0 +1,127 @@ + +<%@ 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/org.wso2.stratos.apimgt.login.ui/pom.xml b/modules/org.wso2.stratos.apimgt.login.ui/pom.xml new file mode 100644 index 0000000000..7faa4cbbc5 --- /dev/null +++ b/modules/org.wso2.stratos.apimgt.login.ui/pom.xml @@ -0,0 +1,125 @@ + + + + + org.wso2.am + am-parent + 1.7.0-SNAPSHOT + ../../pom.xml + + + 4.0.0 + org.wso2.stratos.apimgt.login.ui + ${stratos.version} + bundle + WSO2 AM - Login User Interface + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.5 + 1.5 + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-source + generate-sources + + add-source + + + + target/generated-code/src + + + + + + + + org.apache.felix + maven-bundle-plugin + + true + + + ${project.artifactId} + ${project.artifactId} + + javax.servlet; version="${imp.pkg.version.javax.servlet}", + javax.servlet.http; version="${imp.pkg.version.javax.servlet}", + org.apache.lucene.*, + *;resolution:=optional + + + UIBundle + + + + + + + + + + + log4j + log4j + + + commons-logging + commons-logging + + + org.eclipse.equinox + javax.servlet + ${javax.servlet.version} + + + org.apache.axis2.wso2 + axis2 + + + org.apache.ws.commons.axiom.wso2 + axiom + + + org.wso2.carbon + org.wso2.carbon.ui + ${carbon.kernel.version} + + + org.wso2.carbon + org.wso2.carbon.core + ${carbon.kernel.version} + + + + + diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/META-INF/component.xml b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/META-INF/component.xml new file mode 100644 index 0000000000..746a68bece --- /dev/null +++ b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/META-INF/component.xml @@ -0,0 +1,20 @@ + + + + diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/org/wso2/stratos/apimgt/login/ui/i18n/JSResources.properties b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/org/wso2/stratos/apimgt/login/ui/i18n/JSResources.properties new file mode 100644 index 0000000000..4282f03686 --- /dev/null +++ b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/org/wso2/stratos/apimgt/login/ui/i18n/JSResources.properties @@ -0,0 +1,2 @@ +password.mismatched=Passwords do not match. +current.password.should.provided=You should provide the current password inorder to change the password. \ No newline at end of file diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/org/wso2/stratos/apimgt/login/ui/i18n/Resources.properties b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/org/wso2/stratos/apimgt/login/ui/i18n/Resources.properties new file mode 100644 index 0000000000..887b08780c --- /dev/null +++ b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/org/wso2/stratos/apimgt/login/ui/i18n/Resources.properties @@ -0,0 +1,43 @@ +submit.tenant=Submit Tenant +domain=Domain +domain.information=Domain Information +contact.details=Contact Details +admin.username=Admin Username +current.admin.password=Current Admin Password +new.admin.password=New Admin Password +new.admin.password.repeat=New Admin Password (Repeat) +admin.password=Admin Password +admin.password.repeat=Admin Password (Repeat) +govern.add_tenants.menu=Add New Tenant +govern.view_tenants.menu=View Tenants +overview=Overview +tenants.list=Tenants List +company.organization=Company/Organization +admin.contact=Admin Contact +edit=Edit +multitenancy=Multitenancy +added.successfully=You have successfully added a new tenant with domain: +updated.successfully=You have successfully updated the tenant with domain: +update.added.tenant=Update the just added/updated tenant +update.tenant=Update Tenant +add.new.tenant=Add a new tenant +register.new.organization=Register A New Organization +view.all.tenants=View all tenants +tenant.admin=Tenant Admin +tenant.description=Tenant Description +admin.fullname=Full Name +admin.address=Address +admin.email=Email +admin.telephone=Telephone +admin.im=IM +admin.url=URL +self.registration=Registry Tenant +gaas=GaaS +gaas.register.a.new.tenant=Register A New Tenant +active=Active +theme.management=Theme Managment +word.verification=Word Verification +captcha.message=Type the characters you see in the picture below. +sign.in=Sign in +sign.in.help=Sign in help +forgot.password=Forgot Password diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/css/loginpage.css b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/css/loginpage.css new file mode 100644 index 0000000000..f54bbb533b --- /dev/null +++ b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/css/loginpage.css @@ -0,0 +1,268 @@ +body { + color:#111111; + font-family:"Calibri","Lucida Grande","Lucida Sans","Microsoft Sans Serif","Lucida Sans Unicode","Verdana","Sans-serif","trebuchet ms" !important; + font-size:0.75em; + font-size-adjust:none; + font-style:normal; + font-variant:normal; + font-weight:normal; + line-height:1.25em; + background-image: url(../images/body-bg.gif); + background-position: left top; + background-repeat: repeat-x; + margin: 0px; + padding: 0px; +} + +div.clear { + clear:both; +} +p { } + +td { } + +a:link { } + +a:visited { } + +a:hover { } + +a:active { } + +div#login-content { + background-image:url(../images/login-bg.gif); + background-position:left top; + background-repeat:no-repeat; + height:277px; + left:50%; + margin-left:-481px; + position:absolute; + text-align:center; + width:962px; +} +div#login-content div.main-text { + margin-top: 113px; + margin-left: 50px; + float: left; + width: 750px; + font-size: 140%; + line-height: 125%; + height: 80px; + text-align: left; +} +div.feature { + float:left; + margin-left:79px; + margin-top:23px; + padding-bottom:20px; + padding-top:20px; + text-align:left; + width:221px; +} +div.feature img { + float: left; + margin-right: 10px; + width: 64px; +} +div.feature h2 { + margin-top: 0px; + margin-bottom: 7px; + color: #0499CC; + font-size: 155%; + line-height: 110%; + font-weight: normal; + +} +div.feature p { + margin-top: 0px; + padding-top: 0px; +} +div#login-content div.feature-left { + margin-left: 70px; +} +a.register-button { + background-image:url(../images/reg-button.gif); + background-position:left top; + background-repeat:no-repeat; + color:#FFFFFF; + cursor:pointer; + display:block; + font-size:220%; + font-weight:normal; + line-height:63px; + margin:auto auto 5px; + text-align:left; + text-decoration:none; + text-indent:25px; + width:444px; +} +a.register-button:hover { + background-image: url(../images/reg-button-hover.gif); +} +div.resources { + text-align: center; +} +div.resources a { + background-image:url("../images/link-icon.gif"); + background-position:right 4px; + background-repeat:no-repeat; + color:#004990; + font-size:130%; + line-height:20px; + padding-right:15px; + text-decoration:none; +} +div.resources a:hover { + color: #000000; +} +table.ad { + width: 100%; + margin-top: 15px; +} +table.ad tr td { + vertical-align: top; + text-align: center; +} +td#ad { + height:210px; + width: 50%; +} +div#sign-in { + text-align:left; + width: 580px; + margin: auto; +} +div#sign-in div.sign-in-form { + width: 580px; +} +div#sign-in h2 { + border-bottom:1px solid #78BDE8; + font-size:130%; + margin-bottom:10px; + margin-top:0; + padding-bottom:10px; + padding-top:0; +} +div#sign-in table tr td.top { + padding-top: 10px; +} +div#sign-in table tr td { + padding-bottom:5px; + padding-right:7px; +} +div#sign-in table { + border-bottom:1px solid #0499CC; + margin-bottom:7px; +} +div#sign-in table tr td.title { + font-size: 180%; + font-weight: bold; + padding-bottom: 10px; + padding-top: 0px; + text-align: left; +} +#loginForm td label{ + font-size:12px; +} +div#sign-in a.help { + font-size: 14px; + text-decoration: none; + color: #00447C; +} +td#ad iframe.ad-frame { + border: 0px; + width: 420px; + height: 210px; + margin: 0px; + padding: 0px; +} +div#footer { + margin-top: 30px; + height: 50px; + border-top: solid 1px #009FC2; + padding-top: 7px; + text-align: left; +} +div#footer a { + text-decoration: none; + color: #00447C; +} +div#footer div.powered { + float: right; + font-size: 11px; + color: #333; +} +div#footer div.powered span { + float: left; + margin-right: 5px; + line-height: 23px; +} +div#sign-in table.sign-in { + border-bottom: 0px; +} +div#sign-in table tr td { + padding-top: 10px; + width: 290px; +} +div#sign-in table tbody tr td.third-party { + border-left: dotted 1px #cccccc; + padding: 20px; +} +div#sign-in table tbody tr td.third-party a img { + border: 0px; + margin-top: 10px; +} +.sign-in-box{ + -moz-border-radius: 5px; + border-radius: 5px; + border:solid 1px #b5dff7; + background-color:#ebf7fd; + padding-left:10px; + width:800px; + margin-left:70px; + + -moz-box-shadow: 0 0 3px #999; + -webkit-box-shadow: 0 0 3px #999; + box-shadow: 0 0 3px #999; +} +.sign-in-box h3{ + color:#0499cc; + font-size:12px; + font-weight:bold; + padding-bottom:10px; +} +.sign-in-box table tr td{ + text-align:left !important; +} +.user_pass_table a{ + font-size:11px; +} +.user_pass_table td{ + padding:4px; + text-align:left !important; +} +.sign-in-box div.help_txt{ + color: #666666; + line-height:20px; +} +.user_pass_td{ + border-right:solid 1px #ccc; +} +.google-app-td{ + padding-left:10px; + width:300px; +} +#loginBoxGoogle{ + margin-top:15px; +} +#loginBoxGoogle div.help_txt{ + font-size:11px; +} +h2.stratos-Signin{ + color:#0499cc; + font-size:22px; + line-height:30px; +} +.google-app-td img{ + cursor:pointer; +} \ No newline at end of file diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/css/tenant.css b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/css/tenant.css new file mode 100644 index 0000000000..2f06cc5fbb --- /dev/null +++ b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/css/tenant.css @@ -0,0 +1,62 @@ +/*css editor styles */ +.csseditor-top-line{ + background-color:black; + height:5px; +} +.csseditor-leftbox{ + background-color:#9a9a9a; + padding-left:5px; + padding-right:5px; + padding-bottom:5px; + padding-top:15px; + height:380px; +} +.csseditor-leftbox-top{ + color:#ffffff; + font-size:18px; + height:30px; +} +.csseditor-textbox{ + background-color:#dfe7ed; + border:solid 1px #ffffff; + width:100%; +} +.csseditor-rightbox{ + background-color:#c9c9c9; + border:solid 1px #ffffff; + height:400px; +} +.csseditor-rightbox-title{ + background-color:#9a9a9a; + height:25px; + color:#ffffff; + padding-left:10px; + padding-top:5px; +} +.csseditor-searchbox{ + padding-left:10px; + padding-top:10px; +} +#flickr_results{ + height:300px; + overflow-y:auto; + overflow-x:hidden; + margin-left:5px; + margin-right:5px; + border:solid 1px #ffffff; +} +.imageList{ +} +.imageList li { + padding-top: 3px !important; + padding-left: 5px !important; + background-color: #e1e9ec; + border: solid 1px #b5bdc1; +} + +.imageList li a { + background-image: url(../images/images.gif); + background-repeat: no-repeat; + padding-left: 20px; + text-indent: 50px; +} \ No newline at end of file diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/docs/images/sign-in-no-domain.png b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/docs/images/sign-in-no-domain.png new file mode 100644 index 0000000000..be1c8229f0 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/docs/images/sign-in-no-domain.png differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/docs/images/sign-in-with-domain.png b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/docs/images/sign-in-with-domain.png new file mode 100644 index 0000000000..9bd6c408de Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/docs/images/sign-in-with-domain.png differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/docs/userguide.html b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/docs/userguide.html new file mode 100644 index 0000000000..71fb1cfd97 --- /dev/null +++ b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/docs/userguide.html @@ -0,0 +1,109 @@ + + + + + WSO2 Cloud API Manager - Sign In - User Guide + + + + +

    WSO2 Cloud API Manager - Sign In

    + +

    +You can use this form to sign in to the WSO2 Cloud API Manager Admin Console. + +

    + + + +

    1. The common login

    + +

    + +

    +

    Figure1: Sign In Form

    + +

    + + + + + + + + + + + + + + + + +
    + The Form Field + + Description +
    Username

    For this field you need to enter the username in the following format.

    +
    yourname@yourdomain
    +

    E.g. foo@wso2.com

    +
    PasswordThe Password of your user account +
    +

    + + +

    2. The domain name specific login: When accessed through https://apimanager.stratoslive.wso2.com/t/yourdomoain

    + +

    + +

    +

    Figure1: Sign In Form When accessed through https://apimanager.stratoslive.wso2.com/t/yourdomoain

    + +

    + + + + + + + + + + + + + + + + +
    + The Form Field + + Description +
    Username

    For this field you only need to enter the username as the domain name is already suggested for you. Note that derives the domain + name from the url. So in case you want to login to an account in a different domain you have to change the url of the correct domain specific + login and try entering the username and password.

    +
    PasswordThe Password of your user account +
    +

    + + + + + diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/ajax-loader.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/ajax-loader.gif new file mode 100644 index 0000000000..f2a1bc0c6f Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/ajax-loader.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/body-bg.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/body-bg.gif new file mode 100644 index 0000000000..878c3574c1 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/body-bg.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/button-back.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/button-back.gif new file mode 100644 index 0000000000..6a52e342ef Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/button-back.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/cloud-as-logo.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/cloud-as-logo.gif new file mode 100644 index 0000000000..238587d773 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/cloud-as-logo.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/content-back-left.jpg b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/content-back-left.jpg new file mode 100644 index 0000000000..ebfe8ed717 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/content-back-left.jpg differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/content-back.jpg b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/content-back.jpg new file mode 100644 index 0000000000..62b8da1d8d Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/content-back.jpg differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/create-org-button.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/create-org-button.gif new file mode 100644 index 0000000000..b7e62a3e7a Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/create-org-button.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/feature-01-icon.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/feature-01-icon.gif new file mode 100644 index 0000000000..f2cbb36dad Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/feature-01-icon.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/feature-02-icon.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/feature-02-icon.gif new file mode 100644 index 0000000000..7f0482f0a3 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/feature-02-icon.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/feature-03-icon.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/feature-03-icon.gif new file mode 100644 index 0000000000..c78f9ff443 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/feature-03-icon.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/footer.jpg b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/footer.jpg new file mode 100644 index 0000000000..c617091d21 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/footer.jpg differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/forum.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/forum.gif new file mode 100644 index 0000000000..e92779ad91 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/forum.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/google-apps-login.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/google-apps-login.gif new file mode 100644 index 0000000000..6eb5c9b79b Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/google-apps-login.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/header.jpg b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/header.jpg new file mode 100644 index 0000000000..4438a061c6 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/header.jpg differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/help.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/help.gif new file mode 100644 index 0000000000..3b050aac23 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/help.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/images.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/images.gif new file mode 100644 index 0000000000..94b46dc323 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/images.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/issue-tracker.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/issue-tracker.gif new file mode 100644 index 0000000000..9029c129ee Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/issue-tracker.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/link-icon.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/link-icon.gif new file mode 100644 index 0000000000..5598f59694 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/link-icon.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/login-bg.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/login-bg.gif new file mode 100644 index 0000000000..8c9a818d3f Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/login-bg.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/mailing-list.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/mailing-list.gif new file mode 100644 index 0000000000..06d61e3c68 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/mailing-list.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/paas-login-1pix.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/paas-login-1pix.gif new file mode 100644 index 0000000000..439f27d7fe Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/paas-login-1pix.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/page-back.jpg b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/page-back.jpg new file mode 100644 index 0000000000..2e21b54124 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/page-back.jpg differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/people.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/people.gif new file mode 100644 index 0000000000..edfa49b1ba Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/people.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/powered.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/powered.gif new file mode 100644 index 0000000000..3b4d1b5dd3 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/powered.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/reg-button-hover.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/reg-button-hover.gif new file mode 100644 index 0000000000..89f2c549d3 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/reg-button-hover.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/reg-button.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/reg-button.gif new file mode 100644 index 0000000000..5d8e2e434f Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/reg-button.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/register-button-hover.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/register-button-hover.gif new file mode 100644 index 0000000000..3c50668d8e Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/register-button-hover.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/register-button.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/register-button.gif new file mode 100644 index 0000000000..0929039562 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/register-button.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/services.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/services.gif new file mode 100644 index 0000000000..988311692f Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/services.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/thememgt.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/thememgt.gif new file mode 100644 index 0000000000..e554e87420 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/thememgt.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/user-guide.gif b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/user-guide.gif new file mode 100644 index 0000000000..9342adcd16 Binary files /dev/null and b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/images/user-guide.gif differ diff --git a/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/login_ajaxprocessor.jsp b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/login_ajaxprocessor.jsp new file mode 100644 index 0000000000..5fc66cfedd --- /dev/null +++ b/modules/org.wso2.stratos.apimgt.login.ui/src/main/resources/web/tenant-login/login_ajaxprocessor.jsp @@ -0,0 +1,280 @@ + +<%@ page import="org.wso2.carbon.CarbonConstants" %> + +<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> +<%@ page import="org.wso2.carbon.utils.multitenancy.MultitenantConstants" %> + +<%--Copyright 2004 The Apache Software Foundation + +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. +--%> + +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> +<%@ taglib prefix="carbon" uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" %> + + + + + + + + WSO2 Stratos API Manager + + + + + + + + + + + + + + + + + + + +
    + + +<% + if("Success".equals(request.getParameter("addTenant"))){ + %> + + +<% + } + String tenantdomain = (String)request.getAttribute(MultitenantConstants.TENANT_DOMAIN); + String tip = ""; + if(tenantdomain == null){ + tenantdomain = ""; + tip = "Enter the username in the format: user name@yourdomain, Example: foo@abc.com"; + } + else{ + tenantdomain = "@" + tenantdomain; + } + String userForumURL = (String) config.getServletContext().getAttribute(CarbonConstants.PRODUCT_XML_WSO2CARBON + CarbonConstants.PRODUCT_XML_USERFORUM); + String userGuideURL = (String) config.getServletContext().getAttribute(CarbonConstants.PRODUCT_XML_WSO2CARBON + CarbonConstants.PRODUCT_XML_USERGUIDE); + String mailinglistURL = (String) config.getServletContext().getAttribute(CarbonConstants.PRODUCT_XML_WSO2CARBON + CarbonConstants.PRODUCT_XML_MAILINGLIST); + String issuetrackerURL = (String) config.getServletContext().getAttribute(CarbonConstants.PRODUCT_XML_WSO2CARBON + CarbonConstants.PRODUCT_XML_ISSUETRACKER); + if (userForumURL == null) { + userForumURL = "#"; + } + if (userGuideURL == null) { + userGuideURL = "#"; + } + if (mailinglistURL == null) { + mailinglistURL = "#"; + } + if (issuetrackerURL == null) { + issuetrackerURL = "#"; + } +%> + + <% + String loginStatus = request.getParameter("loginStatus"); + if (loginStatus != null && "false".equalsIgnoreCase(loginStatus)) { + %> + + <% + } + + if (loginStatus != null && "failed".equalsIgnoreCase(loginStatus)) { + %> + + <% + } + String backendURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); + String registerPath = null; + int serviceIndex = backendURL.indexOf("/services/"); + int startingIndex = backendURL.contains("https")? "https://".length(): "http://".length(); + String serverName = backendURL.substring(startingIndex, serviceIndex); + int dotIndex = serverName.indexOf("."); + if (dotIndex != -1) { + String managerServerName = serverName.substring(dotIndex + 1); + registerPath = "https://" + managerServerName + "/carbon/tenant-register/select_domain.jsp"; + } + + %> + <%--New page design begings--%> + + +
    +
    + The WSO2 API Manager, supporting management of all aspects of an API and its life cycle, delivered as a multi-tenant, elastically scaling, metered platform +
    +
    + +
    + + + + +
    + + + +
    + +
    + +
    + + + + +
    + + + diff --git a/modules/p2-profile/pom.xml b/modules/p2-profile/pom.xml new file mode 100644 index 0000000000..043d9b7920 --- /dev/null +++ b/modules/p2-profile/pom.xml @@ -0,0 +1,65 @@ + + + + + + + org.wso2.am + am-parent + 1.7.0-SNAPSHOT + ../../pom.xml + + + 4.0.0 + am-p2-profile-gen-parent + pom + WSO2 API Manager - P2 Profile Generation Parent + http://wso2.com/products/api-manager + WSO2 API Manager P2 Profile Generation Parent + + + + Apache License Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + + + + + product + + + + + + maven-clean-plugin + + + auto-clean + initialize + + clean + + + + + + + diff --git a/modules/p2-profile/product/carbon.product b/modules/p2-profile/product/carbon.product new file mode 100644 index 0000000000..c29ac1eab0 --- /dev/null +++ b/modules/p2-profile/product/carbon.product @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/p2-profile/product/pom.xml b/modules/p2-profile/product/pom.xml new file mode 100644 index 0000000000..62d3232c2b --- /dev/null +++ b/modules/p2-profile/product/pom.xml @@ -0,0 +1,2901 @@ + + + + + + + org.wso2.am + am-p2-profile-gen-parent + 1.7.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + am-p2-profile + pom + WSO2 API Manager - P2 Profile Generation + http://www.wso2.org + + + + + org.apache.maven.plugins + maven-dependency-plugin + 2.0-alpha-4 + false + + + 1-unpack-p2-agent-distribution + test + + unpack + + + + + org.wso2.carbon + wso2carbon-core + ${carbon.kernel.version} + zip + true + target + + + + + + + 2-unpack-kernel-patch + test + + unpack + + + + + org.wso2.carbon + WSO2-CARBON-PATCH-4.2.0 + 0001 + zip + true + target + + + + + + 3-unpack-kernel-patch + test + + unpack + + + + + org.wso2.carbon + WSO2-CARBON-PATCH-4.2.0 + 0002 + zip + true + target + + + + + + 4-unpack-kernel-patch + test + + unpack + + + + + org.wso2.carbon + WSO2-CARBON-PATCH-4.2.0 + 0003 + zip + true + target + + + + + + 5-unpack-kernel-patch + test + + unpack + + + + + org.wso2.carbon + WSO2-CARBON-PATCH-4.2.0 + 0004 + zip + true + target + + + + + + 6-unpack-kernel-patch + test + + unpack + + + + + org.wso2.carbon + WSO2-CARBON-PATCH-4.2.0 + 0005 + zip + true + target + + + + + + 7-unpack-kernel-patch + test + + unpack + + + + + org.wso2.carbon + WSO2-CARBON-PATCH-4.2.0 + 0006 + zip + true + target + + + + + + 8-unpack-kernel-patch + test + + unpack + + + + + org.wso2.carbon + WSO2-CARBON-PATCH-4.2.0 + 0007 + zip + true + target + + + + + + 9-unpack-kernel-patch + test + + unpack + + + + + org.wso2.carbon + WSO2-CARBON-PATCH-4.2.0 + 0008 + zip + true + target + + + + + + + + org.wso2.maven + carbon-p2-plugin + ${carbon.p2.plugin.version} + + + 2-p2-repo-generation + package + + p2-repo-gen + + + ${basedir}/target/p2-agent + file:${basedir}/target/p2-repo + file:${basedir}/target/p2-repo + true + true + + org.wso2.carbon:org.wso2.carbon.core.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.identity.application.mgt.server.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.core.runtime.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.logging.mgt.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.identity.relying.party.server.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.identity.user.profile.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.databridge.datapublisher.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.system.statistics.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.soaptracer.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.security.mgt.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.security.mgt.server.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.service.mgt.server.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.transport.mgt.feature:${carbon.platform.version} + + + org.wso2.carbon:org.wso2.carbon.transport.mail.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.transport.nhttp.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.transport.jms.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.message.flows.feature:${carbon.platform.version} + + + + org.wso2.carbon:org.wso2.carbon.datasource.server.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.tryit.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.registry.core.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.registry.core.server.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.registry.ui.menu.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.registry.resource.properties.feature:${carbon.platform.version} + + org.wso2.carbon:org.apache.synapse.wso2.feature:${synapse.version} + org.wso2.carbon:org.apache.synapse.transport.nhttp.feature:${synapse.version} + + + org.wso2.carbon:org.wso2.carbon.task.server.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.mediation.initializer.feature:${carbon.platform.version} + + + + org.wso2.carbon:org.wso2.carbon.mediation.statistics.feature:${carbon.platform.version} + + + + org.wso2.carbon:org.wso2.carbon.mediation.configadmin.feature:${carbon.platform.version} + + + org.wso2.carbon:org.wso2.carbon.mediation.tracer.feature:${carbon.platform.version} + + + + + + org.wso2.carbon:org.wso2.carbon.mediation.admin.feature:${carbon.platform.version} + + + + + + + org.wso2.carbon:org.wso2.carbon.forum.server.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.mediators.server.feature:${carbon.platform.version} + + + + + + org.wso2.am:org.wso2.am.styles.feature:${apimserver.version} + org.wso2.carbon:org.wso2.carbon.relay.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.relay.server.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.event.server.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.event.common.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.registry.associations.dependencies.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.registry.community.features.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.application.mgt.server.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.application.mgt.synapse.server.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.application.deployer.synapse.feature:${carbon.platform.version} + + + org.wso2.carbon:org.wso2.carbon.deployment.synchronizer.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.registry.community.features.server.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.throttle.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.identity.thrift.authentication.feature:${carbon.platform.version} + + + + + + org.jaggeryjs:org.jaggeryjs.feature:0.9.0.ALPHA5.wso2v1-SNAPSHOT + org.wso2.carbon:org.wso2.carbon.apimgt.feature:${apim.version} + + + + org.wso2.carbon:org.wso2.carbon.registry.extensions.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.registry.ws.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.registry.ui.menu.governance.feature:${carbon.platform.version} + + + + + org.wso2.carbon:org.wso2.carbon.governance.metadata.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.governance.lifecycle.management.feature:${carbon.platform.version} + + + + org.wso2.carbon:org.wso2.carbon.tenant.common.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.identity.authenticator.saml2.sso.server.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.identity.authenticator.saml2.sso.ui.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.registry.uddi.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.user.mgt.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.identity.core.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.identity.provider.server.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.identity.self.registration.server.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.identity.oauth.feature:${carbon.platform.version} + + + org.wso2.carbon:org.wso2.carbon.identity.application.authenticator.basicauth.server.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.identity.application.authenticator.samlsso.server.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.identity.application.authentication.framework.server.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.um.ws.service.server.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.um.ws.service.client.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.ntask.core.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.module.mgt.server.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.caching.server.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.rm.server.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.as.runtimes.cxf.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.webapp.mgt.server.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.webapp.mgt.server.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.claim.mgt.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.webapp.mgt.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.webapp.mgt.feature:${carbon.platform.version} + org.wso2.carbon:org.wso2.carbon.idp.mgt.feature:${carbon.platform.version} + + org.wso2.carbon:org.wso2.carbon.registry.contentsearch.feature:${carbon.platform.version} + + + + org.wso2.carbon:org.wso2.carbon.mediator.bam.feature:${carbon.platform.version} + + + + + + + publishing product + package + + publish-product + + + ${basedir}/carbon.product + + + ${basedir}/target/org.eclipse.equinox.executable_3.5.0.v20110530-7P7NFUFFLWUl76mart + + file:${basedir}/target/p2-repo + file:${basedir}/target/p2-repo + + + + creating-gateway-manager-profile + package + + materialize-product + + + ${basedir}/carbon.product + file:${basedir}/target/p2-repo + file:${basedir}/target/p2-repo + file:${basedir}/target/wso2carbon-core-${carbon.kernel.version}/repository/components + gateway-manager + + + + creating-gateway-worker-profile + package + + materialize-product + + + ${basedir}/carbon.product + file:${basedir}/target/p2-repo + file:${basedir}/target/p2-repo + file:${basedir}/target/wso2carbon-core-${carbon.kernel.version}/repository/components + gateway-worker + + + + + creating-key-manager-profile + package + + materialize-product + + + ${basedir}/carbon.product + file:${basedir}/target/p2-repo + file:${basedir}/target/p2-repo + file:${basedir}/target/wso2carbon-core-${carbon.kernel.version}/repository/components + api-key-manager + + + + + p2-profile-generation-api-publisher-profile + package + + materialize-product + + + ${basedir}/carbon.product + file:${basedir}/target/p2-repo + file:${basedir}/target/p2-repo + file:${basedir}/target/wso2carbon-core-${carbon.kernel.version}/repository/components + api-publisher + + + + + p2-profile-generation-api-store-profile + package + + materialize-product + + + ${basedir}/carbon.product + file:${basedir}/target/p2-repo + file:${basedir}/target/p2-repo + file:${basedir}/target/wso2carbon-core-${carbon.kernel.version}/repository/components + api-store + + + + + + 3-p2-profile-generation + package + + p2-profile-gen + + + default + ${basedir}/target/p2-agent + file:${basedir}/target/p2-repo + file:${basedir}/target/p2-repo + ${basedir}/target/wso2carbon-core-${carbon.kernel.version}/repository/components + true + + + org.wso2.carbon.identity.application.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.relying.party.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.as.runtimes.cxf.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.webapp.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.user.profile.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.webapp.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.ntask.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.logging.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.module.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.databridge.datapublisher.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.throttle.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.thrift.authentication.feature.group + ${carbon.platform.version} + + + org.apache.synapse.wso2.feature.group + ${synapse.version} + + + org.apache.synapse.transport.nhttp.feature.group + ${synapse.version} + + + + org.wso2.carbon.datasource.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.task.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.mediation.initializer.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.mediation.configadmin.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.mediation.statistics.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.mediation.tracer.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.application.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.mgt.synapse.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.deployer.synapse.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.system.statistics.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.soaptracer.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.security.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.security.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.service.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.mail.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.nhttp.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.jms.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.message.flows.feature.group + ${carbon.platform.version} + + + + + org.wso2.carbon.registry.uddi.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.core.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ui.menu.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ui.menu.governance.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.resource.properties.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.mediation.admin.feature.group + ${carbon.platform.version} + + + + + + org.wso2.carbon.mediators.server.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.relay.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.relay.server.feature.group + ${carbon.platform.version} + + + org.wso2.am.styles.feature.group + ${apimserver.version} + + + + org.wso2.carbon.event.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.event.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.associations.dependencies.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.community.features.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.provider.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.oauth.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.identity.application.authenticator.basicauth.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.application.authenticator.samlsso.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.application.authentication.framework.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.self.registration.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.tryit.feature.group + ${carbon.platform.version} + + + + + + + org.wso2.carbon.deployment.synchronizer.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.community.features.server.feature.group + ${carbon.platform.version} + + + + + org.wso2.carbon.registry.ws.feature.group + ${carbon.platform.version} + + + + org.jaggeryjs.feature.group + 0.9.0.ALPHA5.wso2v1-SNAPSHOT + + + org.wso2.carbon.apimgt.feature.group + ${apim.version} + + + + + org.wso2.carbon.registry.extensions.feature.group + ${carbon.platform.version} + + + + + + + org.wso2.carbon.governance.metadata.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.governance.lifecycle.management.feature.group + ${carbon.platform.version} + + + + + + + + + + org.wso2.carbon.user.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.um.ws.service.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.um.ws.service.client.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.claim.mgt.feature.group + ${carbon.platform.version} + + + + + org.wso2.carbon.tenant.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.authenticator.saml2.sso.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.authenticator.saml2.sso.ui.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.webapp.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.webapp.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.contentsearch.feature.group + ${carbon.platform.version} + + + + + org.wso2.carbon.mediator.bam.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.idp.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.forum.server.feature.group + ${carbon.platform.version} + + + + + + + + p2-profile-generation-for-gateway-manager-profile + package + + p2-profile-gen + + + gateway-manager + file:${basedir}/target/p2-repo + file:${basedir}/target/p2-repo + + ${basedir}/target/wso2carbon-core-${carbon.kernel.version}/repository/components + + true + + + org.wso2.carbon.core.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.core.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.core.runtime.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.ntask.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.logging.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.module.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.databridge.datapublisher.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.throttle.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.thrift.authentication.feature.group + ${carbon.platform.version} + + + org.apache.synapse.wso2.feature.group + ${synapse.version} + + + org.apache.synapse.transport.nhttp.feature.group + ${synapse.version} + + + org.wso2.carbon.datasource.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.task.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.mediation.initializer.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.mediation.configadmin.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.mediation.statistics.feature.group + ${carbon.platform.version} + + + + + org.wso2.carbon.mediation.tracer.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.mgt.synapse.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.deployer.synapse.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.security.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.security.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.service.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.mail.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.nhttp.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.jms.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.message.flows.feature.group + ${carbon.platform.version} + + + + + org.wso2.carbon.registry.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.core.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.uddi.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ui.menu.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ui.menu.governance.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.resource.properties.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.mediation.admin.feature.group + ${carbon.platform.version} + + + + + + org.wso2.carbon.mediators.server.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.relay.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.relay.server.feature.group + ${carbon.platform.version} + + + org.wso2.am.styles.feature.group + ${apimserver.version} + + + + org.wso2.carbon.event.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.event.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.associations.dependencies.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.provider.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.community.features.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.oauth.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.identity.self.registration.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.tryit.feature.group + ${carbon.platform.version} + + + + + + org.wso2.carbon.deployment.synchronizer.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.community.features.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ws.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.extensions.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.governance.metadata.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.governance.lifecycle.management.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.user.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.um.ws.service.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.um.ws.service.client.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.tenant.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.apimgt.gateway.feature.group + ${apim.version} + + + org.wso2.carbon.apimgt.core.feature.group + ${apim.version} + + + org.wso2.carbon.registry.extensions.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.registry.contentsearch.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.mediator.bam.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.identity.application.authentication.framework.server.feature.group + ${carbon.platform.version} + + + + + + + + + p2-profile-generation-for-gateway-worker-profile + package + + p2-profile-gen + + + gateway-worker + file:${basedir}/target/p2-repo + file:${basedir}/target/p2-repo + + ${basedir}/target/wso2carbon-core-${carbon.kernel.version}/repository/components + + true + + + org.wso2.carbon.core.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.core.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.core.runtime.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.ntask.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.logging.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.module.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.databridge.datapublisher.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.throttle.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.thrift.authentication.feature.group + ${carbon.platform.version} + + + org.apache.synapse.wso2.feature.group + ${synapse.version} + + + org.apache.synapse.transport.nhttp.feature.group + ${synapse.version} + + + org.wso2.carbon.datasource.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.task.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.mediation.initializer.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.mediation.configadmin.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.mediation.statistics.feature.group + ${carbon.platform.version} + + + + + org.wso2.carbon.mediation.tracer.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.mgt.synapse.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.deployer.synapse.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.security.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.security.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.service.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.mail.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.nhttp.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.jms.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.message.flows.feature.group + ${carbon.platform.version} + + + + + org.wso2.carbon.registry.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.core.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.uddi.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ui.menu.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ui.menu.governance.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.resource.properties.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.mediation.admin.feature.group + ${carbon.platform.version} + + + + + + org.wso2.carbon.mediators.server.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.relay.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.relay.server.feature.group + ${carbon.platform.version} + + + org.wso2.am.styles.feature.group + ${apimserver.version} + + + + org.wso2.carbon.event.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.event.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.associations.dependencies.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.provider.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.community.features.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.oauth.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.identity.self.registration.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.tryit.feature.group + ${carbon.platform.version} + + + + + + org.wso2.carbon.deployment.synchronizer.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.community.features.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ws.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.extensions.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.governance.metadata.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.governance.lifecycle.management.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.user.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.um.ws.service.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.um.ws.service.client.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.tenant.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.apimgt.gateway.feature.group + ${apim.version} + + + org.wso2.carbon.apimgt.core.feature.group + ${apim.version} + + + org.wso2.carbon.registry.extensions.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.registry.contentsearch.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.mediator.bam.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.identity.application.authentication.framework.server.feature.group + ${carbon.platform.version} + + + + + + + + + p2-profile-generation-for-api-store-profile + package + + p2-profile-gen + + + api-store + file:${basedir}/target/p2-repo + file:${basedir}/target/p2-repo + + ${basedir}/target/wso2carbon-core-${carbon.kernel.version}/repository/components + + true + + + org.wso2.carbon.core.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.user.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.user.profile.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.core.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.core.runtime.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.core.ui.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.as.runtimes.cxf.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.webapp.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.webapp.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.ntask.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.logging.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.module.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.databridge.datapublisher.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.throttle.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.thrift.authentication.feature.group + ${carbon.platform.version} + + + org.apache.synapse.wso2.feature.group + ${synapse.version} + + + org.apache.synapse.transport.nhttp.feature.group + ${synapse.version} + + + org.wso2.carbon.datasource.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.task.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.mediation.initializer.feature.group + ${carbon.platform.version} + + + + + org.wso2.carbon.mediation.configadmin.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.mediation.statistics.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.mediation.tracer.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.mgt.synapse.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.deployer.synapse.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.system.statistics.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.soaptracer.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.security.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.security.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.service.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.mail.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.nhttp.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.jms.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.message.flows.feature.group + ${carbon.platform.version} + + + + + + org.wso2.carbon.registry.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.uddi.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.core.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ui.menu.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ui.menu.governance.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.resource.properties.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.mediation.admin.feature.group + ${carbon.platform.version} + + + + + + org.wso2.carbon.mediators.server.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.relay.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.relay.server.feature.group + ${carbon.platform.version} + + + org.wso2.am.styles.feature.group + ${apimserver.version} + + + + org.wso2.carbon.event.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.event.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.associations.dependencies.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.community.features.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.provider.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.oauth.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.identity.application.authenticator.basicauth.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.application.authenticator.samlsso.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.application.authentication.framework.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.self.registration.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.tryit.feature.group + ${carbon.platform.version} + + + + + + + org.wso2.carbon.deployment.synchronizer.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.community.features.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ws.feature.group + ${carbon.platform.version} + + + org.jaggeryjs.feature.group + 0.9.0.ALPHA5.wso2v1-SNAPSHOT + + + org.wso2.carbon.apimgt.gateway.feature.group + ${apim.version} + + + org.wso2.carbon.apimgt.core.feature.group + ${apim.version} + + + org.wso2.carbon.apimgt.store.feature.group + ${apim.version} + + + org.wso2.carbon.registry.extensions.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.governance.metadata.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.governance.lifecycle.management.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.user.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.um.ws.service.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.um.ws.service.client.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.claim.mgt.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.tenant.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.authenticator.saml2.sso.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.authenticator.saml2.sso.ui.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.webapp.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.webapp.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.contentsearch.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.forum.server.feature.group + ${carbon.platform.version} + + + + + + + + + p2-profile-generation-for-api-publisher-profile + package + + p2-profile-gen + + + api-publisher + file:${basedir}/target/p2-repo + file:${basedir}/target/p2-repo + + ${basedir}/target/wso2carbon-core-${carbon.kernel.version}/repository/components + + true + + + org.wso2.carbon.core.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.core.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.core.runtime.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.core.ui.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.as.runtimes.cxf.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.webapp.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.webapp.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.ntask.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.logging.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.module.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.databridge.datapublisher.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.throttle.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.thrift.authentication.feature.group + ${carbon.platform.version} + + + org.apache.synapse.wso2.feature.group + ${synapse.version} + + + org.apache.synapse.transport.nhttp.feature.group + ${synapse.version} + + + org.wso2.carbon.datasource.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.task.server.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.mediation.initializer.feature.group + ${carbon.platform.version} + + + + + org.wso2.carbon.mediation.configadmin.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.mediation.statistics.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.mediation.tracer.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.mgt.synapse.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.deployer.synapse.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.system.statistics.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.soaptracer.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.security.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.security.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.service.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.mail.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.nhttp.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.jms.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.message.flows.feature.group + ${carbon.platform.version} + + + + + org.wso2.carbon.registry.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.uddi.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.core.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ui.menu.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ui.menu.governance.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.resource.properties.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.mediation.admin.feature.group + ${carbon.platform.version} + + + + + + + org.wso2.carbon.mediators.server.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.relay.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.relay.server.feature.group + ${carbon.platform.version} + + + org.wso2.am.styles.feature.group + ${apimserver.version} + + + + org.wso2.carbon.event.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.event.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.associations.dependencies.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.community.features.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.provider.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.oauth.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.identity.application.authenticator.basicauth.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.application.authenticator.samlsso.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.application.authentication.framework.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.self.registration.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.tryit.feature.group + ${carbon.platform.version} + + + + + + org.wso2.carbon.deployment.synchronizer.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.community.features.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ws.feature.group + ${carbon.platform.version} + + + org.jaggeryjs.feature.group + 0.9.0.ALPHA5.wso2v1-SNAPSHOT + + + org.wso2.carbon.apimgt.gateway.feature.group + ${apim.version} + + + org.wso2.carbon.apimgt.core.feature.group + ${apim.version} + + + org.wso2.carbon.apimgt.publisher.feature.group + ${apim.version} + + + org.wso2.carbon.registry.extensions.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.governance.metadata.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.governance.lifecycle.management.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.user.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.um.ws.service.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.um.ws.service.client.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.claim.mgt.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.tenant.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.authenticator.saml2.sso.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.authenticator.saml2.sso.ui.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.webapp.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.webapp.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.contentsearch.feature.group + ${carbon.platform.version} + + + + + + + + + + + p2-profile-generation-for-api-key-manager-profile + package + + p2-profile-gen + + + api-key-manager + file:${basedir}/target/p2-repo + file:${basedir}/target/p2-repo + + ${basedir}/target/wso2carbon-core-${carbon.kernel.version}/repository/components + + true + + + org.wso2.carbon.identity.application.authentication.framework.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.core.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.application.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.core.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.core.runtime.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.ntask.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.logging.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.module.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.databridge.datapublisher.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.throttle.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.thrift.authentication.feature.group + ${carbon.platform.version} + + + org.apache.synapse.wso2.feature.group + ${synapse.version} + + + org.apache.synapse.transport.nhttp.feature.group + ${synapse.version} + + + + org.wso2.carbon.datasource.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.task.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.mediation.initializer.feature.group + ${carbon.platform.version} + + + + + org.wso2.carbon.mediation.configadmin.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.mediation.statistics.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.mediation.tracer.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.mgt.synapse.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.application.deployer.synapse.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.system.statistics.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.soaptracer.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.security.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.security.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.service.mgt.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.mail.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.transport.nhttp.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.transport.jms.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.message.flows.feature.group + ${carbon.platform.version} + + + + + org.wso2.carbon.registry.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.uddi.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.core.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ui.menu.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ui.menu.governance.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.resource.properties.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.mediation.admin.feature.group + ${carbon.platform.version} + + + + + + org.wso2.carbon.mediators.server.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.relay.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.relay.server.feature.group + ${carbon.platform.version} + + + org.wso2.am.styles.feature.group + ${apimserver.version} + + + org.wso2.carbon.identity.provider.server.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.event.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.event.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.associations.dependencies.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.community.features.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.oauth.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.identity.self.registration.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.tryit.feature.group + ${carbon.platform.version} + + + + + + org.wso2.carbon.deployment.synchronizer.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.community.features.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.ws.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.registry.extensions.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.governance.metadata.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.governance.lifecycle.management.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.user.mgt.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.core.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.um.ws.service.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.um.ws.service.client.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.tenant.common.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.authenticator.saml2.sso.server.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.identity.authenticator.saml2.sso.ui.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.apimgt.core.feature.group + ${apim.version} + + + org.wso2.carbon.apimgt.gateway.feature.group + ${apim.version} + + + org.wso2.carbon.registry.extensions.feature.group + ${carbon.platform.version} + + + + org.wso2.carbon.registry.contentsearch.feature.group + ${carbon.platform.version} + + + org.wso2.carbon.idp.mgt.feature.group + ${carbon.platform.version} + + + + + + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + 1.1 + + + package + + + + + + + + + + run + + + + + + + + diff --git a/modules/samples/Billing/API_Manager_Analytics.tbox b/modules/samples/Billing/API_Manager_Analytics.tbox new file mode 100644 index 0000000000..c9140d57c8 Binary files /dev/null and b/modules/samples/Billing/API_Manager_Analytics.tbox differ diff --git a/modules/samples/Billing/billing-conf.xml b/modules/samples/Billing/billing-conf.xml new file mode 100644 index 0000000000..ec394f818c --- /dev/null +++ b/modules/samples/Billing/billing-conf.xml @@ -0,0 +1,16 @@ + + +050.0 +5102.0 +10150005.0 + + +0100.0 +10201.0 +20300002.0 + + +0100.5 +10200001.0 + + diff --git a/modules/samples/Data/UserPopulator.sql b/modules/samples/Data/UserPopulator.sql new file mode 100644 index 0000000000..708a16b83b --- /dev/null +++ b/modules/samples/Data/UserPopulator.sql @@ -0,0 +1,20 @@ +SET @Name = SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME = 'subscriber1'; +DELETE FROM UM_USER_ROLE where UM_USER_ID = @Name; +DELETE FROM UM_USER WHERE UM_USER_NAME ='subscriber1'; + +SET @Name = SELECT UM_ID FROM UM_USER WHERE UM_USER_NAME = 'provider1'; +DELETE FROM UM_USER_ROLE where UM_USER_ID = @Name; +DELETE FROM UM_USER WHERE UM_USER_NAME ='provider1'; + +-- Adding provider +INSERT INTO UM_USER (UM_USER_NAME ,UM_USER_PASSWORD ,UM_SALT_VALUE ,UM_REQUIRE_CHANGE , UM_CHANGED_TIME ,UM_TENANT_ID ) VALUES ('provider1','qsx45WkvN5vS0HCp4rGmTrRxaRsDF51VyjzzFHQjFmw=','wNZPdWDNF27y2ObAJNSchw==','FALSE',CURRENT_TIME(),-1234); + +SELECT 1, SET(@USER_ID, SCOPE_IDENTITY()); +INSERT INTO UM_USER_ROLE (UM_ROLE_ID, UM_USER_ID ,UM_TENANT_ID ) VALUES (1, @USER_ID,-1234); + +-- Adding subscriber +INSERT INTO UM_USER (UM_USER_NAME ,UM_USER_PASSWORD ,UM_SALT_VALUE ,UM_REQUIRE_CHANGE , UM_CHANGED_TIME ,UM_TENANT_ID ) VALUES ('subscriber1','Mx5VpNXKTxHv2WrWUPj7iUR9IfWs4qN18xYUV3sxo94=','Q3En4ZN+pVGk6UYkTx6SDQ==','FALSE',CURRENT_TIME(),-1234); + +SELECT 1, SET(@USER_ID, SCOPE_IDENTITY()); +INSERT INTO UM_USER_ROLE (UM_ROLE_ID, UM_USER_ID ,UM_TENANT_ID ) VALUES (1, @USER_ID,-1234); + diff --git a/modules/samples/Data/build.xml b/modules/samples/Data/build.xml new file mode 100644 index 0000000000..61444d8ea6 --- /dev/null +++ b/modules/samples/Data/build.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/samples/NTLMGrantClient/build.xml b/modules/samples/NTLMGrantClient/build.xml new file mode 100644 index 0000000000..a0e50d0a30 --- /dev/null +++ b/modules/samples/NTLMGrantClient/build.xml @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/Main.java b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/Main.java new file mode 100644 index 0000000000..f8482cac1f --- /dev/null +++ b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/Main.java @@ -0,0 +1,105 @@ +package org.wso2.carbon.grant.ntlm; + +import org.apache.catalina.Realm; +import org.wso2.carbon.grant.ntlm.utils.SimpleHttpRequest; +import org.wso2.carbon.grant.ntlm.utils.SimpleHttpResponse; +import org.wso2.carbon.grant.ntlm.utils.SimpleRealm; +import waffle.apache.NegotiateAuthenticator; +import waffle.util.Base64; +import waffle.windows.auth.IWindowsCredentialsHandle; +import waffle.windows.auth.impl.WindowsAccountImpl; +import waffle.windows.auth.impl.WindowsCredentialsHandleImpl; +import waffle.windows.auth.impl.WindowsSecurityContextImpl; +import org.wso2.carbon.grant.ntlm.utils.SimpleContext; +import org.apache.axiom.util.base64.Base64Utils; +import org.apache.felix.gogo.command.Base64Encoder; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.axiom.util.base64.Base64Utils; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.protocol.BasicHttpContext; +import org.apache.http.protocol.HttpContext; +import org.apache.http.util.EntityUtils; +import org.wso2.carbon.grant.ntlm.utils.CommandHandler; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; + +import java.io.IOException; + + +public class Main { + static NegotiateAuthenticator _authenticator = null; + + public static void main(String[] args) { + + System.out.println("Started NTLM grant client................"); + + CommandHandler.setInputs(args); + + _authenticator = new NegotiateAuthenticator(); + SimpleContext ctx = new SimpleContext(); + Realm realm = new SimpleRealm(); + ctx.setRealm(realm); + _authenticator.setContainer(ctx); + + String securityPackage = "Negotiate"; + boolean autoGenerate=CommandHandler.isTokenAutoGenerated(); + String clientToken=""; + if(autoGenerate){ + IWindowsCredentialsHandle clientCredentials = null; + WindowsSecurityContextImpl clientContext = null; + // client credentials handle + clientCredentials = WindowsCredentialsHandleImpl.getCurrent(securityPackage); + clientCredentials.initialize(); + // initial client security context + clientContext = new WindowsSecurityContextImpl(); + clientContext.setPrincipalName(WindowsAccountImpl.getCurrentUsername()); + System.out.println("username"+WindowsAccountImpl.getCurrentUsername()); + clientContext.setCredentialsHandle(clientCredentials.getHandle()); + clientContext.setSecurityPackage(securityPackage); + clientContext.initialize(null, null, WindowsAccountImpl.getCurrentUsername()); + // negotiate + + clientToken = Base64.encode(clientContext.getToken()); + System.out.println("Generated NTLM token:"+clientToken); + } else{ + clientToken=CommandHandler.getNTLMToken(); + System.out.println("NTLM token: "+clientToken); + } + try { + Thread.sleep(4000); + HttpClient httpclient = new DefaultHttpClient(); + byte[] userKey=(CommandHandler.getConsumerKey()+":"+CommandHandler.getConsumerSecret()).getBytes(); + String encoding = Base64Utils.encode(userKey); + HttpPost httppost = new HttpPost(CommandHandler.getTokenendpoint()); + httppost.setHeader("Authorization", "Basic " + encoding); + List paramVals = new ArrayList(); + paramVals.add(new BasicNameValuePair("grant_type", "iwa:ntlm")); + paramVals.add(new BasicNameValuePair("windows_token", clientToken)); + + System.out.println("executing token API request " + httppost.getRequestLine()); + HttpResponse response = null; + httppost.setEntity(new UrlEncodedFormEntity(paramVals, "UTF-8")); + response = httpclient.execute(httppost); + HttpEntity entity = response.getEntity(); + String responseString = EntityUtils.toString(entity, "UTF-8"); + System.out.println(responseString); + System.out.println("Completed NTLM grant client................"); + System.exit(0); + } catch (IOException e) { + e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + }// catch (InterruptedException e) { + catch (InterruptedException e) { + e.printStackTrace(); + } + // e.printStackTrace(); + // } + }} diff --git a/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/CommandHandler.java b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/CommandHandler.java new file mode 100644 index 0000000000..8d2745d4de --- /dev/null +++ b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/CommandHandler.java @@ -0,0 +1,113 @@ +/* +* Copyright (c) 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.carbon.grant.ntlm.utils; + +import java.util.HashMap; +import java.util.Map; + +public class CommandHandler { + + private static final Map inputs = new HashMap(); + + public static boolean setInputs(String[] arguments) { + + if (arguments.length == 0) { + printMessage(); + return false; + } + if (arguments.length == 1 && arguments[0].equals("--help")) { + printMessage(); + return false; + } + + // now loop through the arguments list to capture the options + for (int i = 0; i < arguments.length; i++) { + if (arguments[i].equals("-url")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Toekn endpoint is missing"); + } + inputs.put("-url", arguments[++i]); + } else if (arguments[i].equals("-auto")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("The flag to generate NTLM token/not is missing"); + } + inputs.put("-auto", arguments[++i]); + + + } else if (arguments[i].equals("-nToken")) { + if (arguments.length - 1 == i && !Boolean.parseBoolean(inputs.get("-auto"))) { + throw new RuntimeException("NTLM token is missing"); + } + inputs.put("-nToken", arguments[++i]); + + } else if (arguments[i].equals("-key")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Consumer Key is missing"); + } + inputs.put("-key", arguments[++i]); + + } else if (arguments[i].equals("-secret")) { + if (arguments.length - 1 == i) { + throw new RuntimeException("Consumer Secret is missing"); + } + inputs.put("-secret", arguments[++i]); + } + } + + return true; + } + + + private static void printMessage() { + System.out.println("Usage: NTLM Grant Type-client "); + System.out.println("Valid options are:"); + System.out.println("\t-url :\t(Required) The token endpoint."); + System.out.println("\t-auto :\t(Required) Generate the NTLM token/not."); + System.out.println("\t-nToken :\t(Optional) The NTLM token."); + System.out.println("\t-key :\t(Required) The consumer key."); + System.out.println("\t-secret:\t(Required) The consumer secret."); + System.out.println(); + System.out.println("Example to execute the NTLM grant client"); + System.out.println("\te.g: ant -url TokenURL -nToken ntlm_token -key consumerKey -secret consumerSecret"); + } + + + + public static String getTokenendpoint() { + return inputs.get("-url"); + } + + public static String getNTLMToken() { + return inputs.get("-nToken"); + } + + public static String getConsumerKey() { + return inputs.get("-key"); + } + + public static String getConsumerSecret() { + return inputs.get("-secret"); + } + + public static boolean isTokenAutoGenerated() { + return Boolean.parseBoolean(inputs.get("-auto")); + } + + +} + diff --git a/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleContext.java b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleContext.java new file mode 100644 index 0000000000..a1b0804b13 --- /dev/null +++ b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleContext.java @@ -0,0 +1,1174 @@ +/* +*Copyright (c) 2005-2013, 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.carbon.grant.ntlm.utils; + + +import org.apache.catalina.*; +import org.apache.catalina.connector.Request; +import org.apache.catalina.connector.Response; +import org.apache.catalina.core.ApplicationServletRegistration; +import org.apache.catalina.util.CharsetMapper; +import org.apache.juli.logging.Log; +import org.apache.tomcat.JarScanner; +import org.apache.tomcat.util.http.mapper.Mapper; + +import javax.management.ObjectName; +import javax.naming.directory.DirContext; +import javax.servlet.*; +import java.beans.PropertyChangeListener; +import java.io.IOException; + + +import java.net.URL; +import java.util.Locale; +import java.util.Set; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.descriptor.JspConfigDescriptor; + +import org.apache.catalina.AccessLog; +import org.apache.catalina.Cluster; +import org.apache.catalina.Container; +import org.apache.catalina.ContainerListener; +import org.apache.catalina.Context; +import org.apache.catalina.Loader; +import org.apache.catalina.Manager; +import org.apache.catalina.Pipeline; +import org.apache.catalina.Realm; +import org.apache.catalina.Wrapper; +import org.apache.catalina.deploy.ApplicationParameter; +import org.apache.catalina.deploy.ErrorPage; +import org.apache.catalina.deploy.FilterDef; +import org.apache.catalina.deploy.FilterMap; +import org.apache.catalina.deploy.LoginConfig; +import org.apache.catalina.deploy.NamingResources; +import org.apache.catalina.deploy.SecurityConstraint; + + +public class SimpleContext implements Context { + + private Realm _realm = null; + private ServletContext _servletContext = new SimpleServletContext(); + + @Override + public void addApplicationListener(String arg0) { + + } + + @Override + public void addApplicationParameter(ApplicationParameter arg0) { + + } + + @Override + public void addConstraint(SecurityConstraint arg0) { + + } + + @Override + public void addErrorPage(ErrorPage arg0) { + + } + + @Override + public void addFilterDef(FilterDef arg0) { + + } + + @Override + public void addFilterMap(FilterMap arg0) { + + } + + @Override + public void addFilterMapBefore(FilterMap filterMap) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void addInstanceListener(String arg0) { + + } + + //@Override + public void addJspMapping(String arg0) { + + } + + @Override + public void addLocaleEncodingMappingParameter(String arg0, String arg1) { + + } + + @Override + public void addMimeMapping(String arg0, String arg1) { + + } + + @Override + public void addParameter(String arg0, String arg1) { + + } + + @Override + public void addRoleMapping(String arg0, String arg1) { + + } + + @Override + public void addSecurityRole(String arg0) { + + } + + @Override + public void addServletMapping(String arg0, String arg1) { + + } + + @Override + public void addServletMapping(String s, String s2, boolean b) { + //To change body of implemented methods use File | Settings | File Templates. + } + + + public void addTaglib(String arg0, String arg1) { + + } + + @Override + public void addWatchedResource(String arg0) { + + } + + @Override + public void addWelcomeFile(String arg0) { + + } + + @Override + public void addWrapperLifecycle(String arg0) { + + } + + @Override + public void addWrapperListener(String arg0) { + + } + + @Override + public Wrapper createWrapper() { + return null; + } + + @Override + public String[] findApplicationListeners() { + return new String[0]; + } + + @Override + public ApplicationParameter[] findApplicationParameters() { + return new ApplicationParameter[0]; + } + + @Override + public SecurityConstraint[] findConstraints() { + return new SecurityConstraint[0]; + } + + @Override + public ErrorPage findErrorPage(int arg0) { + return null; + } + + @Override + public ErrorPage findErrorPage(String arg0) { + return null; + } + + @Override + public ErrorPage[] findErrorPages() { + return new ErrorPage[0]; + } + + @Override + public FilterDef findFilterDef(String arg0) { + return null; + } + + @Override + public FilterDef[] findFilterDefs() { + return new FilterDef[0]; + } + + @Override + public FilterMap[] findFilterMaps() { + return new FilterMap[0]; + } + + @Override + public String[] findInstanceListeners() { + return new String[0]; + } + + @Override + public String findMimeMapping(String arg0) { + return null; + } + + @Override + public String[] findMimeMappings() { + return new String[0]; + } + + @Override + public String findParameter(String arg0) { + return null; + } + + @Override + public String[] findParameters() { + return new String[0]; + } + + @Override + public String findRoleMapping(String arg0) { + return null; + } + + @Override + public boolean findSecurityRole(String arg0) { + return false; + } + + @Override + public String[] findSecurityRoles() { + return new String[0]; + } + + @Override + public String findServletMapping(String arg0) { + return null; + } + + @Override + public String[] findServletMappings() { + return new String[0]; + } + + @Override + public String findStatusPage(int arg0) { + return null; + } + + @Override + public int[] findStatusPages() { + return new int[0]; + } + + //@Override + public String findTaglib(String arg0) { + return null; + } + + // @Override + public String[] findTaglibs() { + return new String[0]; + } + + @Override + public String[] findWatchedResources() { + return new String[0]; + } + + @Override + public boolean findWelcomeFile(String arg0) { + return false; + } + + @Override + public String[] findWelcomeFiles() { + return new String[0]; + } + + @Override + public String[] findWrapperLifecycles() { + return new String[0]; + } + + @Override + public String[] findWrapperListeners() { + return new String[0]; + } + + @Override + public boolean fireRequestInitEvent(ServletRequest servletRequest) { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public boolean fireRequestDestroyEvent(ServletRequest servletRequest) { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public String getAltDDName() { + return null; + } + + @Override + public boolean getAllowCasualMultipartParsing() { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setAllowCasualMultipartParsing(boolean b) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public Object[] getApplicationEventListeners() { + return new Object[0]; + } + + @Override + public Object[] getApplicationLifecycleListeners() { + return new Object[0]; + } + + @Override + public boolean getAvailable() { + return false; + } + + @Override + public CharsetMapper getCharsetMapper() { + return null; + } + + @Override + public URL getConfigFile() { + return null; + } + + @Override + public void setConfigFile(URL url) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public boolean getConfigured() { + return false; + } + + @Override + public boolean getCookies() { + return false; + } + + @Override + public boolean getCrossContext() { + return false; + } + + @Override + public String getDisplayName() { + return null; + } + + @Override + public boolean getDistributable() { + return false; + } + + @Override + public String getDocBase() { + return null; + } + + @Override + public String getEncodedPath() { + return null; + } + + @Override + public boolean getIgnoreAnnotations() { + return false; + } + + @Override + public LoginConfig getLoginConfig() { + return null; + } + + @Override + public Mapper getMapper() { + return null; + } + + @Override + public NamingResources getNamingResources() { + return null; + } + + @Override + public boolean getOverride() { + return false; + } + + @Override + public String getPath() { + return null; + } + + @Override + public boolean getPrivileged() { + return false; + } + + @Override + public String getPublicId() { + return null; + } + + @Override + public boolean getReloadable() { + return false; + } + + @Override + public ServletContext getServletContext() { + return _servletContext; + } + + @Override + public int getSessionTimeout() { + return 0; + } + + @Override + public boolean getSwallowOutput() { + return false; + } + + @Override + public boolean getTldNamespaceAware() { + return false; + } + + @Override + public boolean getTldValidation() { + return false; + } + + @Override + public boolean getUseHttpOnly() { + return false; + } + + @Override + public String getWrapperClass() { + return null; + } + + @Override + public boolean getXmlNamespaceAware() { + return false; + } + + @Override + public boolean getXmlValidation() { + return false; + } + + @Override + public void reload() { + + } + + @Override + public void removeApplicationListener(String arg0) { + + } + + @Override + public void removeApplicationParameter(String arg0) { + + } + + @Override + public void removeConstraint(SecurityConstraint arg0) { + + } + + @Override + public void removeErrorPage(ErrorPage arg0) { + + } + + @Override + public void removeFilterDef(FilterDef arg0) { + + } + + @Override + public void removeFilterMap(FilterMap arg0) { + + } + + @Override + public void removeInstanceListener(String arg0) { + + } + + @Override + public void removeMimeMapping(String arg0) { + + } + + @Override + public void removeParameter(String arg0) { + + } + + @Override + public void removeRoleMapping(String arg0) { + + } + + @Override + public void removeSecurityRole(String arg0) { + + } + + @Override + public void removeServletMapping(String arg0) { + + } + + //@Override + public void removeTaglib(String arg0) { + + } + + @Override + public void removeWatchedResource(String arg0) { + + } + + @Override + public void removeWelcomeFile(String arg0) { + + } + + @Override + public void removeWrapperLifecycle(String arg0) { + + } + + @Override + public void removeWrapperListener(String arg0) { + + } + + @Override + public String getRealPath(String s) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public int getEffectiveMajorVersion() { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setEffectiveMajorVersion(int i) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public int getEffectiveMinorVersion() { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setEffectiveMinorVersion(int i) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public JspConfigDescriptor getJspConfigDescriptor() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void addResourceJarUrl(URL url) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void addServletContainerInitializer(ServletContainerInitializer servletContainerInitializer, Set> classes) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public boolean getPaused() { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public boolean isServlet22() { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public Set addServletSecurity(ApplicationServletRegistration applicationServletRegistration, ServletSecurityElement servletSecurityElement) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setResourceOnlyServlets(String s) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public String getResourceOnlyServlets() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public boolean isResourceOnlyServlet(String s) { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public String getBaseName() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setWebappVersion(String s) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public String getWebappVersion() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setFireRequestListenersOnForwards(boolean b) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public boolean getFireRequestListenersOnForwards() { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setPreemptiveAuthentication(boolean b) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public boolean getPreemptiveAuthentication() { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setSendRedirectBody(boolean b) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public boolean getSendRedirectBody() { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setAltDDName(String arg0) { + + } + + @Override + public void setApplicationEventListeners(Object[] arg0) { + + } + + @Override + public void setApplicationLifecycleListeners(Object[] arg0) { + + } + + //@Override + public void setAvailable(boolean arg0) { + + } + + @Override + public void setCharsetMapper(CharsetMapper arg0) { + + } + + @Override + public String getCharset(Locale locale) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + //@Override + public void setConfigFile(String arg0) { + + } + + @Override + public void setConfigured(boolean arg0) { + + } + + @Override + public void setCookies(boolean arg0) { + + } + + @Override + public void setCrossContext(boolean arg0) { + + } + + @Override + public void setDisplayName(String arg0) { + + } + + @Override + public void setDistributable(boolean arg0) { + + } + + @Override + public void setDocBase(String arg0) { + + } + + @Override + public void setIgnoreAnnotations(boolean arg0) { + + } + + @Override + public void setLoginConfig(LoginConfig arg0) { + + } + + @Override + public void setNamingResources(NamingResources arg0) { + + } + + @Override + public void setOverride(boolean arg0) { + + } + + @Override + public void setPath(String arg0) { + + } + + @Override + public void setPrivileged(boolean arg0) { + + } + + @Override + public void setPublicId(String arg0) { + + } + + @Override + public void setReloadable(boolean arg0) { + + } + + @Override + public void setSessionTimeout(int arg0) { + + } + + @Override + public boolean getSwallowAbortedUploads() { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setSwallowAbortedUploads(boolean b) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setSwallowOutput(boolean arg0) { + + } + + @Override + public void setTldNamespaceAware(boolean arg0) { + + } + + @Override + public JarScanner getJarScanner() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setJarScanner(JarScanner jarScanner) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public Authenticator getAuthenticator() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setLogEffectiveWebXml(boolean b) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public boolean getLogEffectiveWebXml() { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setTldValidation(boolean arg0) { + + } + + @Override + public void setUseHttpOnly(boolean arg0) { + + } + + @Override + public void setWrapperClass(String arg0) { + + } + + @Override + public void setXmlNamespaceAware(boolean arg0) { + + } + + @Override + public void setXmlValidation(boolean arg0) { + + } + + @Override + public void addChild(Container arg0) { + + } + + @Override + public void addContainerListener(ContainerListener arg0) { + + } + + @Override + public void addPropertyChangeListener(PropertyChangeListener arg0) { + + } + + @Override + public void backgroundProcess() { + + } + + @Override + public Container findChild(String arg0) { + return null; + } + + @Override + public Container[] findChildren() { + return new Container[0]; + } + + @Override + public ContainerListener[] findContainerListeners() { + return new ContainerListener[0]; + } + + @Override + public int getBackgroundProcessorDelay() { + return 0; + } + + @Override + public Cluster getCluster() { + return null; + } + + @Override + public String getInfo() { + return null; + } + + @Override + public Loader getLoader() { + return null; + } + + @Override + public Log getLogger() { + return null; + } + + @Override + public Manager getManager() { + return null; + } + + @Override + public Object getMappingObject() { + return null; + } + + @Override + public String getName() { + return null; + } + + @Override + public ObjectName getObjectName() { + return null; + } + + @Override + public Container getParent() { + return null; + } + + @Override + public ClassLoader getParentClassLoader() { + return null; + } + + @Override + public Pipeline getPipeline() { + return null; + } + + @Override + public Realm getRealm() { + return _realm; + } + + @Override + public DirContext getResources() { + return null; + } + + @Override + public void invoke(Request arg0, Response arg1) throws IOException, + ServletException { + + } + + @Override + public void removeChild(Container arg0) { + + } + + @Override + public void removeContainerListener(ContainerListener arg0) { + + } + + @Override + public void removePropertyChangeListener(PropertyChangeListener arg0) { + + } + + @Override + public void fireContainerEvent(String s, Object o) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setBackgroundProcessorDelay(int arg0) { + + } + + @Override + public void setCluster(Cluster arg0) { + + } + + @Override + public void setLoader(Loader arg0) { + + } + + @Override + public void setManager(Manager arg0) { + + } + + @Override + public void setName(String arg0) { + + } + + @Override + public void setParent(Container arg0) { + + } + + @Override + public void setParentClassLoader(ClassLoader arg0) { + + } + + @Override + public void setRealm(Realm realm) { + _realm = realm; + } + + @Override + public void setResources(DirContext arg0) { + + } + + @Override + public String getSessionCookieDomain() { + return null; + } + + @Override + public String getSessionCookieName() { + return null; + } + + @Override + public String getSessionCookiePath() { + return null; + } + + @Override + public void setSessionCookieDomain(String arg0) { + + } + + @Override + public void setSessionCookieName(String arg0) { + + } + + @Override + public void setSessionCookiePath(String arg0) { + + } + + @Override + public boolean getSessionCookiePathUsesTrailingSlash() { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setSessionCookiePathUsesTrailingSlash(boolean b) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public AccessLog getAccessLog() { + return null; + } + + @Override + public int getStartStopThreads() { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setStartStopThreads(int i) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void logAccess(Request arg0, Response arg1, long arg2, boolean arg3) { + + } + + //@Override + public boolean isDisableURLRewriting() { + return false; + } + + //@Override + public void setDisableURLRewriting(boolean arg0) { + + } + + @Override + public void addLifecycleListener(LifecycleListener lifecycleListener) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public LifecycleListener[] findLifecycleListeners() { + return new LifecycleListener[0]; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void removeLifecycleListener(LifecycleListener lifecycleListener) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void init() throws LifecycleException { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void start() throws LifecycleException { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void stop() throws LifecycleException { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void destroy() throws LifecycleException { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public LifecycleState getState() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public String getStateName() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } +} diff --git a/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleHttpRequest.java b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleHttpRequest.java new file mode 100644 index 0000000000..167d824043 --- /dev/null +++ b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleHttpRequest.java @@ -0,0 +1,181 @@ +/* +*Copyright (c) 2005-2013, 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.carbon.grant.ntlm.utils; + +import org.apache.catalina.connector.Request; + +import javax.servlet.http.HttpSession; +import java.security.Principal; +import java.util.HashMap; +import java.util.Map; + + +public class SimpleHttpRequest extends Request { + + private static int _remotePort_s = 0; + + private String _requestURI = null; + private String _queryString = null; + private String _remoteUser = null; + private String _method = "GET"; + private String _remoteHost = null; + private String _remoteAddr = null; + private int _remotePort = -1; + private Map _headers = new HashMap(); + private Map _parameters = new HashMap(); + private byte[] _content = null; + private HttpSession _session = new SimpleHttpSession(); + private Principal _principal = null; + + public SimpleHttpRequest() { + super(); + _remotePort = nextRemotePort(); + } + + public synchronized static int nextRemotePort() { + return ++_remotePort_s; + } + + public synchronized static void resetRemotePort() { + _remotePort_s = 0; + } + + //@Override + public void addHeader(String headerName, String headerValue) { + _headers.put(headerName, headerValue); + } + + @Override + public String getHeader(String headerName) { + return _headers.get(headerName); + } + + @Override + public String getMethod() { + return _method; + } + + @Override + public int getContentLength() { + return _content == null ? -1 : _content.length; + } + + @Override + public int getRemotePort() { + return _remotePort; + } + + // @Override + public void setMethod(String methodName) { + _method = methodName; + } + + // @Override + public void setContentLength(int length) { + _content = new byte[length]; + } + + public void setRemoteUser(String username) { + _remoteUser = username; + } + + @Override + public String getRemoteUser() { + return _remoteUser; + } + + @Override + public HttpSession getSession() { + return _session; + } + + @Override + public HttpSession getSession(boolean create) { + if (_session == null && create) { + _session = new SimpleHttpSession(); + } + return _session; + } + + @Override + public String getQueryString() { + return _queryString; + } + + //@Override + public void setQueryString(String queryString) { + _queryString = queryString; + if (_queryString != null) { + for (String eachParameter : _queryString.split("[&]")) { + String[] pair = eachParameter.split("="); + String value = (pair.length == 2) ? pair[1] : ""; + addParameter(pair[0], value); + } + } + } + + //@Override + public void setRequestURI(String uri) { + _requestURI = uri; + } + + @Override + public String getRequestURI() { + return _requestURI; + } + + @Override + public String getParameter(String parameterName) { + return _parameters.get(parameterName); + } + + public void addParameter(String parameterName, String parameterValue) { + _parameters.put(parameterName, parameterValue); + } + + @Override + public String getRemoteHost() { + return _remoteHost; + } + + @Override + public void setRemoteHost(String remoteHost) { + _remoteHost = remoteHost; + } + + @Override + public String getRemoteAddr() { + return _remoteAddr; + } + + @Override + public void setRemoteAddr(String remoteAddr) { + _remoteAddr = remoteAddr; + } + + @Override + public Principal getUserPrincipal() { + return _principal; + } + + @Override + public void setUserPrincipal(Principal principal) { + _principal = principal; + } +} diff --git a/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleHttpResponse.java b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleHttpResponse.java new file mode 100644 index 0000000000..764d697eb1 --- /dev/null +++ b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleHttpResponse.java @@ -0,0 +1,123 @@ +/* +*Copyright (c) 2005-2013, 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.carbon.grant.ntlm.utils; + +import org.apache.catalina.connector.Response; + +import java.util.*; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author dblock[at]dblock[dot]org + */ +public class SimpleHttpResponse extends Response { + private int _status = 500; + private Map> _headers = new HashMap>(); + + @Override + public int getStatus() { + return _status; + } + + @Override + public void addHeader(String headerName, String headerValue) { + List current = _headers.get(headerName); + if (current == null) + current = new ArrayList(); + current.add(headerValue); + _headers.put(headerName, current); + } + + @Override + public void setHeader(String headerName, String headerValue) { + List current = _headers.get(headerName); + if (current == null) { + current = new ArrayList(); + } else { + current.clear(); + } + current.add(headerValue); + _headers.put(headerName, current); + } + + @Override + public void setStatus(int value) { + _status = value; + } + + public String getStatusString() { + if (_status == 401) { + return "Unauthorized"; + } + return "Unknown"; + } + + @Override + public void flushBuffer() { + System.out.println(_status + " " + getStatusString()); + for (String header : _headers.keySet()) { + for (String headerValue : _headers.get(header)) { + System.out.println(header + ": " + headerValue); + } + } + } + + //@Override + public String[] getHeaderValues(String headerName) { + List headerValues = _headers.get(headerName); + return headerValues == null ? null : headerValues + .toArray(new String[0]); + } + + @Override + public String getHeader(String headerName) { + List headerValues = _headers.get(headerName); + if (headerValues == null) { + return null; + } + StringBuilder sb = new StringBuilder(); + for (String headerValue : headerValues) { + if (sb.length() > 0) { + sb.append(", "); + } + sb.append(headerValue); + } + return sb.toString(); + } + + @Override + public Collection getHeaderNames() { + return _headers.keySet(); + } + + @Override + public void sendError(int rc, String message) { + _status = rc; + } + + @Override + public void sendError(int rc) { + _status = rc; + } +} diff --git a/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleHttpSession.java b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleHttpSession.java new file mode 100644 index 0000000000..acb5aaad46 --- /dev/null +++ b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleHttpSession.java @@ -0,0 +1,119 @@ +/* +*Copyright (c) 2005-2013, 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.carbon.grant.ntlm.utils; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpSession; +import javax.servlet.http.HttpSessionContext; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +/** + * Simple Http Session + */ +@SuppressWarnings("deprecation") +public class SimpleHttpSession implements HttpSession { + + private Map _attributes = new HashMap(); + + @Override + public Object getAttribute(String attributeName) { + return _attributes.get(attributeName); + } + + @Override + public Enumeration getAttributeNames() { + return null; + } + + @Override + public long getCreationTime() { + return 0; + } + + @Override + public String getId() { + return null; + } + + @Override + public long getLastAccessedTime() { + return 0; + } + + @Override + public int getMaxInactiveInterval() { + return 0; + } + + @Override + public ServletContext getServletContext() { + return null; + } + + @Override + public HttpSessionContext getSessionContext() { + return null; + } + + @Override + public Object getValue(String arg0) { + return null; + } + + @Override + public String[] getValueNames() { + return new String[0]; + } + + @Override + public void invalidate() { + + } + + @Override + public boolean isNew() { + return false; + } + + @Override + public void putValue(String arg0, Object arg1) { + } + + @Override + public void removeAttribute(String attributeName) { + _attributes.remove(attributeName); + } + + @Override + public void removeValue(String arg0) { + + } + + @Override + public void setAttribute(String attributeName, Object attributeValue) { + _attributes.put(attributeName, attributeValue); + } + + @Override + public void setMaxInactiveInterval(int arg0) { + + } +} diff --git a/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleRealm.java b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleRealm.java new file mode 100644 index 0000000000..f32fe3fc29 --- /dev/null +++ b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleRealm.java @@ -0,0 +1,41 @@ +/* +*Copyright (c) 2005-2013, 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.carbon.grant.ntlm.utils; + +import org.apache.catalina.realm.RealmBase; + +import java.security.Principal; + +public class SimpleRealm extends RealmBase { + + @Override + protected String getName() { + return "simpleRealm"; + } + + @Override + protected String getPassword(String arg0) { + return null; + } + + @Override + protected Principal getPrincipal(String arg0) { + return null; + } +} diff --git a/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleRequestDispatcher.java b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleRequestDispatcher.java new file mode 100644 index 0000000000..577b0c8bc5 --- /dev/null +++ b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleRequestDispatcher.java @@ -0,0 +1,50 @@ +/* +*Copyright (c) 2005-2013, 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.carbon.grant.ntlm.utils; + +import java.io.IOException; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletResponse; + + +public class SimpleRequestDispatcher implements RequestDispatcher { + + private String _url; + + public SimpleRequestDispatcher(String url) { + _url = url; + } + + @Override + public void forward(ServletRequest request, ServletResponse response) + throws ServletException, IOException { + HttpServletResponse httpResponse = (HttpServletResponse) response; + httpResponse.setStatus(304); + httpResponse.addHeader("Location", _url); + } + + @Override + public void include(ServletRequest request, ServletResponse response) + throws ServletException, IOException { + } +} diff --git a/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleServletContext.java b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleServletContext.java new file mode 100644 index 0000000000..a955c17620 --- /dev/null +++ b/modules/samples/NTLMGrantClient/src/org/wso2/carbon/grant/ntlm/utils/SimpleServletContext.java @@ -0,0 +1,294 @@ +/* +*Copyright (c) 2005-2013, 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.carbon.grant.ntlm.utils; + + +import javax.servlet.*; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.*; + +import java.util.Enumeration; +import java.util.Set; + +import javax.servlet.RequestDispatcher; +import javax.servlet.Servlet; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.descriptor.JspConfigDescriptor; + + +public class SimpleServletContext implements ServletContext { + + @Override + public Object getAttribute(String arg0) { + return null; + } + + @Override + public Enumeration getAttributeNames() { + return null; + } + + @Override + public ServletContext getContext(String arg0) { + return null; + } + + @Override + public String getContextPath() { + return null; + } + + @Override + public String getInitParameter(String arg0) { + return null; + } + + @Override + public Enumeration getInitParameterNames() { + return null; + } + + @Override + public boolean setInitParameter(String s, String s2) { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public int getMajorVersion() { + return 0; + } + + @Override + public String getMimeType(String arg0) { + return null; + } + + @Override + public int getMinorVersion() { + return 0; + } + + @Override + public int getEffectiveMajorVersion() { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public int getEffectiveMinorVersion() { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public RequestDispatcher getNamedDispatcher(String name) { + return null; + } + + @Override + public String getRealPath(String arg0) { + return null; + } + + @Override + public RequestDispatcher getRequestDispatcher(String url) { + return new SimpleRequestDispatcher(url); + } + + @Override + public URL getResource(String arg0) throws MalformedURLException { + return null; + } + + @Override + public InputStream getResourceAsStream(String arg0) { + return null; + } + + @Override + public Set getResourcePaths(String arg0) { + return null; + } + + @Override + public String getServerInfo() { + return null; + } + + @Override + public Servlet getServlet(String arg0) throws ServletException { + return null; + } + + @Override + public String getServletContextName() { + return null; + } + + @Override + public ServletRegistration.Dynamic addServlet(String s, String s2) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public ServletRegistration.Dynamic addServlet(String s, Servlet servlet) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public ServletRegistration.Dynamic addServlet(String s, Class aClass) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public T createServlet(Class tClass) throws ServletException { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public ServletRegistration getServletRegistration(String s) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public Map getServletRegistrations() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public FilterRegistration.Dynamic addFilter(String s, String s2) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public FilterRegistration.Dynamic addFilter(String s, Filter filter) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public FilterRegistration.Dynamic addFilter(String s, Class aClass) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public T createFilter(Class tClass) throws ServletException { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public FilterRegistration getFilterRegistration(String s) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public Map getFilterRegistrations() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public SessionCookieConfig getSessionCookieConfig() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setSessionTrackingModes(Set sessionTrackingModes) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public Set getDefaultSessionTrackingModes() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public Set getEffectiveSessionTrackingModes() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void addListener(String s) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void addListener(T t) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void addListener(Class aClass) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public T createListener(Class tClass) throws ServletException { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public JspConfigDescriptor getJspConfigDescriptor() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public ClassLoader getClassLoader() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void declareRoles(String... strings) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public Enumeration getServletNames() { + return null; + } + + @Override + public Enumeration getServlets() { + return null; + } + + @Override + public void log(String arg0) { + + } + + @Override + public void log(Exception arg0, String arg1) { + + } + + @Override + public void log(String arg0, Throwable arg1) { + + } + + @Override + public void removeAttribute(String arg0) { + + } + + @Override + public void setAttribute(String arg0, Object arg1) { + + } +} diff --git a/modules/samples/PizzaShack/PizzaShack.zip b/modules/samples/PizzaShack/PizzaShack.zip new file mode 100644 index 0000000000..b6fbff02e5 Binary files /dev/null and b/modules/samples/PizzaShack/PizzaShack.zip differ diff --git a/modules/samples/PizzaShack/pizza-shack-api/order.json b/modules/samples/PizzaShack/pizza-shack-api/order.json new file mode 100644 index 0000000000..36b93fe1fe --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-api/order.json @@ -0,0 +1,5 @@ +{ + "name": "Spicy Italian", + "quantity": 1, + "customerName": "Hiranya" +} diff --git a/modules/samples/PizzaShack/pizza-shack-api/pom.xml b/modules/samples/PizzaShack/pizza-shack-api/pom.xml new file mode 100644 index 0000000000..f9400440bc --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-api/pom.xml @@ -0,0 +1,169 @@ + + + + + com.pizzashack + pizzashack + 1.0.0 + + + 4.0.0 + com.pizzashack + pizzashack-api + + war + PizzaShack JAX-RS API + Simple CXF JAX-RS webapp service using spring configuration + + 1.8.6 + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + 2.6.1 + + + org.codehaus.jackson + jackson-core-asl + ${jackson.version} + + + org.codehaus.jackson + jackson-mapper-asl + ${jackson.version} + + + org.codehaus.jackson + jackson-jaxrs + ${jackson.version} + + + junit + junit + 4.10 + test + + + org.springframework + spring-web + 3.0.6.RELEASE + + + + + + + org.codehaus.mojo + tomcat-maven-plugin + 1.1 + + + default-cli + + run + + + 13000 + /jaxrs-service + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.5 + 1.5 + + + + org.apache.maven.plugins + maven-eclipse-plugin + + [artifactId]-[version] + true + true + 2.0 + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.5 + + + reserve-network-port + + reserve-network-port + + process-test-resources + + + test.server.port + + + + + + + org.codehaus.mojo + tomcat-maven-plugin + + + start-tomcat + + run-war + + pre-integration-test + + ${test.server.port} + /jaxrs-service + true + true + + + + stop-tomcat + + shutdown + + post-integration-test + + /jaxrs-service + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + 2.8.1 + + + integration-test + + integration-test + + + + http://localhost:${test.server.port}/jaxrs-service + + + + + verify + + verify + + + + + + + diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/OrderManager.java b/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/OrderManager.java new file mode 100644 index 0000000000..8671e50692 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/OrderManager.java @@ -0,0 +1,64 @@ +package com.pizzashack; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +import com.pizzashack.beans.Order; + +public class OrderManager { + + private Map orders = new ConcurrentHashMap(); + + private static final OrderManager instance = new OrderManager(); + + private OrderManager() { + + } + + public static OrderManager getInstance() { + return instance; + } + + public String placeOrder(Order order) { + String orderId = UUID.randomUUID().toString(); + order.setOrderId(orderId); + orders.put(orderId, order); + return orderId; + } + + public Order getOrder(String orderId) { + return orders.get(orderId); + } + + public boolean updateOrder(String orderId, Order order) { + if (orders.containsKey(orderId)) { + order.setOrderId(orderId); + orders.put(orderId, order); + return true; + } + return false; + } + + public boolean cancelOrder(String orderId) { + if (orders.containsKey(orderId)) { + orders.remove(orderId); + return true; + } + return false; + } + + public Order[] listOrders() { + return orders.values().toArray(new Order[orders.size()]); + } + + public boolean deliverOrder(String orderId) { + Order order = orders.get(orderId); + if (order != null) { + order.setOrderId(orderId); + order.setDelivered(true); + return true; + } + return false; + } +} diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/PizzaMenu.java b/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/PizzaMenu.java new file mode 100644 index 0000000000..f299a3ea07 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/PizzaMenu.java @@ -0,0 +1,106 @@ +package com.pizzashack; + +import java.text.DecimalFormat; +import java.util.Comparator; +import java.util.Random; +import java.util.Set; +import java.util.TreeSet; + +import com.pizzashack.beans.MenuItem; + +public class PizzaMenu { + + private Set items = new TreeSet(new Comparator() { + public int compare(MenuItem o1, MenuItem o2) { + return o1.getName().compareTo(o2.getName()); + } + }); + + private static final PizzaMenu instance = new PizzaMenu(); + + private PizzaMenu() { + Random rand = new Random(); + DecimalFormat format = new DecimalFormat("#.##"); + + MenuItem item1 = new MenuItem(); + item1.setName("Chicken Parmesan"); + item1.setDescription("Grilled chicken, fresh tomatoes, feta and mozzarella cheese"); + item1.setPrice(format.format(rand.nextInt(20) + 10 - 0.01)); + item1.setIcon("/images/1.png"); + items.add(item1); + + MenuItem item2 = new MenuItem(); + item2.setName("Spicy Italian"); + item2.setDescription("Pepperoni and a double portion of spicy Italian sausage"); + item2.setPrice(format.format(rand.nextInt(20) + 10 - 0.01)); + item2.setIcon("/images/2.png"); + items.add(item2); + + MenuItem item3 = new MenuItem(); + item3.setName("Garden Fresh"); + item3.setDescription("Slices onions and green peppers, gourmet " + + "mushrooms, black olives and ripe Roma tomatoes"); + item3.setPrice(format.format(rand.nextInt(20) + 10 - 0.01)); + item3.setIcon("/images/3.png"); + items.add(item3); + + MenuItem item4 = new MenuItem(); + item4.setName("Tuscan Six Cheese"); + item4.setDescription("Six cheese blend of mozzarella, Parmesan, Romano, Asiago and Fontina"); + item4.setPrice(format.format(rand.nextInt(20) + 10 - 0.01)); + item4.setIcon("/images/4.png"); + items.add(item4); + + MenuItem item5 = new MenuItem(); + item5.setName("Spinach Alfredo"); + item5.setDescription("Rich and creamy blend of spinach and garlic Parmesan with Alfredo sauce"); + item5.setPrice(format.format(rand.nextInt(20) + 10 - 0.01)); + item5.setIcon("/images/5.png"); + items.add(item5); + + MenuItem item6 = new MenuItem(); + item6.setName("BBQ Chicken Bacon"); + item6.setDescription("Grilled white chicken, hickory-smoked bacon and fresh sliced onions in barbeque sauce"); + item6.setPrice(format.format(rand.nextInt(20) + 10 - 0.01)); + item6.setIcon("/images/6.png"); + items.add(item6); + + MenuItem item7 = new MenuItem(); + item7.setName("Hawaiian BBQ Chicken"); + item7.setDescription("Grilled white chicken, hickory-smoked bacon, barbeque sauce topped with sweet pine-apple"); + item7.setPrice(format.format(rand.nextInt(20) + 10 - 0.01)); + item7.setIcon("/images/7.png"); + items.add(item7); + + MenuItem item8 = new MenuItem(); + item8.setName("Grilled Chicken Club"); + item8.setDescription("Grilled white chicken, hickory-smoked bacon and fresh sliced onions topped with Roma tomatoes"); + item8.setPrice(format.format(rand.nextInt(20) + 10 - 0.01)); + item8.setIcon("/images/8.png"); + items.add(item8); + + MenuItem item9 = new MenuItem(); + item9.setName("Double Bacon 6Cheese"); + item9.setDescription("Hickory-smoked bacon, Julienne cut Canadian bacon, Parmesan, " + + "mozzarella, Romano, Asiago and and Fontina cheese"); + item9.setPrice(format.format(rand.nextInt(20) + 10 - 0.01)); + item9.setIcon("/images/9.png"); + items.add(item9); + + MenuItem item10 = new MenuItem(); + item10.setName("Chilly Chicken Cordon Bleu"); + item10.setDescription("Spinash Alfredo sauce topped with grilled chicken, ham, onions and " + + "mozzarella"); + item10.setPrice(format.format(rand.nextInt(20) + 10 - 0.01)); + item10.setIcon("/images/10.png"); + items.add(item10); + } + + public static PizzaMenu getInstance() { + return instance; + } + + public MenuItem[] getMenu() { + return items.toArray(new MenuItem[items.size()]); + } +} diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/PizzaShackDeliveryAPI.java b/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/PizzaShackDeliveryAPI.java new file mode 100644 index 0000000000..d2d07fb0e8 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/PizzaShackDeliveryAPI.java @@ -0,0 +1,36 @@ +package com.pizzashack; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; + +import com.pizzashack.beans.Order; + +@Path("/delivery") +public class PizzaShackDeliveryAPI { + + @GET + @Produces("application/json") + public Response getOrderList() { + Order[] orders = OrderManager.getInstance().listOrders(); + return Response.ok().entity(orders).build(); + } + + @PUT + @Consumes("application/json") + @Produces("application/json") + @Path("/{orderId}") + public Response deliverOrder(@PathParam("orderId") String orderId) { + boolean updated = OrderManager.getInstance().deliverOrder(orderId); + if (updated) { + return Response.ok().build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } + +} diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/PizzaShackMenuAPI.java b/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/PizzaShackMenuAPI.java new file mode 100644 index 0000000000..8b7b62c6c8 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/PizzaShackMenuAPI.java @@ -0,0 +1,19 @@ +package com.pizzashack; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; + +import com.pizzashack.beans.MenuItem; + +@Path("/menu") +public class PizzaShackMenuAPI { + + @GET + @Produces("application/json") + public Response getMenu() { + MenuItem[] menuItems = PizzaMenu.getInstance().getMenu(); + return Response.ok().entity(menuItems).build(); + } +} diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/PizzaShackOrderAPI.java b/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/PizzaShackOrderAPI.java new file mode 100644 index 0000000000..358b189173 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/PizzaShackOrderAPI.java @@ -0,0 +1,66 @@ +package com.pizzashack; + +import java.net.URI; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; + +import com.pizzashack.beans.Order; + +@Path("/order") +public class PizzaShackOrderAPI { + + @POST + @Consumes("application/json") + @Produces("application/json") + public Response placeOrder(Order order) { + String orderId = OrderManager.getInstance().placeOrder(order); + return Response.created(URI.create("order/" + orderId)).entity(order).build(); + } + + @GET + @Produces("application/json") + @Path("/{orderId}") + public Response getOrder(@PathParam("orderId") String orderId) { + Order order = OrderManager.getInstance().getOrder(orderId); + if (order != null) { + return Response.ok().entity(order).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } + + @DELETE + @Produces("application/json") + @Path("/{orderId}") + public Response cancelOrder(@PathParam("orderId") String orderId) { + boolean cancelled = OrderManager.getInstance().cancelOrder(orderId); + if (cancelled) { + return Response.ok().build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } + + @PUT + @Consumes("application/json") + @Produces("application/json") + @Path("/{orderId}") + public Response updateOrder(@PathParam("orderId") String orderId, Order order) { + boolean updated = OrderManager.getInstance().updateOrder(orderId, order); + if (updated) { + return Response.ok().entity(order).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } + +} + diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/beans/MenuItem.java b/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/beans/MenuItem.java new file mode 100644 index 0000000000..508f1d4126 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/beans/MenuItem.java @@ -0,0 +1,42 @@ +package com.pizzashack.beans; + +public class MenuItem { + + private String name; + private String description; + private String price; + private String icon; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getIcon() { + return icon; + } + + public void setIcon(String icon) { + this.icon = icon; + } + +} diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/beans/Order.java b/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/beans/Order.java new file mode 100644 index 0000000000..9114e03510 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-api/src/main/java/com/pizzashack/beans/Order.java @@ -0,0 +1,69 @@ +package com.pizzashack.beans; + +public class Order { + + private String orderId; + private String pizzaType; + private int quantity; + private String customerName; + private String creditCardNumber; + private String address; + private boolean delivered; + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public String getPizzaType() { + return pizzaType; + } + + public void setPizzaType(String pizzaType) { + this.pizzaType = pizzaType; + } + + public int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public String getCustomerName() { + return customerName; + } + + public void setCustomerName(String customerName) { + this.customerName = customerName; + } + + public String getCreditCardNumber() { + return creditCardNumber; + } + + public void setCreditCardNumber(String creditCardNumber) { + this.creditCardNumber = creditCardNumber; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public boolean isDelivered() { + return delivered; + } + + public void setDelivered(boolean delivered) { + this.delivered = delivered; + } + +} diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/META-INF/MANIFEST.MF b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..fea56d8b73 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,12 @@ +Manifest-Version: 1.0 +Class-Path: cxf-rt-frontend-jaxrs-2.6.1.jar cxf-api-2.6.1.jar woodstox + -core-asl-4.1.2.jar stax2-api-3.1.1.jar xmlschema-core-2.0.2.jar gero + nimo-javamail_1.4_spec-1.7.1.jar wsdl4j-1.6.2.jar cxf-rt-core-2.6.1.j + ar jaxb-impl-2.1.13.jar jsr311-api-1.1.1.jar cxf-rt-bindings-xml-2.6. + 1.jar cxf-rt-transports-http-2.6.1.jar jackson-core-asl-1.8.6.jar jac + kson-mapper-asl-1.8.6.jar jackson-jaxrs-1.8.6.jar spring-web-3.0.6.RE + LEASE.jar aopalliance-1.0.jar spring-beans-3.0.6.RELEASE.jar spring-c + ore-3.0.6.RELEASE.jar spring-asm-3.0.6.RELEASE.jar commons-logging-1. + 1.1.jar spring-context-3.0.6.RELEASE.jar spring-aop-3.0.6.RELEASE.jar + spring-expression-3.0.6.RELEASE.jar + diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/WEB-INF/beans.xml b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..abd33e1c4c --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/WEB-INF/web.xml b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..8f35874985 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,31 @@ + + + JAX-RS Simple Service + JAX-RS Simple Service + + + contextConfigLocation + WEB-INF/beans.xml + + + + org.springframework.web.context.ContextLoaderListener + + + + CXFServlet + + org.apache.cxf.transport.servlet.CXFServlet + + 1 + + + + CXFServlet + /api/* + + diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/1.png b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/1.png new file mode 100644 index 0000000000..973daa082f Binary files /dev/null and b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/1.png differ diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/10.png b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/10.png new file mode 100644 index 0000000000..799214e2b7 Binary files /dev/null and b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/10.png differ diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/2.png b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/2.png new file mode 100644 index 0000000000..d6070e7a44 Binary files /dev/null and b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/2.png differ diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/3.png b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/3.png new file mode 100644 index 0000000000..8ca203ea0d Binary files /dev/null and b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/3.png differ diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/4.png b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/4.png new file mode 100644 index 0000000000..3e10d24c2e Binary files /dev/null and b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/4.png differ diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/5.png b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/5.png new file mode 100644 index 0000000000..ee15f80395 Binary files /dev/null and b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/5.png differ diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/6.png b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/6.png new file mode 100644 index 0000000000..99ce0f6beb Binary files /dev/null and b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/6.png differ diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/7.png b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/7.png new file mode 100644 index 0000000000..32ccf21ba7 Binary files /dev/null and b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/7.png differ diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/8.png b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/8.png new file mode 100644 index 0000000000..c8725984c1 Binary files /dev/null and b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/8.png differ diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/9.png b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/9.png new file mode 100644 index 0000000000..22ab5b19a8 Binary files /dev/null and b/modules/samples/PizzaShack/pizza-shack-api/src/main/webapp/images/9.png differ diff --git a/modules/samples/PizzaShack/pizza-shack-api/src/test/java/com/pizzashack/PizzaShackOrderAPIIT.java b/modules/samples/PizzaShack/pizza-shack-api/src/test/java/com/pizzashack/PizzaShackOrderAPIIT.java new file mode 100644 index 0000000000..7e2b5d0f32 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-api/src/test/java/com/pizzashack/PizzaShackOrderAPIIT.java @@ -0,0 +1,53 @@ +package com.pizzashack; + +import static org.junit.Assert.assertEquals; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.core.Response; + +import org.apache.cxf.helpers.IOUtils; +import org.apache.cxf.jaxrs.client.WebClient; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.pizzashack.beans.Order; + +public class PizzaShackOrderAPIIT { + + private static String endpointUrl; + + @BeforeClass + public static void beforeClass() { + endpointUrl = System.getProperty("service.url"); + } + + @Test + public void testGetMenu() throws Exception { + WebClient client = WebClient.create(endpointUrl + "/api/menu"); + Response r = client.accept("application/json").get(); + assertEquals(Response.Status.OK.getStatusCode(), r.getStatus()); + String value = IOUtils.toString((InputStream)r.getEntity()); + System.out.println(value); + } + + @Test + public void testPlaceOrder() throws Exception { + List providers = new ArrayList(); + providers.add(new org.codehaus.jackson.jaxrs.JacksonJsonProvider()); + WebClient client = WebClient.create(endpointUrl + "/api/order", providers); + Order order = new Order(); + order.setPizzaType("Pizza1"); + order.setCustomerName("Hiranya"); + order.setCreditCardNumber("123456"); + order.setAddress("59 Flower Road"); + order.setQuantity(1); + Response r = client.accept("application/json").type("application/json").post(order); + assertEquals(Response.Status.CREATED.getStatusCode(), r.getStatus()); + String value = IOUtils.toString((InputStream)r.getEntity()); + System.out.println(value); + } + +} diff --git a/modules/samples/PizzaShack/pizza-shack-web/pom.xml b/modules/samples/PizzaShack/pizza-shack-web/pom.xml new file mode 100644 index 0000000000..710c2e95b0 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/pom.xml @@ -0,0 +1,96 @@ + + + + com.pizzashack + pizzashack + 1.0.0 + + + 4.0.0 + com.pizzashack.client.web + pizza-shack-web + PizzaShack Web Application + war + http://maven.apache.org + + + junit + junit + 3.8.1 + test + + + com.googlecode.json-simple + json-simple + 1.1 + + + org.apache.httpcomponents.wso2 + httpclient + 4.1.1-wso2v1 + + + javax.servlet + servlet-api + 2.5 + provided + + + commons-logging + commons-logging + 1.1.1 + provided + + + + pizzashack + + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + + + + + + + + + + + + + + + wso2-nexus + WSO2 internal Repository + http://maven.wso2.org/nexus/content/groups/wso2-public/ + + true + daily + fail + + + + diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/dto/Order.java b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/dto/Order.java new file mode 100644 index 0000000000..5e9d5f8f91 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/dto/Order.java @@ -0,0 +1,93 @@ +package com.pizzashack.client.dto; + + +public class Order { + private String address; + private String pizzaType; + private String customerName; + private int quantity; + private String creditCardNumber; + boolean delivered; + private String orderId; + + public Order(){ + + } + public Order(String address, String pizzaType, String customerName, String quantity, + String creditCardNumber) { + this.address = address; + this.pizzaType = pizzaType; + this.customerName = customerName; + this.quantity = Integer.valueOf(quantity).intValue(); + this.creditCardNumber = creditCardNumber; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getPizzaType() { + return pizzaType; + } + + public void setPizzaType(String pizzaType) { + this.pizzaType = pizzaType; + } + + public String getCustomerName() { + return customerName; + } + + public void setCustomerName(String customerName) { + this.customerName = customerName; + } + + public int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public String getCreditCardNumber() { + return creditCardNumber; + } + + public void setCreditCardNumber(String creditCardNumber) { + this.creditCardNumber = creditCardNumber; + } + + public boolean isDelivered() { + return delivered; + } + + public void setDelivered(boolean delivered) { + this.delivered = delivered; + } + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + @Override + public String toString() { + return "Order{" + + "address='" + address + '\'' + + ", pizzaType='" + pizzaType + '\'' + + ", customerName='" + customerName + '\'' + + ", quantity=" + quantity + + ", creditCardNumber='" + creditCardNumber + '\'' + + ", delivered=" + delivered + + ", orderId='" + orderId + '\'' + + '}'; + } +} diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/dto/Pizza.java b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/dto/Pizza.java new file mode 100644 index 0000000000..00f9cd916b --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/dto/Pizza.java @@ -0,0 +1,41 @@ +package com.pizzashack.client.dto; + + +public class Pizza { + private String name; + private String description; + private String imageUrl; + private double price; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getImageUrl() { + return imageUrl; + } + + public void setImageUrl(String imageUrl) { + this.imageUrl = imageUrl; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } +} diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/dto/Token.java b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/dto/Token.java new file mode 100644 index 0000000000..6a02b38180 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/dto/Token.java @@ -0,0 +1,51 @@ +package com.pizzashack.client.dto; + + +public class Token { + private String tokenType; + private long expiresIn; + private String refreshToken; + private String accessToken; + + public String getTokenType() { + return tokenType; + } + + public void setTokenType(String tokenType) { + this.tokenType = tokenType; + } + + public long getExpiresIn() { + return expiresIn; + } + + public void setExpiresIn(long expiresIn) { + this.expiresIn = expiresIn; + } + + public String getRefreshToken() { + return refreshToken; + } + + public void setRefreshToken(String refreshToken) { + this.refreshToken = refreshToken; + } + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @Override + public String toString() { + return "Token{" + + "tokenType='" + tokenType + '\'' + + ", expiresIn=" + expiresIn + + ", refreshToken='" + refreshToken + '\'' + + ", accessToken='" + accessToken + '\'' + + '}'; + } +} diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/HTTPClient.java b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/HTTPClient.java new file mode 100644 index 0000000000..ef253dfa15 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/HTTPClient.java @@ -0,0 +1,135 @@ +package com.pizzashack.client.web; + +import org.apache.http.HttpEntityEnclosingRequest; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpRequest; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpRequestRetryHandler; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.scheme.SocketFactory; +import org.apache.http.entity.ContentProducer; +import org.apache.http.entity.EntityTemplate; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.apache.http.params.HttpConnectionParams; +import org.apache.http.params.HttpParams; +import org.apache.http.protocol.HttpContext; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +public class HTTPClient { + + private ThreadSafeClientConnManager connManager; + private DefaultHttpClient client; + + public HTTPClient() { + connManager = getHTTPConnectionManager(); + client = configureHTTPClient(connManager); + } + + public HttpResponse doPost(String url, String token, final String payload, String contentType) throws IOException { + HttpUriRequest request = new HttpPost(url); + addSecurityHeaders(request, token); + + HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request; + EntityTemplate ent = new EntityTemplate(new ContentProducer() { + public void writeTo(OutputStream outputStream) throws IOException { + outputStream.write(payload.getBytes()); + outputStream.flush(); + } + }); + ent.setContentType(contentType); + entityEncReq.setEntity(ent); + return client.execute(request); + } + + public HttpResponse doGet(String url, String token) throws IOException { + HttpUriRequest request = new HttpGet(url); + addSecurityHeaders(request, token); + return client.execute(request); + } + + public String getResponsePayload(HttpResponse response) throws IOException { + StringBuffer buffer = new StringBuffer(); + InputStream in = null; + try { + if (response.getEntity() != null) { + in = response.getEntity().getContent(); + int length; + byte[] tmp = new byte[2048]; + while ((length = in.read(tmp)) != -1) { + buffer.append(new String(tmp, 0, length)); + } + } + } catch (IllegalStateException e) { + e.printStackTrace(); + } finally { + if (in != null) { + in.close(); + } + } + + return buffer.toString(); + } + + public HttpResponse doPut(String url, String token, final String payload, String contentType) throws IOException { + HttpUriRequest request = new HttpPut(url); + addSecurityHeaders(request, token); + + HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request; + EntityTemplate ent = new EntityTemplate(new ContentProducer() { + public void writeTo(OutputStream outputStream) throws IOException { + outputStream.write(payload.getBytes()); + outputStream.flush(); + } + }); + ent.setContentType(contentType); + entityEncReq.setEntity(ent); + return client.execute(request); + } + + public HttpResponse doDelete(String url, String token) throws IOException { + HttpUriRequest request = new HttpDelete(url); + addSecurityHeaders(request, token); + return client.execute(request); + } + + private DefaultHttpClient configureHTTPClient( + ThreadSafeClientConnManager connManager) { + connManager.setDefaultMaxPerRoute(1000); + DefaultHttpClient client = new DefaultHttpClient(connManager); + HttpParams params = client.getParams(); + HttpConnectionParams.setConnectionTimeout(params, 30000); + HttpConnectionParams.setSoTimeout(params, 30000); + client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { + public boolean retryRequest(IOException e, int i, + HttpContext httpContext) { + return false; + } + }); + return client; + } + + private ThreadSafeClientConnManager getHTTPConnectionManager() { + SchemeRegistry supportedSchemes = new SchemeRegistry(); + SocketFactory sf = PlainSocketFactory.getSocketFactory(); + supportedSchemes.register(new Scheme("http", sf, 80)); + + return new ThreadSafeClientConnManager(supportedSchemes); + } + + private void addSecurityHeaders(HttpRequest request, String token) { + if (token != null) { + request.setHeader(HttpHeaders.AUTHORIZATION, token); + } + } +} diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/JSONClient.java b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/JSONClient.java new file mode 100644 index 0000000000..dfc7978767 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/JSONClient.java @@ -0,0 +1,208 @@ +package com.pizzashack.client.web; + + +import com.pizzashack.client.dto.Order; +import com.pizzashack.client.dto.Pizza; +import com.pizzashack.client.dto.Token; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.util.ArrayList; +import java.util.Iterator; + +public class JSONClient { + public static void main(String args[]) { +// //Get Pizza list Test +// MenuItemManager menuItemManager = new MenuItemManager(); +// ArrayList pizzaArrayList = menuItemManager.getAvailablePizzaList("3ckecjecnrejkchrhklhckeh"); +// for (Pizza pizza : pizzaArrayList) { +// System.out.println(pizza.getName() +// + " : " + pizza.getDescription() + " : " + pizza.getImageUrl() + " : " + pizza.getPrice()); +// } +// +// //Save Order Test +// OrderManager orderManager = new OrderManager(); +// Order order = orderManager.saveOrder("59, Malpara", "Vege Delight", "1" +// , "Ritigala Jayasena", "3442-3453-5643-2334", "3ckecjecnrejkchrhklhckeh"); +// +// System.out.println(order.getOrderId()); +// order = orderManager.getOrder(order.getOrderId(),"3ckecjecnrejkchrhklhckeh"); +// System.out.println(order); + + + //Generate Token Test +// TokenManager tokenManager = new TokenManager(); +// Token token = tokenManager.getToken("k1NIAas_H49ZKv2jlhZROJkyHQga","fgYlec00Fg3fpP3FgH3ZyAc17EQa","chanaka","test123"); +// System.out.println(token); + +// //Test Pizza List +// JSONClient jsonClient = new JSONClient(); +// //url = "http://10.150.3.80:9763/order-api-1.0.0/api/order/menu"; +// +// ArrayList pizzaArrayList = jsonClient.getAvailablePizzaList("http://localhost:8080/examples/test-json.txt"); +// for (Pizza pizza : pizzaArrayList) { +// System.out.println(pizza.getName() +// + " : " + pizza.getDescription() + " : " + pizza.getImageUrl() + " : " + pizza.getPrice()); +// } +// +// //Test Order JSON +// Order order = new Order(); +// order.setAddress("Malpara"); +// order.setCreditCardNumber("3442-3453-5643-2334"); +// order.setCustomerName("Ritigala Jayasena"); +// order.setDelivered(false); +// order.setPizzaType("Vegidelight"); +// order.setQuantity(2); +// String orderJSON = jsonClient.generateSaveOrderMessage(order); +// System.out.println(orderJSON); +// +// //Test Order Save +// HTTPClient HTTPClient = new HTTPClient(); +//// HTTPClient.doPost(order, "http://10.150.3.80:9763/pizzashack-1.0.0/api/order"); + } + + + /** + * @param pizzaContents + * @return + */ + public static ArrayList getAvailablePizzaList(String pizzaContents) { + JSONParser parser = new JSONParser(); + ArrayList pizzaList = new ArrayList(); + try { + Object obj = parser.parse(pizzaContents); + + JSONArray array = (JSONArray) obj; + Iterator iterator = array.iterator(); + Pizza pizza; + while (iterator.hasNext()) { + pizza = new Pizza(); + JSONObject pizzaItem = iterator.next(); + pizza.setName((String) pizzaItem.get("name")); + pizza.setDescription((String) pizzaItem.get("description")); + pizza.setImageUrl((String) pizzaItem.get("icon")); + double price = Double.valueOf((String) pizzaItem.get("price")).doubleValue(); + + pizza.setPrice(price); + pizzaList.add(pizza); + } + } catch (ParseException e) { + e.printStackTrace(); + } + return pizzaList; + } + + + /** + * Constructs a JSON String similar to: + * {"address":"59 Flower Road","pizzaType":"Pizza1","quantity":1,"customerName":"Hiranya", + * "creditCardNumber":"123456","delivered":false} + * + * @param order + * @return + */ + public static String generateSaveOrderMessage(Order order) { + JSONObject orderJSON = new JSONObject(); + + orderJSON.put("address", order.getAddress()); + orderJSON.put("pizzaType", order.getPizzaType()); + orderJSON.put("quantity", order.getQuantity()); + orderJSON.put("customerName", order.getCustomerName()); + orderJSON.put("creditCardNumber", order.getCreditCardNumber()); + return orderJSON.toJSONString(); + } + + /** + * Returns a populated Order object when a JSON message similar to following is passed. + * { + * "address": "Malpara", + * "quantity": 2, + * "customerName": "Ritigala Jayasena", + * "creditCardNumber": "3442-3453-5643-2334", + * "delivered": false, + * "pizzaType": "Vegidelight", + * "orderId": "b06fe761-c95e-4b55-91ff-7e1f8ea8f3a0" + * } + * @param orderJson + * @return + */ + public static Order getOrder(String orderJson){ + JSONParser parser = new JSONParser(); + + Order order = new Order(); + try { + Object obj = parser.parse(orderJson); + JSONObject jsonObject = (JSONObject)obj; + order.setAddress((String)jsonObject.get("address")); + int quantity = ((Long)jsonObject.get("quantity")).intValue(); + order.setQuantity(quantity); + order.setCustomerName((String) jsonObject.get("customerName")); + order.setCreditCardNumber((String) jsonObject.get("creditCardNumber")); + boolean delivered = Boolean.valueOf((Boolean)jsonObject.get("delivered")); + order.setDelivered(delivered); + order.setPizzaType((String)jsonObject.get("pizzaType")); + order.setOrderId((String) jsonObject.get("orderId")); + return order; + } catch (ParseException e) { + e.printStackTrace(); + } + return null; + } + +// public static ArrayList getOrderList(String ordersJson){ +// JSONParser parser = new JSONParser(); +// +// ArrayList orderList = new ArrayList(); +// try { +// Object obj = parser.parse(orderJson); +// JSONObject jsonObject = (JSONObject)obj; +// order.setAddress((String)jsonObject.get("address")); +// int quantity = ((Long)jsonObject.get("quantity")).intValue(); +// order.setQuantity(quantity); +// order.setCustomerName((String) jsonObject.get("customerName")); +// order.setCreditCardNumber((String) jsonObject.get("creditCardNumber")); +// boolean delivered = Boolean.valueOf((String)jsonObject.get("pizzaType")); +// order.setDelivered(delivered); +// order.setPizzaType((String)jsonObject.get("pizzaType")); +// order.setOrderId((String) jsonObject.get("orderId")); +// return order; +// } catch (ParseException e) { +// e.printStackTrace(); +// } +// return null; +// } + + + /** + * Populates Token object using folloing JSON String + * { + * "token_type": "bearer", + * "expires_in": 3600000, + * "refresh_token": "f43de118a489d56c3b3b7ba77a1549e", + * "access_token": "269becaec9b8b292906b3f9e69b5a9" + } + * @param accessTokenJson + * @return + */ + public static Token getAccessToken(String accessTokenJson){ + JSONParser parser = new JSONParser(); + + Token token = new Token(); + try { + Object obj = parser.parse(accessTokenJson); + JSONObject jsonObject = (JSONObject)obj; + token.setAccessToken((String)jsonObject.get("access_token")); + long expiresIn = ((Long)jsonObject.get("expires_in")).intValue(); + token.setExpiresIn(expiresIn); + token.setRefreshToken((String)jsonObject.get("refresh_token")); + token.setTokenType((String)jsonObject.get("token_type")); + + } catch (ParseException e) { + e.printStackTrace(); + } + return token; + + } +} diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/MenuItemManager.java b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/MenuItemManager.java new file mode 100644 index 0000000000..08d199b0a0 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/MenuItemManager.java @@ -0,0 +1,35 @@ +package com.pizzashack.client.web; + + +import com.pizzashack.client.dto.Pizza; +import org.apache.http.HttpResponse; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; + +public class MenuItemManager { + + private HTTPClient httpClient; + private String serverURL; + private final String PIZZA_LIST_URL = "/menu/1.0.0"; + + public MenuItemManager() { + httpClient = new HTTPClient(); + serverURL = PizzaShackWebConfiguration.getInstance().getServerURL(); + } + + public ArrayList getAvailablePizzaList(String token) { + InputStream is = null; + HttpResponse httpResponse = null; + try { + httpResponse = httpClient.doGet(serverURL + PIZZA_LIST_URL, "Bearer " + token); + String response = httpClient.getResponsePayload(httpResponse); + return JSONClient.getAvailablePizzaList(response); + + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/OrderManager.java b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/OrderManager.java new file mode 100644 index 0000000000..fe1a8fb682 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/OrderManager.java @@ -0,0 +1,54 @@ +package com.pizzashack.client.web; + + +import com.pizzashack.client.dto.Order; +import org.apache.http.HttpResponse; + +import java.io.IOException; + +public class OrderManager { + private HTTPClient httpClient; + private String serverURL; + private final String PIZZA_ORDER_URL = "/order/1.0.0"; + private final String PIZZA_DELIVERY_URL = "/api/delivery"; + + + public OrderManager() { + httpClient = new HTTPClient(); + serverURL = PizzaShackWebConfiguration.getInstance().getServerURL(); + } + + public Order saveOrder(String address, String pizzaType, String quantity + , String customerName, String creditCardNumber, String token) { + Order order = new Order(address,pizzaType,customerName,quantity,creditCardNumber); + String jsonString = JSONClient.generateSaveOrderMessage(order); + + String submitUrl = PizzaShackWebConfiguration.getInstance().getServerURL() + PIZZA_ORDER_URL; + try { + HttpResponse httpResponse = httpClient.doPost(submitUrl,"Bearer " + token,jsonString,"application/json"); + String response = httpClient.getResponsePayload(httpResponse); + //new instance with orderId + order = JSONClient.getOrder(response); + } catch (IOException e) { + e.printStackTrace(); + } + return order; + } + + public Order getOrder(String orderId, String token){ + String submitUrl = PizzaShackWebConfiguration.getInstance().getServerURL() + + PIZZA_ORDER_URL + "/" + orderId; + + Order order = null; + try { + HttpResponse httpResponse = httpClient.doGet(submitUrl, "Bearer " + token); + String response = httpClient.getResponsePayload(httpResponse); + order = JSONClient.getOrder(response); + return order; + } catch (IOException e) { + e.printStackTrace(); + } + return order; + } + +} diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/PizzaShackContextListener.java b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/PizzaShackContextListener.java new file mode 100644 index 0000000000..e62862afbe --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/PizzaShackContextListener.java @@ -0,0 +1,30 @@ +package com.pizzashack.client.web; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +public class PizzaShackContextListener implements ServletContextListener { + + @Override + public void contextDestroyed(ServletContextEvent event) { + + } + + @Override + public void contextInitialized(ServletContextEvent event) { + String serverURL = event.getServletContext().getInitParameter("serverURL"); + System.out.println("Setting server URL to: " + serverURL); + PizzaShackWebConfiguration.getInstance().setServerURL(serverURL); + + String loginURL = event.getServletContext().getInitParameter("loginURL"); + //String loginURL = "https://10.150.3.80:9443/_WSO2AMLoginAPI_"; + PizzaShackWebConfiguration.getInstance().setLoginURL(loginURL); + + String consumerKey = event.getServletContext().getInitParameter("consumerKey"); + PizzaShackWebConfiguration.getInstance().setConsumerKey(consumerKey); + + String consumerSecret = event.getServletContext().getInitParameter("consumerSecret"); + PizzaShackWebConfiguration.getInstance().setConsumerSecret(consumerSecret); + } + +} diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/PizzaShackWebConfiguration.java b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/PizzaShackWebConfiguration.java new file mode 100644 index 0000000000..7289563ae7 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/PizzaShackWebConfiguration.java @@ -0,0 +1,52 @@ +package com.pizzashack.client.web; + +public class PizzaShackWebConfiguration { + + private static final PizzaShackWebConfiguration instance = new PizzaShackWebConfiguration(); + + private String serverURL; + private String loginURL; + private String consumerKey; + private String consumerSecret; + + private PizzaShackWebConfiguration() { + + } + + public static PizzaShackWebConfiguration getInstance() { + return instance; + } + + public String getServerURL() { + return serverURL; + } + + public void setServerURL(String serverURL) { + this.serverURL = serverURL; + } + + public String getLoginURL() { + return loginURL; + } + + public void setLoginURL(String loginURL) { + this.loginURL = loginURL; + } + + public String getConsumerKey() { + return consumerKey; + } + + public void setConsumerKey(String consumerKey) { + this.consumerKey = consumerKey; + } + + public String getConsumerSecret() { + return consumerSecret; + } + + public void setConsumerSecret(String consumerSecret) { + this.consumerSecret = consumerSecret; + } + +} diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/TokenManager.java b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/TokenManager.java new file mode 100644 index 0000000000..28f2eb571f --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/java/com/pizzashack/client/web/TokenManager.java @@ -0,0 +1,40 @@ +package com.pizzashack.client.web; + + +import com.pizzashack.client.dto.Token; +import org.apache.http.HttpResponse; +import sun.misc.BASE64Encoder; + +import java.io.IOException; + +public class TokenManager { + + private HTTPClient httpClient; + + public TokenManager() { + httpClient = new HTTPClient(); + } + + public Token getToken(String username, String password){ + String submitUrl = PizzaShackWebConfiguration.getInstance().getLoginURL(); + String consumerKey = PizzaShackWebConfiguration.getInstance().getConsumerKey(); + String consumerSecret = PizzaShackWebConfiguration.getInstance().getConsumerSecret(); + try { + String applicationToken = consumerKey + ":" + consumerSecret; + BASE64Encoder base64Encoder = new BASE64Encoder(); + applicationToken = "Basic " + base64Encoder.encode(applicationToken.getBytes()).trim(); + + String payload = "grant_type=password&username="+username+"&password="+password; + HttpResponse httpResponse = httpClient.doPost(submitUrl,applicationToken, + payload,"application/x-www-form-urlencoded"); + if (httpResponse.getStatusLine().getStatusCode() != 200) { + return null; + } + String response = httpClient.getResponsePayload(httpResponse); + return JSONClient.getAccessToken(response); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/WEB-INF/web.xml b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..2e28284c16 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,27 @@ + + Pizza Shack Client App + + + com.pizzashack.client.web.PizzaShackContextListener + + + + serverURL + http://localhost:8280/pizzashack + + + loginURL + http://localhost:8280/token + + + consumerKey + p51ZBFaY_GD955qMjqSah76Pa_ca + + + consumerSecret + 1Y_K6Zr_bQq8MfDBa31odFTa0BEa + + + diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/css/local.css b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/css/local.css new file mode 100644 index 0000000000..407c5634c9 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/css/local.css @@ -0,0 +1,68 @@ +body { + background-color: #c40404; + *background-color: #c40404; + background-image: -ms-linear-gradient(top, #680001, #c40404); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#680001), to(#c40404)); + background-image: -webkit-linear-gradient(top, #680001, #c40404); + background-image: -o-linear-gradient(top, #680001, #c40404); + background-image: linear-gradient(top, #680001, #c40404); + background-image: -moz-linear-gradient(top, #680001, #c40404); + filter: progid:dximagetransform.microsoft.gradient(startColorstr = '#680001', endColorstr = '#c40404', GradientType = 0); + filter: progid:dximagetransform.microsoft.gradient(enabled = false); + background-repeat: repeat-x; +} +.navbar-inner { + min-height: 40px; + padding-right: 20px; + padding-left: 20px; + background-color: #2c2c2c; + background-image: -moz-linear-gradient(top, #000000, #680001); + background-image: -ms-linear-gradient(top, #000000, #680001); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#000000), to(#680001)); + background-image: -webkit-linear-gradient(top, #000000, #680001); + background-image: -o-linear-gradient(top, #000000, #680001); + background-image: linear-gradient(top, #000000, #680001); + background-repeat: repeat-x; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#000000', endColorstr='#680001', GradientType=0); + -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.1); + -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.1); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.1); +} +.btn-primary { + background-color: #444; + *background-color: #444444; + background-image: -ms-linear-gradient(top, #111111, #444444); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#111111), to(#444444)); + background-image: -webkit-linear-gradient(top, #111111, #444444); + background-image: -o-linear-gradient(top, #111111, #444444); + background-image: -moz-linear-gradient(top, #111111, #444444); + background-image: linear-gradient(top, #111111, #444444); + background-repeat: repeat-x; + border-color: #444444 #444444 #003580; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#111111', endColorstr='#444444', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); +} +.btn-primary, +.btn-primary:hover { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color:#444444; +} +.pizza-logo{ + padding-top:10px; + padding-bottom:10px; +} +.thumbnail{ + text-align:center; +} +h1{ + margin-bottom:20px; + color:#680001; +} +.thumbnails div.thumbnail{ + height:230px; + } \ No newline at end of file diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/images/UCL_Natl.png b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/images/UCL_Natl.png new file mode 100644 index 0000000000..d01a657c98 Binary files /dev/null and b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/images/UCL_Natl.png differ diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/images/shack-logo.png b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/images/shack-logo.png new file mode 100644 index 0000000000..aff96b98d5 Binary files /dev/null and b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/images/shack-logo.png differ diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/include_head.jsp b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/include_head.jsp new file mode 100644 index 0000000000..705fea9f03 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/include_head.jsp @@ -0,0 +1,17 @@ + +Pizza Shack + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/include_head_row.jsp b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/include_head_row.jsp new file mode 100644 index 0000000000..5af967c0a5 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/include_head_row.jsp @@ -0,0 +1,5 @@ +
    + +
    \ No newline at end of file diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/index.jsp b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/index.jsp new file mode 100644 index 0000000000..d063f0cc8f --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/index.jsp @@ -0,0 +1,95 @@ + +<%@page import="com.pizzashack.client.web.PizzaShackWebConfiguration"%> +<%@page import="com.pizzashack.client.dto.Pizza"%> +<%@page import="java.util.List"%> +<%@page import="com.pizzashack.client.web.MenuItemManager"%> +<% + String token = (String) session.getAttribute("access.token"); + if (token == null) { + response.sendRedirect("login.jsp"); + return; + } +%> + + + + + + + + +
    + + + + +
    + +
    + +
    + <% + String orderId = request.getParameter("orderId"); + if (orderId != null) { + %> +

    Your last order has been submitted. Please note the order ID:
    <%=orderId %>

    + <% + } + %> +
    + +

    CHOOSE YOUR PIZZA

    + +
      + <% + MenuItemManager manager = new MenuItemManager(); + List menuItems = manager.getAvailablePizzaList(token); + String serverURL = PizzaShackWebConfiguration.getInstance().getServerURL(); + %> + <% + for (Pizza item : menuItems) { + %> + + +
    • +
      + " alt=""> + +
      +
      <%=item.getName()%>
      + +

      <%=item.getDescription()%>

      + +

      Order Now

      +
      +
      +
    • + + <% + } + %> +
    +
    +
    + +
    + + + + + diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/lib/css/bootstrap.css b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/lib/css/bootstrap.css new file mode 100644 index 0000000000..bb40c85f7d --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/lib/css/bootstrap.css @@ -0,0 +1,4983 @@ +/*! + * Bootstrap v2.0.4 + * + * Copyright 2012 Twitter, Inc + * Licensed under the Apache License v2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Designed and built with all the love in the world @twitter by @mdo and @fat. + */ + +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +nav, +section { + display: block; +} + +audio, +canvas, +video { + display: inline-block; + *display: inline; + *zoom: 1; +} + +audio:not([controls]) { + display: none; +} + +html { + font-size: 100%; + -webkit-text-size-adjust: 100%; + -ms-text-size-adjust: 100%; +} + +a:focus { + outline: thin dotted #333; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; +} + +a:hover, +a:active { + outline: 0; +} + +sub, +sup { + position: relative; + font-size: 75%; + line-height: 0; + vertical-align: baseline; +} + +sup { + top: -0.5em; +} + +sub { + bottom: -0.25em; +} + +img { + max-width: 100%; + vertical-align: middle; + border: 0; + -ms-interpolation-mode: bicubic; +} + +#map_canvas img { + max-width: none; +} + +button, +input, +select, +textarea { + margin: 0; + font-size: 100%; + vertical-align: middle; +} + +button, +input { + *overflow: visible; + line-height: normal; +} + +button::-moz-focus-inner, +input::-moz-focus-inner { + padding: 0; + border: 0; +} + +button, +input[type="button"], +input[type="reset"], +input[type="submit"] { + cursor: pointer; + -webkit-appearance: button; +} + +input[type="search"] { + -webkit-box-sizing: content-box; + -moz-box-sizing: content-box; + box-sizing: content-box; + -webkit-appearance: textfield; +} + +input[type="search"]::-webkit-search-decoration, +input[type="search"]::-webkit-search-cancel-button { + -webkit-appearance: none; +} + +textarea { + overflow: auto; + vertical-align: top; +} + +.clearfix { + *zoom: 1; +} + +.clearfix:before, +.clearfix:after { + display: table; + content: ""; +} + +.clearfix:after { + clear: both; +} + +.hide-text { + font: 0/0 a; + color: transparent; + text-shadow: none; + background-color: transparent; + border: 0; +} + +.input-block-level { + display: block; + width: 100%; + min-height: 28px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + -ms-box-sizing: border-box; + box-sizing: border-box; +} + +body { + margin: 0; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 13px; + line-height: 18px; + color: #333333; + background-color: #ffffff; +} + +a { + color: #0088cc; + text-decoration: none; +} + +a:hover { + color: #005580; + text-decoration: underline; +} + +.row { + margin-left: -20px; + *zoom: 1; +} + +.row:before, +.row:after { + display: table; + content: ""; +} + +.row:after { + clear: both; +} + +[class*="span"] { + float: left; + margin-left: 20px; +} + +.container, +.navbar-fixed-top .container, +.navbar-fixed-bottom .container { + width: 940px; +} + +.span12 { + width: 940px; +} + +.span11 { + width: 860px; +} + +.span10 { + width: 780px; +} + +.span9 { + width: 700px; +} + +.span8 { + width: 620px; +} + +.span7 { + width: 540px; +} + +.span6 { + width: 460px; +} + +.span5 { + width: 380px; +} + +.span4 { + width: 300px; +} + +.span3 { + width: 220px; +} + +.span2 { + width: 140px; +} + +.span1 { + width: 60px; +} + +.offset12 { + margin-left: 980px; +} + +.offset11 { + margin-left: 900px; +} + +.offset10 { + margin-left: 820px; +} + +.offset9 { + margin-left: 740px; +} + +.offset8 { + margin-left: 660px; +} + +.offset7 { + margin-left: 580px; +} + +.offset6 { + margin-left: 500px; +} + +.offset5 { + margin-left: 420px; +} + +.offset4 { + margin-left: 340px; +} + +.offset3 { + margin-left: 260px; +} + +.offset2 { + margin-left: 180px; +} + +.offset1 { + margin-left: 100px; +} + +.row-fluid { + width: 100%; + *zoom: 1; +} + +.row-fluid:before, +.row-fluid:after { + display: table; + content: ""; +} + +.row-fluid:after { + clear: both; +} + +.row-fluid [class*="span"] { + display: block; + float: left; + width: 100%; + min-height: 28px; + margin-left: 2.127659574%; + *margin-left: 2.0744680846382977%; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + -ms-box-sizing: border-box; + box-sizing: border-box; +} + +.row-fluid [class*="span"]:first-child { + margin-left: 0; +} + +.row-fluid .span12 { + width: 99.99999998999999%; + *width: 99.94680850063828%; +} + +.row-fluid .span11 { + width: 91.489361693%; + *width: 91.4361702036383%; +} + +.row-fluid .span10 { + width: 82.97872339599999%; + *width: 82.92553190663828%; +} + +.row-fluid .span9 { + width: 74.468085099%; + *width: 74.4148936096383%; +} + +.row-fluid .span8 { + width: 65.95744680199999%; + *width: 65.90425531263828%; +} + +.row-fluid .span7 { + width: 57.446808505%; + *width: 57.3936170156383%; +} + +.row-fluid .span6 { + width: 48.93617020799999%; + *width: 48.88297871863829%; +} + +.row-fluid .span5 { + width: 40.425531911%; + *width: 40.3723404216383%; +} + +.row-fluid .span4 { + width: 31.914893614%; + *width: 31.8617021246383%; +} + +.row-fluid .span3 { + width: 23.404255317%; + *width: 23.3510638276383%; +} + +.row-fluid .span2 { + width: 14.89361702%; + *width: 14.8404255306383%; +} + +.row-fluid .span1 { + width: 6.382978723%; + *width: 6.329787233638298%; +} + +.container { + margin-right: auto; + margin-left: auto; + *zoom: 1; +} + +.container:before, +.container:after { + display: table; + content: ""; +} + +.container:after { + clear: both; +} + +.container-fluid { + padding-right: 20px; + padding-left: 20px; + *zoom: 1; +} + +.container-fluid:before, +.container-fluid:after { + display: table; + content: ""; +} + +.container-fluid:after { + clear: both; +} + +p { + margin: 0 0 9px; +} + +p small { + font-size: 11px; + color: #999999; +} + +.lead { + margin-bottom: 18px; + font-size: 20px; + font-weight: 200; + line-height: 27px; +} + +h1, +h2, +h3, +h4, +h5, +h6 { + margin: 0; + font-family: inherit; + font-weight: bold; + color: inherit; + text-rendering: optimizelegibility; +} + +h1 small, +h2 small, +h3 small, +h4 small, +h5 small, +h6 small { + font-weight: normal; + color: #999999; +} + +h1 { + font-size: 30px; + line-height: 36px; +} + +h1 small { + font-size: 18px; +} + +h2 { + font-size: 24px; + line-height: 36px; +} + +h2 small { + font-size: 18px; +} + +h3 { + font-size: 18px; + line-height: 27px; +} + +h3 small { + font-size: 14px; +} + +h4, +h5, +h6 { + line-height: 18px; +} + +h4 { + font-size: 14px; +} + +h4 small { + font-size: 12px; +} + +h5 { + font-size: 12px; +} + +h6 { + font-size: 11px; + color: #999999; + text-transform: uppercase; +} + +.page-header { + padding-bottom: 17px; + margin: 18px 0; + border-bottom: 1px solid #eeeeee; +} + +.page-header h1 { + line-height: 1; +} + +ul, +ol { + padding: 0; + margin: 0 0 9px 25px; +} + +ul ul, +ul ol, +ol ol, +ol ul { + margin-bottom: 0; +} + +ul { + list-style: disc; +} + +ol { + list-style: decimal; +} + +li { + line-height: 18px; +} + +ul.unstyled, +ol.unstyled { + margin-left: 0; + list-style: none; +} + +dl { + margin-bottom: 18px; +} + +dt, +dd { + line-height: 18px; +} + +dt { + font-weight: bold; + line-height: 17px; +} + +dd { + margin-left: 9px; +} + +.dl-horizontal dt { + float: left; + width: 120px; + overflow: hidden; + clear: left; + text-align: right; + text-overflow: ellipsis; + white-space: nowrap; +} + +.dl-horizontal dd { + margin-left: 130px; +} + +hr { + margin: 18px 0; + border: 0; + border-top: 1px solid #eeeeee; + border-bottom: 1px solid #ffffff; +} + +strong { + font-weight: bold; +} + +em { + font-style: italic; +} + +.muted { + color: #999999; +} + +abbr[title] { + cursor: help; + border-bottom: 1px dotted #999999; +} + +abbr.initialism { + font-size: 90%; + text-transform: uppercase; +} + +blockquote { + padding: 0 0 0 15px; + margin: 0 0 18px; + border-left: 5px solid #eeeeee; +} + +blockquote p { + margin-bottom: 0; + font-size: 16px; + font-weight: 300; + line-height: 22.5px; +} + +blockquote small { + display: block; + line-height: 18px; + color: #999999; +} + +blockquote small:before { + content: '\2014 \00A0'; +} + +blockquote.pull-right { + float: right; + padding-right: 15px; + padding-left: 0; + border-right: 5px solid #eeeeee; + border-left: 0; +} + +blockquote.pull-right p, +blockquote.pull-right small { + text-align: right; +} + +q:before, +q:after, +blockquote:before, +blockquote:after { + content: ""; +} + +address { + display: block; + margin-bottom: 18px; + font-style: normal; + line-height: 18px; +} + +small { + font-size: 100%; +} + +cite { + font-style: normal; +} + +code, +pre { + padding: 0 3px 2px; + font-family: Menlo, Monaco, Consolas, "Courier New", monospace; + font-size: 12px; + color: #333333; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} + +code { + padding: 2px 4px; + color: #d14; + background-color: #f7f7f9; + border: 1px solid #e1e1e8; +} + +pre { + display: block; + padding: 8.5px; + margin: 0 0 9px; + font-size: 12.025px; + line-height: 18px; + word-break: break-all; + word-wrap: break-word; + white-space: pre; + white-space: pre-wrap; + background-color: #f5f5f5; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, 0.15); + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} + +pre.prettyprint { + margin-bottom: 18px; +} + +pre code { + padding: 0; + color: inherit; + background-color: transparent; + border: 0; +} + +.pre-scrollable { + max-height: 340px; + overflow-y: scroll; +} + +form { + margin: 0 0 18px; +} + +fieldset { + padding: 0; + margin: 0; + border: 0; +} + +legend { + display: block; + width: 100%; + padding: 0; + margin-bottom: 27px; + font-size: 19.5px; + line-height: 36px; + color: #333333; + border: 0; + border-bottom: 1px solid #e5e5e5; +} + +legend small { + font-size: 13.5px; + color: #999999; +} + +label, +input, +button, +select, +textarea { + font-size: 13px; + font-weight: normal; + line-height: 18px; +} + +input, +button, +select, +textarea { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; +} + +label { + display: block; + margin-bottom: 5px; +} + +select, +textarea, +input[type="text"], +input[type="password"], +input[type="datetime"], +input[type="datetime-local"], +input[type="date"], +input[type="month"], +input[type="time"], +input[type="week"], +input[type="number"], +input[type="email"], +input[type="url"], +input[type="search"], +input[type="tel"], +input[type="color"], +.uneditable-input { + display: inline-block; + height: 18px; + padding: 4px; + margin-bottom: 9px; + font-size: 13px; + line-height: 18px; + color: #555555; +} + +input, +textarea { + width: 210px; +} + +textarea { + height: auto; +} + +textarea, +input[type="text"], +input[type="password"], +input[type="datetime"], +input[type="datetime-local"], +input[type="date"], +input[type="month"], +input[type="time"], +input[type="week"], +input[type="number"], +input[type="email"], +input[type="url"], +input[type="search"], +input[type="tel"], +input[type="color"], +.uneditable-input { + background-color: #ffffff; + border: 1px solid #cccccc; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -webkit-transition: border linear 0.2s, box-shadow linear 0.2s; + -moz-transition: border linear 0.2s, box-shadow linear 0.2s; + -ms-transition: border linear 0.2s, box-shadow linear 0.2s; + -o-transition: border linear 0.2s, box-shadow linear 0.2s; + transition: border linear 0.2s, box-shadow linear 0.2s; +} + +textarea:focus, +input[type="text"]:focus, +input[type="password"]:focus, +input[type="datetime"]:focus, +input[type="datetime-local"]:focus, +input[type="date"]:focus, +input[type="month"]:focus, +input[type="time"]:focus, +input[type="week"]:focus, +input[type="number"]:focus, +input[type="email"]:focus, +input[type="url"]:focus, +input[type="search"]:focus, +input[type="tel"]:focus, +input[type="color"]:focus, +.uneditable-input:focus { + border-color: rgba(82, 168, 236, 0.8); + outline: 0; + outline: thin dotted \9; + /* IE6-9 */ + + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); +} + +input[type="radio"], +input[type="checkbox"] { + margin: 3px 0; + *margin-top: 0; + /* IE7 */ + + line-height: normal; + cursor: pointer; +} + +input[type="submit"], +input[type="reset"], +input[type="button"], +input[type="radio"], +input[type="checkbox"] { + width: auto; +} + +.uneditable-textarea { + width: auto; + height: auto; +} + +select, +input[type="file"] { + height: 28px; + /* In IE7, the height of the select element cannot be changed by height, only font-size */ + + *margin-top: 4px; + /* For IE7, add top margin to align select with labels */ + + line-height: 28px; +} + +select { + width: 220px; + border: 1px solid #bbb; +} + +select[multiple], +select[size] { + height: auto; +} + +select:focus, +input[type="file"]:focus, +input[type="radio"]:focus, +input[type="checkbox"]:focus { + outline: thin dotted #333; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; +} + +.radio, +.checkbox { + min-height: 18px; + padding-left: 18px; +} + +.radio input[type="radio"], +.checkbox input[type="checkbox"] { + float: left; + margin-left: -18px; +} + +.controls > .radio:first-child, +.controls > .checkbox:first-child { + padding-top: 5px; +} + +.radio.inline, +.checkbox.inline { + display: inline-block; + padding-top: 5px; + margin-bottom: 0; + vertical-align: middle; +} + +.radio.inline + .radio.inline, +.checkbox.inline + .checkbox.inline { + margin-left: 10px; +} + +.input-mini { + width: 60px; +} + +.input-small { + width: 90px; +} + +.input-medium { + width: 150px; +} + +.input-large { + width: 210px; +} + +.input-xlarge { + width: 270px; +} + +.input-xxlarge { + width: 530px; +} + +input[class*="span"], +select[class*="span"], +textarea[class*="span"], +.uneditable-input[class*="span"], +.row-fluid input[class*="span"], +.row-fluid select[class*="span"], +.row-fluid textarea[class*="span"], +.row-fluid .uneditable-input[class*="span"] { + float: none; + margin-left: 0; +} + +.input-append input[class*="span"], +.input-append .uneditable-input[class*="span"], +.input-prepend input[class*="span"], +.input-prepend .uneditable-input[class*="span"], +.row-fluid .input-prepend [class*="span"], +.row-fluid .input-append [class*="span"] { + display: inline-block; +} + +input, +textarea, +.uneditable-input { + margin-left: 0; +} + +input.span12, +textarea.span12, +.uneditable-input.span12 { + width: 930px; +} + +input.span11, +textarea.span11, +.uneditable-input.span11 { + width: 850px; +} + +input.span10, +textarea.span10, +.uneditable-input.span10 { + width: 770px; +} + +input.span9, +textarea.span9, +.uneditable-input.span9 { + width: 690px; +} + +input.span8, +textarea.span8, +.uneditable-input.span8 { + width: 610px; +} + +input.span7, +textarea.span7, +.uneditable-input.span7 { + width: 530px; +} + +input.span6, +textarea.span6, +.uneditable-input.span6 { + width: 450px; +} + +input.span5, +textarea.span5, +.uneditable-input.span5 { + width: 370px; +} + +input.span4, +textarea.span4, +.uneditable-input.span4 { + width: 290px; +} + +input.span3, +textarea.span3, +.uneditable-input.span3 { + width: 210px; +} + +input.span2, +textarea.span2, +.uneditable-input.span2 { + width: 130px; +} + +input.span1, +textarea.span1, +.uneditable-input.span1 { + width: 50px; +} + +input[disabled], +select[disabled], +textarea[disabled], +input[readonly], +select[readonly], +textarea[readonly] { + cursor: not-allowed; + background-color: #eeeeee; + border-color: #ddd; +} + +input[type="radio"][disabled], +input[type="checkbox"][disabled], +input[type="radio"][readonly], +input[type="checkbox"][readonly] { + background-color: transparent; +} + +.control-group.warning > label, +.control-group.warning .help-block, +.control-group.warning .help-inline { + color: #c09853; +} + +.control-group.warning .checkbox, +.control-group.warning .radio, +.control-group.warning input, +.control-group.warning select, +.control-group.warning textarea { + color: #c09853; + border-color: #c09853; +} + +.control-group.warning .checkbox:focus, +.control-group.warning .radio:focus, +.control-group.warning input:focus, +.control-group.warning select:focus, +.control-group.warning textarea:focus { + border-color: #a47e3c; + -webkit-box-shadow: 0 0 6px #dbc59e; + -moz-box-shadow: 0 0 6px #dbc59e; + box-shadow: 0 0 6px #dbc59e; +} + +.control-group.warning .input-prepend .add-on, +.control-group.warning .input-append .add-on { + color: #c09853; + background-color: #fcf8e3; + border-color: #c09853; +} + +.control-group.error > label, +.control-group.error .help-block, +.control-group.error .help-inline { + color: #b94a48; +} + +.control-group.error .checkbox, +.control-group.error .radio, +.control-group.error input, +.control-group.error select, +.control-group.error textarea { + color: #b94a48; + border-color: #b94a48; +} + +.control-group.error .checkbox:focus, +.control-group.error .radio:focus, +.control-group.error input:focus, +.control-group.error select:focus, +.control-group.error textarea:focus { + border-color: #953b39; + -webkit-box-shadow: 0 0 6px #d59392; + -moz-box-shadow: 0 0 6px #d59392; + box-shadow: 0 0 6px #d59392; +} + +.control-group.error .input-prepend .add-on, +.control-group.error .input-append .add-on { + color: #b94a48; + background-color: #f2dede; + border-color: #b94a48; +} + +.control-group.success > label, +.control-group.success .help-block, +.control-group.success .help-inline { + color: #468847; +} + +.control-group.success .checkbox, +.control-group.success .radio, +.control-group.success input, +.control-group.success select, +.control-group.success textarea { + color: #468847; + border-color: #468847; +} + +.control-group.success .checkbox:focus, +.control-group.success .radio:focus, +.control-group.success input:focus, +.control-group.success select:focus, +.control-group.success textarea:focus { + border-color: #356635; + -webkit-box-shadow: 0 0 6px #7aba7b; + -moz-box-shadow: 0 0 6px #7aba7b; + box-shadow: 0 0 6px #7aba7b; +} + +.control-group.success .input-prepend .add-on, +.control-group.success .input-append .add-on { + color: #468847; + background-color: #dff0d8; + border-color: #468847; +} + +input:focus:required:invalid, +textarea:focus:required:invalid, +select:focus:required:invalid { + color: #b94a48; + border-color: #ee5f5b; +} + +input:focus:required:invalid:focus, +textarea:focus:required:invalid:focus, +select:focus:required:invalid:focus { + border-color: #e9322d; + -webkit-box-shadow: 0 0 6px #f8b9b7; + -moz-box-shadow: 0 0 6px #f8b9b7; + box-shadow: 0 0 6px #f8b9b7; +} + +.form-actions { + padding: 17px 20px 18px; + margin-top: 18px; + margin-bottom: 18px; + background-color: #f5f5f5; + border-top: 1px solid #e5e5e5; + *zoom: 1; +} + +.form-actions:before, +.form-actions:after { + display: table; + content: ""; +} + +.form-actions:after { + clear: both; +} + +.uneditable-input { + overflow: hidden; + white-space: nowrap; + cursor: not-allowed; + background-color: #ffffff; + border-color: #eee; + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); + -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); +} + +:-moz-placeholder { + color: #999999; +} + +:-ms-input-placeholder { + color: #999999; +} + +::-webkit-input-placeholder { + color: #999999; +} + +.help-block, +.help-inline { + color: #555555; +} + +.help-block { + display: block; + margin-bottom: 9px; +} + +.help-inline { + display: inline-block; + *display: inline; + padding-left: 5px; + vertical-align: middle; + *zoom: 1; +} + +.input-prepend, +.input-append { + margin-bottom: 5px; +} + +.input-prepend input, +.input-append input, +.input-prepend select, +.input-append select, +.input-prepend .uneditable-input, +.input-append .uneditable-input { + position: relative; + margin-bottom: 0; + *margin-left: 0; + vertical-align: middle; + -webkit-border-radius: 0 3px 3px 0; + -moz-border-radius: 0 3px 3px 0; + border-radius: 0 3px 3px 0; +} + +.input-prepend input:focus, +.input-append input:focus, +.input-prepend select:focus, +.input-append select:focus, +.input-prepend .uneditable-input:focus, +.input-append .uneditable-input:focus { + z-index: 2; +} + +.input-prepend .uneditable-input, +.input-append .uneditable-input { + border-left-color: #ccc; +} + +.input-prepend .add-on, +.input-append .add-on { + display: inline-block; + width: auto; + height: 18px; + min-width: 16px; + padding: 4px 5px; + font-weight: normal; + line-height: 18px; + text-align: center; + text-shadow: 0 1px 0 #ffffff; + vertical-align: middle; + background-color: #eeeeee; + border: 1px solid #ccc; +} + +.input-prepend .add-on, +.input-append .add-on, +.input-prepend .btn, +.input-append .btn { + margin-left: -1px; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} + +.input-prepend .active, +.input-append .active { + background-color: #a9dba9; + border-color: #46a546; +} + +.input-prepend .add-on, +.input-prepend .btn { + margin-right: -1px; +} + +.input-prepend .add-on:first-child, +.input-prepend .btn:first-child { + -webkit-border-radius: 3px 0 0 3px; + -moz-border-radius: 3px 0 0 3px; + border-radius: 3px 0 0 3px; +} + +.input-append input, +.input-append select, +.input-append .uneditable-input { + -webkit-border-radius: 3px 0 0 3px; + -moz-border-radius: 3px 0 0 3px; + border-radius: 3px 0 0 3px; +} + +.input-append .uneditable-input { + border-right-color: #ccc; + border-left-color: #eee; +} + +.input-append .add-on:last-child, +.input-append .btn:last-child { + -webkit-border-radius: 0 3px 3px 0; + -moz-border-radius: 0 3px 3px 0; + border-radius: 0 3px 3px 0; +} + +.input-prepend.input-append input, +.input-prepend.input-append select, +.input-prepend.input-append .uneditable-input { + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} + +.input-prepend.input-append .add-on:first-child, +.input-prepend.input-append .btn:first-child { + margin-right: -1px; + -webkit-border-radius: 3px 0 0 3px; + -moz-border-radius: 3px 0 0 3px; + border-radius: 3px 0 0 3px; +} + +.input-prepend.input-append .add-on:last-child, +.input-prepend.input-append .btn:last-child { + margin-left: -1px; + -webkit-border-radius: 0 3px 3px 0; + -moz-border-radius: 0 3px 3px 0; + border-radius: 0 3px 3px 0; +} + +.search-query { + padding-right: 14px; + padding-right: 4px \9; + padding-left: 14px; + padding-left: 4px \9; + /* IE7-8 doesn't have border-radius, so don't indent the padding */ + + margin-bottom: 0; + -webkit-border-radius: 14px; + -moz-border-radius: 14px; + border-radius: 14px; +} + +.form-search input, +.form-inline input, +.form-horizontal input, +.form-search textarea, +.form-inline textarea, +.form-horizontal textarea, +.form-search select, +.form-inline select, +.form-horizontal select, +.form-search .help-inline, +.form-inline .help-inline, +.form-horizontal .help-inline, +.form-search .uneditable-input, +.form-inline .uneditable-input, +.form-horizontal .uneditable-input, +.form-search .input-prepend, +.form-inline .input-prepend, +.form-horizontal .input-prepend, +.form-search .input-append, +.form-inline .input-append, +.form-horizontal .input-append { + display: inline-block; + *display: inline; + margin-bottom: 0; + *zoom: 1; +} + +.form-search .hide, +.form-inline .hide, +.form-horizontal .hide { + display: none; +} + +.form-search label, +.form-inline label { + display: inline-block; +} + +.form-search .input-append, +.form-inline .input-append, +.form-search .input-prepend, +.form-inline .input-prepend { + margin-bottom: 0; +} + +.form-search .radio, +.form-search .checkbox, +.form-inline .radio, +.form-inline .checkbox { + padding-left: 0; + margin-bottom: 0; + vertical-align: middle; +} + +.form-search .radio input[type="radio"], +.form-search .checkbox input[type="checkbox"], +.form-inline .radio input[type="radio"], +.form-inline .checkbox input[type="checkbox"] { + float: left; + margin-right: 3px; + margin-left: 0; +} + +.control-group { + margin-bottom: 9px; +} + +legend + .control-group { + margin-top: 18px; + -webkit-margin-top-collapse: separate; +} + +.form-horizontal .control-group { + margin-bottom: 18px; + *zoom: 1; +} + +.form-horizontal .control-group:before, +.form-horizontal .control-group:after { + display: table; + content: ""; +} + +.form-horizontal .control-group:after { + clear: both; +} + +.form-horizontal .control-label { + float: left; + width: 140px; + padding-top: 5px; + text-align: right; +} + +.form-horizontal .controls { + *display: inline-block; + *padding-left: 20px; + margin-left: 160px; + *margin-left: 0; +} + +.form-horizontal .controls:first-child { + *padding-left: 160px; +} + +.form-horizontal .help-block { + margin-top: 9px; + margin-bottom: 0; +} + +.form-horizontal .form-actions { + padding-left: 160px; +} + +table { + max-width: 100%; + background-color: transparent; + border-collapse: collapse; + border-spacing: 0; +} + +.table { + width: 100%; + margin-bottom: 18px; +} + +.table th, +.table td { + padding: 8px; + line-height: 18px; + text-align: left; + vertical-align: top; + border-top: 1px solid #dddddd; +} + +.table th { + font-weight: bold; +} + +.table thead th { + vertical-align: bottom; +} + +.table caption + thead tr:first-child th, +.table caption + thead tr:first-child td, +.table colgroup + thead tr:first-child th, +.table colgroup + thead tr:first-child td, +.table thead:first-child tr:first-child th, +.table thead:first-child tr:first-child td { + border-top: 0; +} + +.table tbody + tbody { + border-top: 2px solid #dddddd; +} + +.table-condensed th, +.table-condensed td { + padding: 4px 5px; +} + +.table-bordered { + border: 1px solid #dddddd; + border-collapse: separate; + *border-collapse: collapsed; + border-left: 0; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} + +.table-bordered th, +.table-bordered td { + border-left: 1px solid #dddddd; +} + +.table-bordered caption + thead tr:first-child th, +.table-bordered caption + tbody tr:first-child th, +.table-bordered caption + tbody tr:first-child td, +.table-bordered colgroup + thead tr:first-child th, +.table-bordered colgroup + tbody tr:first-child th, +.table-bordered colgroup + tbody tr:first-child td, +.table-bordered thead:first-child tr:first-child th, +.table-bordered tbody:first-child tr:first-child th, +.table-bordered tbody:first-child tr:first-child td { + border-top: 0; +} + +.table-bordered thead:first-child tr:first-child th:first-child, +.table-bordered tbody:first-child tr:first-child td:first-child { + -webkit-border-top-left-radius: 4px; + border-top-left-radius: 4px; + -moz-border-radius-topleft: 4px; +} + +.table-bordered thead:first-child tr:first-child th:last-child, +.table-bordered tbody:first-child tr:first-child td:last-child { + -webkit-border-top-right-radius: 4px; + border-top-right-radius: 4px; + -moz-border-radius-topright: 4px; +} + +.table-bordered thead:last-child tr:last-child th:first-child, +.table-bordered tbody:last-child tr:last-child td:first-child { + -webkit-border-radius: 0 0 0 4px; + -moz-border-radius: 0 0 0 4px; + border-radius: 0 0 0 4px; + -webkit-border-bottom-left-radius: 4px; + border-bottom-left-radius: 4px; + -moz-border-radius-bottomleft: 4px; +} + +.table-bordered thead:last-child tr:last-child th:last-child, +.table-bordered tbody:last-child tr:last-child td:last-child { + -webkit-border-bottom-right-radius: 4px; + border-bottom-right-radius: 4px; + -moz-border-radius-bottomright: 4px; +} + +.table-striped tbody tr:nth-child(odd) td, +.table-striped tbody tr:nth-child(odd) th { + background-color: #f9f9f9; +} + +.table tbody tr:hover td, +.table tbody tr:hover th { + background-color: #f5f5f5; +} + +table .span1 { + float: none; + width: 44px; + margin-left: 0; +} + +table .span2 { + float: none; + width: 124px; + margin-left: 0; +} + +table .span3 { + float: none; + width: 204px; + margin-left: 0; +} + +table .span4 { + float: none; + width: 284px; + margin-left: 0; +} + +table .span5 { + float: none; + width: 364px; + margin-left: 0; +} + +table .span6 { + float: none; + width: 444px; + margin-left: 0; +} + +table .span7 { + float: none; + width: 524px; + margin-left: 0; +} + +table .span8 { + float: none; + width: 604px; + margin-left: 0; +} + +table .span9 { + float: none; + width: 684px; + margin-left: 0; +} + +table .span10 { + float: none; + width: 764px; + margin-left: 0; +} + +table .span11 { + float: none; + width: 844px; + margin-left: 0; +} + +table .span12 { + float: none; + width: 924px; + margin-left: 0; +} + +table .span13 { + float: none; + width: 1004px; + margin-left: 0; +} + +table .span14 { + float: none; + width: 1084px; + margin-left: 0; +} + +table .span15 { + float: none; + width: 1164px; + margin-left: 0; +} + +table .span16 { + float: none; + width: 1244px; + margin-left: 0; +} + +table .span17 { + float: none; + width: 1324px; + margin-left: 0; +} + +table .span18 { + float: none; + width: 1404px; + margin-left: 0; +} + +table .span19 { + float: none; + width: 1484px; + margin-left: 0; +} + +table .span20 { + float: none; + width: 1564px; + margin-left: 0; +} + +table .span21 { + float: none; + width: 1644px; + margin-left: 0; +} + +table .span22 { + float: none; + width: 1724px; + margin-left: 0; +} + +table .span23 { + float: none; + width: 1804px; + margin-left: 0; +} + +table .span24 { + float: none; + width: 1884px; + margin-left: 0; +} + +[class^="icon-"], +[class*=" icon-"] { + display: inline-block; + width: 14px; + height: 14px; + *margin-right: .3em; + line-height: 14px; + vertical-align: text-top; + background-image: url("../img/glyphicons-halflings.png"); + background-position: 14px 14px; + background-repeat: no-repeat; +} + +[class^="icon-"]:last-child, +[class*=" icon-"]:last-child { + *margin-left: 0; +} + +.icon-white { + background-image: url("../img/glyphicons-halflings-white.png"); +} + +.icon-glass { + background-position: 0 0; +} + +.icon-music { + background-position: -24px 0; +} + +.icon-search { + background-position: -48px 0; +} + +.icon-envelope { + background-position: -72px 0; +} + +.icon-heart { + background-position: -96px 0; +} + +.icon-star { + background-position: -120px 0; +} + +.icon-star-empty { + background-position: -144px 0; +} + +.icon-user { + background-position: -168px 0; +} + +.icon-film { + background-position: -192px 0; +} + +.icon-th-large { + background-position: -216px 0; +} + +.icon-th { + background-position: -240px 0; +} + +.icon-th-list { + background-position: -264px 0; +} + +.icon-ok { + background-position: -288px 0; +} + +.icon-remove { + background-position: -312px 0; +} + +.icon-zoom-in { + background-position: -336px 0; +} + +.icon-zoom-out { + background-position: -360px 0; +} + +.icon-off { + background-position: -384px 0; +} + +.icon-signal { + background-position: -408px 0; +} + +.icon-cog { + background-position: -432px 0; +} + +.icon-trash { + background-position: -456px 0; +} + +.icon-home { + background-position: 0 -24px; +} + +.icon-file { + background-position: -24px -24px; +} + +.icon-time { + background-position: -48px -24px; +} + +.icon-road { + background-position: -72px -24px; +} + +.icon-download-alt { + background-position: -96px -24px; +} + +.icon-download { + background-position: -120px -24px; +} + +.icon-upload { + background-position: -144px -24px; +} + +.icon-inbox { + background-position: -168px -24px; +} + +.icon-play-circle { + background-position: -192px -24px; +} + +.icon-repeat { + background-position: -216px -24px; +} + +.icon-refresh { + background-position: -240px -24px; +} + +.icon-list-alt { + background-position: -264px -24px; +} + +.icon-lock { + background-position: -287px -24px; +} + +.icon-flag { + background-position: -312px -24px; +} + +.icon-headphones { + background-position: -336px -24px; +} + +.icon-volume-off { + background-position: -360px -24px; +} + +.icon-volume-down { + background-position: -384px -24px; +} + +.icon-volume-up { + background-position: -408px -24px; +} + +.icon-qrcode { + background-position: -432px -24px; +} + +.icon-barcode { + background-position: -456px -24px; +} + +.icon-tag { + background-position: 0 -48px; +} + +.icon-tags { + background-position: -25px -48px; +} + +.icon-book { + background-position: -48px -48px; +} + +.icon-bookmark { + background-position: -72px -48px; +} + +.icon-print { + background-position: -96px -48px; +} + +.icon-camera { + background-position: -120px -48px; +} + +.icon-font { + background-position: -144px -48px; +} + +.icon-bold { + background-position: -167px -48px; +} + +.icon-italic { + background-position: -192px -48px; +} + +.icon-text-height { + background-position: -216px -48px; +} + +.icon-text-width { + background-position: -240px -48px; +} + +.icon-align-left { + background-position: -264px -48px; +} + +.icon-align-center { + background-position: -288px -48px; +} + +.icon-align-right { + background-position: -312px -48px; +} + +.icon-align-justify { + background-position: -336px -48px; +} + +.icon-list { + background-position: -360px -48px; +} + +.icon-indent-left { + background-position: -384px -48px; +} + +.icon-indent-right { + background-position: -408px -48px; +} + +.icon-facetime-video { + background-position: -432px -48px; +} + +.icon-picture { + background-position: -456px -48px; +} + +.icon-pencil { + background-position: 0 -72px; +} + +.icon-map-marker { + background-position: -24px -72px; +} + +.icon-adjust { + background-position: -48px -72px; +} + +.icon-tint { + background-position: -72px -72px; +} + +.icon-edit { + background-position: -96px -72px; +} + +.icon-share { + background-position: -120px -72px; +} + +.icon-check { + background-position: -144px -72px; +} + +.icon-move { + background-position: -168px -72px; +} + +.icon-step-backward { + background-position: -192px -72px; +} + +.icon-fast-backward { + background-position: -216px -72px; +} + +.icon-backward { + background-position: -240px -72px; +} + +.icon-play { + background-position: -264px -72px; +} + +.icon-pause { + background-position: -288px -72px; +} + +.icon-stop { + background-position: -312px -72px; +} + +.icon-forward { + background-position: -336px -72px; +} + +.icon-fast-forward { + background-position: -360px -72px; +} + +.icon-step-forward { + background-position: -384px -72px; +} + +.icon-eject { + background-position: -408px -72px; +} + +.icon-chevron-left { + background-position: -432px -72px; +} + +.icon-chevron-right { + background-position: -456px -72px; +} + +.icon-plus-sign { + background-position: 0 -96px; +} + +.icon-minus-sign { + background-position: -24px -96px; +} + +.icon-remove-sign { + background-position: -48px -96px; +} + +.icon-ok-sign { + background-position: -72px -96px; +} + +.icon-question-sign { + background-position: -96px -96px; +} + +.icon-info-sign { + background-position: -120px -96px; +} + +.icon-screenshot { + background-position: -144px -96px; +} + +.icon-remove-circle { + background-position: -168px -96px; +} + +.icon-ok-circle { + background-position: -192px -96px; +} + +.icon-ban-circle { + background-position: -216px -96px; +} + +.icon-arrow-left { + background-position: -240px -96px; +} + +.icon-arrow-right { + background-position: -264px -96px; +} + +.icon-arrow-up { + background-position: -289px -96px; +} + +.icon-arrow-down { + background-position: -312px -96px; +} + +.icon-share-alt { + background-position: -336px -96px; +} + +.icon-resize-full { + background-position: -360px -96px; +} + +.icon-resize-small { + background-position: -384px -96px; +} + +.icon-plus { + background-position: -408px -96px; +} + +.icon-minus { + background-position: -433px -96px; +} + +.icon-asterisk { + background-position: -456px -96px; +} + +.icon-exclamation-sign { + background-position: 0 -120px; +} + +.icon-gift { + background-position: -24px -120px; +} + +.icon-leaf { + background-position: -48px -120px; +} + +.icon-fire { + background-position: -72px -120px; +} + +.icon-eye-open { + background-position: -96px -120px; +} + +.icon-eye-close { + background-position: -120px -120px; +} + +.icon-warning-sign { + background-position: -144px -120px; +} + +.icon-plane { + background-position: -168px -120px; +} + +.icon-calendar { + background-position: -192px -120px; +} + +.icon-random { + background-position: -216px -120px; +} + +.icon-comment { + background-position: -240px -120px; +} + +.icon-magnet { + background-position: -264px -120px; +} + +.icon-chevron-up { + background-position: -288px -120px; +} + +.icon-chevron-down { + background-position: -313px -119px; +} + +.icon-retweet { + background-position: -336px -120px; +} + +.icon-shopping-cart { + background-position: -360px -120px; +} + +.icon-folder-close { + background-position: -384px -120px; +} + +.icon-folder-open { + background-position: -408px -120px; +} + +.icon-resize-vertical { + background-position: -432px -119px; +} + +.icon-resize-horizontal { + background-position: -456px -118px; +} + +.icon-hdd { + background-position: 0 -144px; +} + +.icon-bullhorn { + background-position: -24px -144px; +} + +.icon-bell { + background-position: -48px -144px; +} + +.icon-certificate { + background-position: -72px -144px; +} + +.icon-thumbs-up { + background-position: -96px -144px; +} + +.icon-thumbs-down { + background-position: -120px -144px; +} + +.icon-hand-right { + background-position: -144px -144px; +} + +.icon-hand-left { + background-position: -168px -144px; +} + +.icon-hand-up { + background-position: -192px -144px; +} + +.icon-hand-down { + background-position: -216px -144px; +} + +.icon-circle-arrow-right { + background-position: -240px -144px; +} + +.icon-circle-arrow-left { + background-position: -264px -144px; +} + +.icon-circle-arrow-up { + background-position: -288px -144px; +} + +.icon-circle-arrow-down { + background-position: -312px -144px; +} + +.icon-globe { + background-position: -336px -144px; +} + +.icon-wrench { + background-position: -360px -144px; +} + +.icon-tasks { + background-position: -384px -144px; +} + +.icon-filter { + background-position: -408px -144px; +} + +.icon-briefcase { + background-position: -432px -144px; +} + +.icon-fullscreen { + background-position: -456px -144px; +} + +.dropup, +.dropdown { + position: relative; +} + +.dropdown-toggle { + *margin-bottom: -3px; +} + +.dropdown-toggle:active, +.open .dropdown-toggle { + outline: 0; +} + +.caret { + display: inline-block; + width: 0; + height: 0; + vertical-align: top; + border-top: 4px solid #000000; + border-right: 4px solid transparent; + border-left: 4px solid transparent; + content: ""; + opacity: 0.3; + filter: alpha(opacity=30); +} + +.dropdown .caret { + margin-top: 8px; + margin-left: 2px; +} + +.dropdown:hover .caret, +.open .caret { + opacity: 1; + filter: alpha(opacity=100); +} + +.dropdown-menu { + position: absolute; + top: 100%; + left: 0; + z-index: 1000; + display: none; + float: left; + min-width: 160px; + padding: 4px 0; + margin: 1px 0 0; + list-style: none; + background-color: #ffffff; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, 0.2); + *border-right-width: 2px; + *border-bottom-width: 2px; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; + -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + -webkit-background-clip: padding-box; + -moz-background-clip: padding; + background-clip: padding-box; +} + +.dropdown-menu.pull-right { + right: 0; + left: auto; +} + +.dropdown-menu .divider { + *width: 100%; + height: 1px; + margin: 8px 1px; + *margin: -5px 0 5px; + overflow: hidden; + background-color: #e5e5e5; + border-bottom: 1px solid #ffffff; +} + +.dropdown-menu a { + display: block; + padding: 3px 15px; + clear: both; + font-weight: normal; + line-height: 18px; + color: #333333; + white-space: nowrap; +} + +.dropdown-menu li > a:hover, +.dropdown-menu .active > a, +.dropdown-menu .active > a:hover { + color: #ffffff; + text-decoration: none; + background-color: #0088cc; +} + +.open { + *z-index: 1000; +} + +.open > .dropdown-menu { + display: block; +} + +.pull-right > .dropdown-menu { + right: 0; + left: auto; +} + +.dropup .caret, +.navbar-fixed-bottom .dropdown .caret { + border-top: 0; + border-bottom: 4px solid #000000; + content: "\2191"; +} + +.dropup .dropdown-menu, +.navbar-fixed-bottom .dropdown .dropdown-menu { + top: auto; + bottom: 100%; + margin-bottom: 1px; +} + +.typeahead { + margin-top: 2px; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} + +.well { + min-height: 20px; + padding: 19px; + margin-bottom: 20px; + background-color: #f5f5f5; + border: 1px solid #eee; + border: 1px solid rgba(0, 0, 0, 0.05); + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); +} + +.well blockquote { + border-color: #ddd; + border-color: rgba(0, 0, 0, 0.15); +} + +.well-large { + padding: 24px; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; +} + +.well-small { + padding: 9px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} + +.fade { + opacity: 0; + -webkit-transition: opacity 0.15s linear; + -moz-transition: opacity 0.15s linear; + -ms-transition: opacity 0.15s linear; + -o-transition: opacity 0.15s linear; + transition: opacity 0.15s linear; +} + +.fade.in { + opacity: 1; +} + +.collapse { + position: relative; + height: 0; + overflow: hidden; + -webkit-transition: height 0.35s ease; + -moz-transition: height 0.35s ease; + -ms-transition: height 0.35s ease; + -o-transition: height 0.35s ease; + transition: height 0.35s ease; +} + +.collapse.in { + height: auto; +} + +.close { + float: right; + font-size: 20px; + font-weight: bold; + line-height: 18px; + color: #000000; + text-shadow: 0 1px 0 #ffffff; + opacity: 0.2; + filter: alpha(opacity=20); +} + +.close:hover { + color: #000000; + text-decoration: none; + cursor: pointer; + opacity: 0.4; + filter: alpha(opacity=40); +} + +button.close { + padding: 0; + cursor: pointer; + background: transparent; + border: 0; + -webkit-appearance: none; +} + +.btn { + display: inline-block; + *display: inline; + padding: 4px 10px 4px; + margin-bottom: 0; + *margin-left: .3em; + font-size: 13px; + line-height: 18px; + *line-height: 20px; + color: #333333; + text-align: center; + text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); + vertical-align: middle; + cursor: pointer; + background-color: #f5f5f5; + *background-color: #e6e6e6; + background-image: -ms-linear-gradient(top, #ffffff, #e6e6e6); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6)); + background-image: -webkit-linear-gradient(top, #ffffff, #e6e6e6); + background-image: -o-linear-gradient(top, #ffffff, #e6e6e6); + background-image: linear-gradient(top, #ffffff, #e6e6e6); + background-image: -moz-linear-gradient(top, #ffffff, #e6e6e6); + background-repeat: repeat-x; + border: 1px solid #cccccc; + *border: 0; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + border-color: #e6e6e6 #e6e6e6 #bfbfbf; + border-bottom-color: #b3b3b3; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ffffff', endColorstr='#e6e6e6', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); + *zoom: 1; + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); +} + +.btn:hover, +.btn:active, +.btn.active, +.btn.disabled, +.btn[disabled] { + background-color: #e6e6e6; + *background-color: #d9d9d9; +} + +.btn:active, +.btn.active { + background-color: #cccccc \9; +} + +.btn:first-child { + *margin-left: 0; +} + +.btn:hover { + color: #333333; + text-decoration: none; + background-color: #e6e6e6; + *background-color: #d9d9d9; + /* Buttons in IE7 don't get borders, so darken on hover */ + + background-position: 0 -15px; + -webkit-transition: background-position 0.1s linear; + -moz-transition: background-position 0.1s linear; + -ms-transition: background-position 0.1s linear; + -o-transition: background-position 0.1s linear; + transition: background-position 0.1s linear; +} + +.btn:focus { + outline: thin dotted #333; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; +} + +.btn.active, +.btn:active { + background-color: #e6e6e6; + background-color: #d9d9d9 \9; + background-image: none; + outline: 0; + -webkit-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); +} + +.btn.disabled, +.btn[disabled] { + cursor: default; + background-color: #e6e6e6; + background-image: none; + opacity: 0.65; + filter: alpha(opacity=65); + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; +} + +.btn-large { + padding: 9px 14px; + font-size: 15px; + line-height: normal; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; +} + +.btn-large [class^="icon-"] { + margin-top: 1px; +} + +.btn-small { + padding: 5px 9px; + font-size: 11px; + line-height: 16px; +} + +.btn-small [class^="icon-"] { + margin-top: -1px; +} + +.btn-mini { + padding: 2px 6px; + font-size: 11px; + line-height: 14px; +} + +.btn-primary, +.btn-primary:hover, +.btn-warning, +.btn-warning:hover, +.btn-danger, +.btn-danger:hover, +.btn-success, +.btn-success:hover, +.btn-info, +.btn-info:hover, +.btn-inverse, +.btn-inverse:hover { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); +} + +.btn-primary.active, +.btn-warning.active, +.btn-danger.active, +.btn-success.active, +.btn-info.active, +.btn-inverse.active { + color: rgba(255, 255, 255, 0.75); +} + +.btn { + border-color: #ccc; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); +} + +.btn-primary { + background-color: #0074cc; + *background-color: #0055cc; + background-image: -ms-linear-gradient(top, #0088cc, #0055cc); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0055cc)); + background-image: -webkit-linear-gradient(top, #0088cc, #0055cc); + background-image: -o-linear-gradient(top, #0088cc, #0055cc); + background-image: -moz-linear-gradient(top, #0088cc, #0055cc); + background-image: linear-gradient(top, #0088cc, #0055cc); + background-repeat: repeat-x; + border-color: #0055cc #0055cc #003580; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#0088cc', endColorstr='#0055cc', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); +} + +.btn-primary:hover, +.btn-primary:active, +.btn-primary.active, +.btn-primary.disabled, +.btn-primary[disabled] { + background-color: #0055cc; + *background-color: #004ab3; +} + +.btn-primary:active, +.btn-primary.active { + background-color: #004099 \9; +} + +.btn-warning { + background-color: #faa732; + *background-color: #f89406; + background-image: -ms-linear-gradient(top, #fbb450, #f89406); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406)); + background-image: -webkit-linear-gradient(top, #fbb450, #f89406); + background-image: -o-linear-gradient(top, #fbb450, #f89406); + background-image: -moz-linear-gradient(top, #fbb450, #f89406); + background-image: linear-gradient(top, #fbb450, #f89406); + background-repeat: repeat-x; + border-color: #f89406 #f89406 #ad6704; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#fbb450', endColorstr='#f89406', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); +} + +.btn-warning:hover, +.btn-warning:active, +.btn-warning.active, +.btn-warning.disabled, +.btn-warning[disabled] { + background-color: #f89406; + *background-color: #df8505; +} + +.btn-warning:active, +.btn-warning.active { + background-color: #c67605 \9; +} + +.btn-danger { + background-color: #da4f49; + *background-color: #bd362f; + background-image: -ms-linear-gradient(top, #ee5f5b, #bd362f); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#bd362f)); + background-image: -webkit-linear-gradient(top, #ee5f5b, #bd362f); + background-image: -o-linear-gradient(top, #ee5f5b, #bd362f); + background-image: -moz-linear-gradient(top, #ee5f5b, #bd362f); + background-image: linear-gradient(top, #ee5f5b, #bd362f); + background-repeat: repeat-x; + border-color: #bd362f #bd362f #802420; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ee5f5b', endColorstr='#bd362f', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); +} + +.btn-danger:hover, +.btn-danger:active, +.btn-danger.active, +.btn-danger.disabled, +.btn-danger[disabled] { + background-color: #bd362f; + *background-color: #a9302a; +} + +.btn-danger:active, +.btn-danger.active { + background-color: #942a25 \9; +} + +.btn-success { + background-color: #5bb75b; + *background-color: #51a351; + background-image: -ms-linear-gradient(top, #62c462, #51a351); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#51a351)); + background-image: -webkit-linear-gradient(top, #62c462, #51a351); + background-image: -o-linear-gradient(top, #62c462, #51a351); + background-image: -moz-linear-gradient(top, #62c462, #51a351); + background-image: linear-gradient(top, #62c462, #51a351); + background-repeat: repeat-x; + border-color: #51a351 #51a351 #387038; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#62c462', endColorstr='#51a351', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); +} + +.btn-success:hover, +.btn-success:active, +.btn-success.active, +.btn-success.disabled, +.btn-success[disabled] { + background-color: #51a351; + *background-color: #499249; +} + +.btn-success:active, +.btn-success.active { + background-color: #408140 \9; +} + +.btn-info { + background-color: #49afcd; + *background-color: #2f96b4; + background-image: -ms-linear-gradient(top, #5bc0de, #2f96b4); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f96b4)); + background-image: -webkit-linear-gradient(top, #5bc0de, #2f96b4); + background-image: -o-linear-gradient(top, #5bc0de, #2f96b4); + background-image: -moz-linear-gradient(top, #5bc0de, #2f96b4); + background-image: linear-gradient(top, #5bc0de, #2f96b4); + background-repeat: repeat-x; + border-color: #2f96b4 #2f96b4 #1f6377; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#5bc0de', endColorstr='#2f96b4', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); +} + +.btn-info:hover, +.btn-info:active, +.btn-info.active, +.btn-info.disabled, +.btn-info[disabled] { + background-color: #2f96b4; + *background-color: #2a85a0; +} + +.btn-info:active, +.btn-info.active { + background-color: #24748c \9; +} + +.btn-inverse { + background-color: #414141; + *background-color: #222222; + background-image: -ms-linear-gradient(top, #555555, #222222); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#555555), to(#222222)); + background-image: -webkit-linear-gradient(top, #555555, #222222); + background-image: -o-linear-gradient(top, #555555, #222222); + background-image: -moz-linear-gradient(top, #555555, #222222); + background-image: linear-gradient(top, #555555, #222222); + background-repeat: repeat-x; + border-color: #222222 #222222 #000000; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#555555', endColorstr='#222222', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); +} + +.btn-inverse:hover, +.btn-inverse:active, +.btn-inverse.active, +.btn-inverse.disabled, +.btn-inverse[disabled] { + background-color: #222222; + *background-color: #151515; +} + +.btn-inverse:active, +.btn-inverse.active { + background-color: #080808 \9; +} + +button.btn, +input[type="submit"].btn { + *padding-top: 2px; + *padding-bottom: 2px; +} + +button.btn::-moz-focus-inner, +input[type="submit"].btn::-moz-focus-inner { + padding: 0; + border: 0; +} + +button.btn.btn-large, +input[type="submit"].btn.btn-large { + *padding-top: 7px; + *padding-bottom: 7px; +} + +button.btn.btn-small, +input[type="submit"].btn.btn-small { + *padding-top: 3px; + *padding-bottom: 3px; +} + +button.btn.btn-mini, +input[type="submit"].btn.btn-mini { + *padding-top: 1px; + *padding-bottom: 1px; +} + +.btn-group { + position: relative; + *margin-left: .3em; + *zoom: 1; +} + +.btn-group:before, +.btn-group:after { + display: table; + content: ""; +} + +.btn-group:after { + clear: both; +} + +.btn-group:first-child { + *margin-left: 0; +} + +.btn-group + .btn-group { + margin-left: 5px; +} + +.btn-toolbar { + margin-top: 9px; + margin-bottom: 9px; +} + +.btn-toolbar .btn-group { + display: inline-block; + *display: inline; + /* IE7 inline-block hack */ + + *zoom: 1; +} + +.btn-group > .btn { + position: relative; + float: left; + margin-left: -1px; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} + +.btn-group > .btn:first-child { + margin-left: 0; + -webkit-border-bottom-left-radius: 4px; + border-bottom-left-radius: 4px; + -webkit-border-top-left-radius: 4px; + border-top-left-radius: 4px; + -moz-border-radius-bottomleft: 4px; + -moz-border-radius-topleft: 4px; +} + +.btn-group > .btn:last-child, +.btn-group > .dropdown-toggle { + -webkit-border-top-right-radius: 4px; + border-top-right-radius: 4px; + -webkit-border-bottom-right-radius: 4px; + border-bottom-right-radius: 4px; + -moz-border-radius-topright: 4px; + -moz-border-radius-bottomright: 4px; +} + +.btn-group > .btn.large:first-child { + margin-left: 0; + -webkit-border-bottom-left-radius: 6px; + border-bottom-left-radius: 6px; + -webkit-border-top-left-radius: 6px; + border-top-left-radius: 6px; + -moz-border-radius-bottomleft: 6px; + -moz-border-radius-topleft: 6px; +} + +.btn-group > .btn.large:last-child, +.btn-group > .large.dropdown-toggle { + -webkit-border-top-right-radius: 6px; + border-top-right-radius: 6px; + -webkit-border-bottom-right-radius: 6px; + border-bottom-right-radius: 6px; + -moz-border-radius-topright: 6px; + -moz-border-radius-bottomright: 6px; +} + +.btn-group > .btn:hover, +.btn-group > .btn:focus, +.btn-group > .btn:active, +.btn-group > .btn.active { + z-index: 2; +} + +.btn-group .dropdown-toggle:active, +.btn-group.open .dropdown-toggle { + outline: 0; +} + +.btn-group > .dropdown-toggle { + *padding-top: 4px; + padding-right: 8px; + *padding-bottom: 4px; + padding-left: 8px; + -webkit-box-shadow: inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); +} + +.btn-group > .btn-mini.dropdown-toggle { + padding-right: 5px; + padding-left: 5px; +} + +.btn-group > .btn-small.dropdown-toggle { + *padding-top: 4px; + *padding-bottom: 4px; +} + +.btn-group > .btn-large.dropdown-toggle { + padding-right: 12px; + padding-left: 12px; +} + +.btn-group.open .dropdown-toggle { + background-image: none; + -webkit-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); +} + +.btn-group.open .btn.dropdown-toggle { + background-color: #e6e6e6; +} + +.btn-group.open .btn-primary.dropdown-toggle { + background-color: #0055cc; +} + +.btn-group.open .btn-warning.dropdown-toggle { + background-color: #f89406; +} + +.btn-group.open .btn-danger.dropdown-toggle { + background-color: #bd362f; +} + +.btn-group.open .btn-success.dropdown-toggle { + background-color: #51a351; +} + +.btn-group.open .btn-info.dropdown-toggle { + background-color: #2f96b4; +} + +.btn-group.open .btn-inverse.dropdown-toggle { + background-color: #222222; +} + +.btn .caret { + margin-top: 7px; + margin-left: 0; +} + +.btn:hover .caret, +.open.btn-group .caret { + opacity: 1; + filter: alpha(opacity=100); +} + +.btn-mini .caret { + margin-top: 5px; +} + +.btn-small .caret { + margin-top: 6px; +} + +.btn-large .caret { + margin-top: 6px; + border-top-width: 5px; + border-right-width: 5px; + border-left-width: 5px; +} + +.dropup .btn-large .caret { + border-top: 0; + border-bottom: 5px solid #000000; +} + +.btn-primary .caret, +.btn-warning .caret, +.btn-danger .caret, +.btn-info .caret, +.btn-success .caret, +.btn-inverse .caret { + border-top-color: #ffffff; + border-bottom-color: #ffffff; + opacity: 0.75; + filter: alpha(opacity=75); +} + +.alert { + padding: 8px 35px 8px 14px; + margin-bottom: 18px; + color: #c09853; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); + background-color: #fcf8e3; + border: 1px solid #fbeed5; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} + +.alert-heading { + color: inherit; +} + +.alert .close { + position: relative; + top: -2px; + right: -21px; + line-height: 18px; +} + +.alert-success { + color: #468847; + background-color: #dff0d8; + border-color: #d6e9c6; +} + +.alert-danger, +.alert-error { + color: #b94a48; + background-color: #f2dede; + border-color: #eed3d7; +} + +.alert-info { + color: #3a87ad; + background-color: #d9edf7; + border-color: #bce8f1; +} + +.alert-block { + padding-top: 14px; + padding-bottom: 14px; +} + +.alert-block > p, +.alert-block > ul { + margin-bottom: 0; +} + +.alert-block p + p { + margin-top: 5px; +} + +.nav { + margin-bottom: 18px; + margin-left: 0; + list-style: none; +} + +.nav > li > a { + display: block; +} + +.nav > li > a:hover { + text-decoration: none; + background-color: #eeeeee; +} + +.nav > .pull-right { + float: right; +} + +.nav .nav-header { + display: block; + padding: 3px 15px; + font-size: 11px; + font-weight: bold; + line-height: 18px; + color: #999999; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); + text-transform: uppercase; +} + +.nav li + .nav-header { + margin-top: 9px; +} + +.nav-list { + padding-right: 15px; + padding-left: 15px; + margin-bottom: 0; +} + +.nav-list > li > a, +.nav-list .nav-header { + margin-right: -15px; + margin-left: -15px; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); +} + +.nav-list > li > a { + padding: 3px 15px; +} + +.nav-list > .active > a, +.nav-list > .active > a:hover { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2); + background-color: #0088cc; +} + +.nav-list [class^="icon-"] { + margin-right: 2px; +} + +.nav-list .divider { + *width: 100%; + height: 1px; + margin: 8px 1px; + *margin: -5px 0 5px; + overflow: hidden; + background-color: #e5e5e5; + border-bottom: 1px solid #ffffff; +} + +.nav-tabs, +.nav-pills { + *zoom: 1; +} + +.nav-tabs:before, +.nav-pills:before, +.nav-tabs:after, +.nav-pills:after { + display: table; + content: ""; +} + +.nav-tabs:after, +.nav-pills:after { + clear: both; +} + +.nav-tabs > li, +.nav-pills > li { + float: left; +} + +.nav-tabs > li > a, +.nav-pills > li > a { + padding-right: 12px; + padding-left: 12px; + margin-right: 2px; + line-height: 14px; +} + +.nav-tabs { + border-bottom: 1px solid #ddd; +} + +.nav-tabs > li { + margin-bottom: -1px; +} + +.nav-tabs > li > a { + padding-top: 8px; + padding-bottom: 8px; + line-height: 18px; + border: 1px solid transparent; + -webkit-border-radius: 4px 4px 0 0; + -moz-border-radius: 4px 4px 0 0; + border-radius: 4px 4px 0 0; +} + +.nav-tabs > li > a:hover { + border-color: #eeeeee #eeeeee #dddddd; +} + +.nav-tabs > .active > a, +.nav-tabs > .active > a:hover { + color: #555555; + cursor: default; + background-color: #ffffff; + border: 1px solid #ddd; + border-bottom-color: transparent; +} + +.nav-pills > li > a { + padding-top: 8px; + padding-bottom: 8px; + margin-top: 2px; + margin-bottom: 2px; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; +} + +.nav-pills > .active > a, +.nav-pills > .active > a:hover { + color: #ffffff; + background-color: #0088cc; +} + +.nav-stacked > li { + float: none; +} + +.nav-stacked > li > a { + margin-right: 0; +} + +.nav-tabs.nav-stacked { + border-bottom: 0; +} + +.nav-tabs.nav-stacked > li > a { + border: 1px solid #ddd; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} + +.nav-tabs.nav-stacked > li:first-child > a { + -webkit-border-radius: 4px 4px 0 0; + -moz-border-radius: 4px 4px 0 0; + border-radius: 4px 4px 0 0; +} + +.nav-tabs.nav-stacked > li:last-child > a { + -webkit-border-radius: 0 0 4px 4px; + -moz-border-radius: 0 0 4px 4px; + border-radius: 0 0 4px 4px; +} + +.nav-tabs.nav-stacked > li > a:hover { + z-index: 2; + border-color: #ddd; +} + +.nav-pills.nav-stacked > li > a { + margin-bottom: 3px; +} + +.nav-pills.nav-stacked > li:last-child > a { + margin-bottom: 1px; +} + +.nav-tabs .dropdown-menu { + -webkit-border-radius: 0 0 5px 5px; + -moz-border-radius: 0 0 5px 5px; + border-radius: 0 0 5px 5px; +} + +.nav-pills .dropdown-menu { + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} + +.nav-tabs .dropdown-toggle .caret, +.nav-pills .dropdown-toggle .caret { + margin-top: 6px; + border-top-color: #0088cc; + border-bottom-color: #0088cc; +} + +.nav-tabs .dropdown-toggle:hover .caret, +.nav-pills .dropdown-toggle:hover .caret { + border-top-color: #005580; + border-bottom-color: #005580; +} + +.nav-tabs .active .dropdown-toggle .caret, +.nav-pills .active .dropdown-toggle .caret { + border-top-color: #333333; + border-bottom-color: #333333; +} + +.nav > .dropdown.active > a:hover { + color: #000000; + cursor: pointer; +} + +.nav-tabs .open .dropdown-toggle, +.nav-pills .open .dropdown-toggle, +.nav > li.dropdown.open.active > a:hover { + color: #ffffff; + background-color: #999999; + border-color: #999999; +} + +.nav li.dropdown.open .caret, +.nav li.dropdown.open.active .caret, +.nav li.dropdown.open a:hover .caret { + border-top-color: #ffffff; + border-bottom-color: #ffffff; + opacity: 1; + filter: alpha(opacity=100); +} + +.tabs-stacked .open > a:hover { + border-color: #999999; +} + +.tabbable { + *zoom: 1; +} + +.tabbable:before, +.tabbable:after { + display: table; + content: ""; +} + +.tabbable:after { + clear: both; +} + +.tab-content { + overflow: auto; +} + +.tabs-below > .nav-tabs, +.tabs-right > .nav-tabs, +.tabs-left > .nav-tabs { + border-bottom: 0; +} + +.tab-content > .tab-pane, +.pill-content > .pill-pane { + display: none; +} + +.tab-content > .active, +.pill-content > .active { + display: block; +} + +.tabs-below > .nav-tabs { + border-top: 1px solid #ddd; +} + +.tabs-below > .nav-tabs > li { + margin-top: -1px; + margin-bottom: 0; +} + +.tabs-below > .nav-tabs > li > a { + -webkit-border-radius: 0 0 4px 4px; + -moz-border-radius: 0 0 4px 4px; + border-radius: 0 0 4px 4px; +} + +.tabs-below > .nav-tabs > li > a:hover { + border-top-color: #ddd; + border-bottom-color: transparent; +} + +.tabs-below > .nav-tabs > .active > a, +.tabs-below > .nav-tabs > .active > a:hover { + border-color: transparent #ddd #ddd #ddd; +} + +.tabs-left > .nav-tabs > li, +.tabs-right > .nav-tabs > li { + float: none; +} + +.tabs-left > .nav-tabs > li > a, +.tabs-right > .nav-tabs > li > a { + min-width: 74px; + margin-right: 0; + margin-bottom: 3px; +} + +.tabs-left > .nav-tabs { + float: left; + margin-right: 19px; + border-right: 1px solid #ddd; +} + +.tabs-left > .nav-tabs > li > a { + margin-right: -1px; + -webkit-border-radius: 4px 0 0 4px; + -moz-border-radius: 4px 0 0 4px; + border-radius: 4px 0 0 4px; +} + +.tabs-left > .nav-tabs > li > a:hover { + border-color: #eeeeee #dddddd #eeeeee #eeeeee; +} + +.tabs-left > .nav-tabs .active > a, +.tabs-left > .nav-tabs .active > a:hover { + border-color: #ddd transparent #ddd #ddd; + *border-right-color: #ffffff; +} + +.tabs-right > .nav-tabs { + float: right; + margin-left: 19px; + border-left: 1px solid #ddd; +} + +.tabs-right > .nav-tabs > li > a { + margin-left: -1px; + -webkit-border-radius: 0 4px 4px 0; + -moz-border-radius: 0 4px 4px 0; + border-radius: 0 4px 4px 0; +} + +.tabs-right > .nav-tabs > li > a:hover { + border-color: #eeeeee #eeeeee #eeeeee #dddddd; +} + +.tabs-right > .nav-tabs .active > a, +.tabs-right > .nav-tabs .active > a:hover { + border-color: #ddd #ddd #ddd transparent; + *border-left-color: #ffffff; +} + +.navbar { + *position: relative; + *z-index: 2; + margin-bottom: 18px; + overflow: visible; +} + +.navbar-inner { + min-height: 40px; + padding-right: 20px; + padding-left: 20px; + background-color: #2c2c2c; + background-image: -moz-linear-gradient(top, #333333, #222222); + background-image: -ms-linear-gradient(top, #333333, #222222); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#333333), to(#222222)); + background-image: -webkit-linear-gradient(top, #333333, #222222); + background-image: -o-linear-gradient(top, #333333, #222222); + background-image: linear-gradient(top, #333333, #222222); + background-repeat: repeat-x; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#333333', endColorstr='#222222', GradientType=0); + -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.1); + -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.1); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.1); +} + +.navbar .container { + width: auto; +} + +.nav-collapse.collapse { + height: auto; +} + +.navbar { + color: #999999; +} + +.navbar .brand:hover { + text-decoration: none; +} + +.navbar .brand { + display: block; + float: left; + padding: 8px 20px 12px; + margin-left: -20px; + font-size: 20px; + font-weight: 200; + line-height: 1; + color: #999999; +} + +.navbar .navbar-text { + margin-bottom: 0; + line-height: 40px; +} + +.navbar .navbar-link { + color: #999999; +} + +.navbar .navbar-link:hover { + color: #ffffff; +} + +.navbar .btn, +.navbar .btn-group { + margin-top: 5px; +} + +.navbar .btn-group .btn { + margin: 0; +} + +.navbar-form { + margin-bottom: 0; + *zoom: 1; +} + +.navbar-form:before, +.navbar-form:after { + display: table; + content: ""; +} + +.navbar-form:after { + clear: both; +} + +.navbar-form input, +.navbar-form select, +.navbar-form .radio, +.navbar-form .checkbox { + margin-top: 5px; +} + +.navbar-form input, +.navbar-form select { + display: inline-block; + margin-bottom: 0; +} + +.navbar-form input[type="image"], +.navbar-form input[type="checkbox"], +.navbar-form input[type="radio"] { + margin-top: 3px; +} + +.navbar-form .input-append, +.navbar-form .input-prepend { + margin-top: 6px; + white-space: nowrap; +} + +.navbar-form .input-append input, +.navbar-form .input-prepend input { + margin-top: 0; +} + +.navbar-search { + position: relative; + float: left; + margin-top: 6px; + margin-bottom: 0; +} + +.navbar-search .search-query { + padding: 4px 9px; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 13px; + font-weight: normal; + line-height: 1; + color: #ffffff; + background-color: #626262; + border: 1px solid #151515; + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15); + -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15); + -webkit-transition: none; + -moz-transition: none; + -ms-transition: none; + -o-transition: none; + transition: none; +} + +.navbar-search .search-query:-moz-placeholder { + color: #cccccc; +} + +.navbar-search .search-query:-ms-input-placeholder { + color: #cccccc; +} + +.navbar-search .search-query::-webkit-input-placeholder { + color: #cccccc; +} + +.navbar-search .search-query:focus, +.navbar-search .search-query.focused { + padding: 5px 10px; + color: #333333; + text-shadow: 0 1px 0 #ffffff; + background-color: #ffffff; + border: 0; + outline: 0; + -webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); + -moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); + box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); +} + +.navbar-fixed-top, +.navbar-fixed-bottom { + position: fixed; + right: 0; + left: 0; + z-index: 1030; + margin-bottom: 0; +} + +.navbar-fixed-top .navbar-inner, +.navbar-fixed-bottom .navbar-inner { + padding-right: 0; + padding-left: 0; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} + +.navbar-fixed-top .container, +.navbar-fixed-bottom .container { + width: 940px; +} + +.navbar-fixed-top { + top: 0; +} + +.navbar-fixed-bottom { + bottom: 0; +} + +.navbar .nav { + position: relative; + left: 0; + display: block; + float: left; + margin: 0 10px 0 0; +} + +.navbar .nav.pull-right { + float: right; +} + +.navbar .nav > li { + display: block; + float: left; +} + +.navbar .nav > li > a { + float: none; + padding: 9px 10px 11px; + line-height: 19px; + color: #999999; + text-decoration: none; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); +} + +.navbar .btn { + display: inline-block; + padding: 4px 10px 4px; + margin: 5px 5px 6px; + line-height: 18px; +} + +.navbar .btn-group { + padding: 5px 5px 6px; + margin: 0; +} + +.navbar .nav > li > a:hover { + color: #ffffff; + text-decoration: none; + background-color: transparent; +} + +.navbar .nav .active > a, +.navbar .nav .active > a:hover { + color: #ffffff; + text-decoration: none; + background-color: #222222; +} + +.navbar .divider-vertical { + width: 1px; + height: 40px; + margin: 0 9px; + overflow: hidden; + background-color: #222222; + border-right: 1px solid #333333; +} + +.navbar .nav.pull-right { + margin-right: 0; + margin-left: 10px; +} + +.navbar .btn-navbar { + display: none; + float: right; + padding: 7px 10px; + margin-right: 5px; + margin-left: 5px; + background-color: #2c2c2c; + *background-color: #222222; + background-image: -ms-linear-gradient(top, #333333, #222222); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#333333), to(#222222)); + background-image: -webkit-linear-gradient(top, #333333, #222222); + background-image: -o-linear-gradient(top, #333333, #222222); + background-image: linear-gradient(top, #333333, #222222); + background-image: -moz-linear-gradient(top, #333333, #222222); + background-repeat: repeat-x; + border-color: #222222 #222222 #000000; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#333333', endColorstr='#222222', GradientType=0); + filter: progid:dximagetransform.microsoft.gradient(enabled=false); + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075); + -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075); +} + +.navbar .btn-navbar:hover, +.navbar .btn-navbar:active, +.navbar .btn-navbar.active, +.navbar .btn-navbar.disabled, +.navbar .btn-navbar[disabled] { + background-color: #222222; + *background-color: #151515; +} + +.navbar .btn-navbar:active, +.navbar .btn-navbar.active { + background-color: #080808 \9; +} + +.navbar .btn-navbar .icon-bar { + display: block; + width: 18px; + height: 2px; + background-color: #f5f5f5; + -webkit-border-radius: 1px; + -moz-border-radius: 1px; + border-radius: 1px; + -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); + -moz-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); + box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); +} + +.btn-navbar .icon-bar + .icon-bar { + margin-top: 3px; +} + +.navbar .dropdown-menu:before { + position: absolute; + top: -7px; + left: 9px; + display: inline-block; + border-right: 7px solid transparent; + border-bottom: 7px solid #ccc; + border-left: 7px solid transparent; + border-bottom-color: rgba(0, 0, 0, 0.2); + content: ''; +} + +.navbar .dropdown-menu:after { + position: absolute; + top: -6px; + left: 10px; + display: inline-block; + border-right: 6px solid transparent; + border-bottom: 6px solid #ffffff; + border-left: 6px solid transparent; + content: ''; +} + +.navbar-fixed-bottom .dropdown-menu:before { + top: auto; + bottom: -7px; + border-top: 7px solid #ccc; + border-bottom: 0; + border-top-color: rgba(0, 0, 0, 0.2); +} + +.navbar-fixed-bottom .dropdown-menu:after { + top: auto; + bottom: -6px; + border-top: 6px solid #ffffff; + border-bottom: 0; +} + +.navbar .nav li.dropdown .dropdown-toggle .caret, +.navbar .nav li.dropdown.open .caret { + border-top-color: #ffffff; + border-bottom-color: #ffffff; +} + +.navbar .nav li.dropdown.active .caret { + opacity: 1; + filter: alpha(opacity=100); +} + +.navbar .nav li.dropdown.open > .dropdown-toggle, +.navbar .nav li.dropdown.active > .dropdown-toggle, +.navbar .nav li.dropdown.open.active > .dropdown-toggle { + background-color: transparent; +} + +.navbar .nav li.dropdown.active > .dropdown-toggle:hover { + color: #ffffff; +} + +.navbar .pull-right .dropdown-menu, +.navbar .dropdown-menu.pull-right { + right: 0; + left: auto; +} + +.navbar .pull-right .dropdown-menu:before, +.navbar .dropdown-menu.pull-right:before { + right: 12px; + left: auto; +} + +.navbar .pull-right .dropdown-menu:after, +.navbar .dropdown-menu.pull-right:after { + right: 13px; + left: auto; +} + +.breadcrumb { + padding: 7px 14px; + margin: 0 0 18px; + list-style: none; + background-color: #fbfbfb; + background-image: -moz-linear-gradient(top, #ffffff, #f5f5f5); + background-image: -ms-linear-gradient(top, #ffffff, #f5f5f5); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f5f5f5)); + background-image: -webkit-linear-gradient(top, #ffffff, #f5f5f5); + background-image: -o-linear-gradient(top, #ffffff, #f5f5f5); + background-image: linear-gradient(top, #ffffff, #f5f5f5); + background-repeat: repeat-x; + border: 1px solid #ddd; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ffffff', endColorstr='#f5f5f5', GradientType=0); + -webkit-box-shadow: inset 0 1px 0 #ffffff; + -moz-box-shadow: inset 0 1px 0 #ffffff; + box-shadow: inset 0 1px 0 #ffffff; +} + +.breadcrumb li { + display: inline-block; + *display: inline; + text-shadow: 0 1px 0 #ffffff; + *zoom: 1; +} + +.breadcrumb .divider { + padding: 0 5px; + color: #999999; +} + +.breadcrumb .active a { + color: #333333; +} + +.pagination { + height: 36px; + margin: 18px 0; +} + +.pagination ul { + display: inline-block; + *display: inline; + margin-bottom: 0; + margin-left: 0; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; + *zoom: 1; + -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); +} + +.pagination li { + display: inline; +} + +.pagination a { + float: left; + padding: 0 14px; + line-height: 34px; + text-decoration: none; + border: 1px solid #ddd; + border-left-width: 0; +} + +.pagination a:hover, +.pagination .active a { + background-color: #f5f5f5; +} + +.pagination .active a { + color: #999999; + cursor: default; +} + +.pagination .disabled span, +.pagination .disabled a, +.pagination .disabled a:hover { + color: #999999; + cursor: default; + background-color: transparent; +} + +.pagination li:first-child a { + border-left-width: 1px; + -webkit-border-radius: 3px 0 0 3px; + -moz-border-radius: 3px 0 0 3px; + border-radius: 3px 0 0 3px; +} + +.pagination li:last-child a { + -webkit-border-radius: 0 3px 3px 0; + -moz-border-radius: 0 3px 3px 0; + border-radius: 0 3px 3px 0; +} + +.pagination-centered { + text-align: center; +} + +.pagination-right { + text-align: right; +} + +.pager { + margin-bottom: 18px; + margin-left: 0; + text-align: center; + list-style: none; + *zoom: 1; +} + +.pager:before, +.pager:after { + display: table; + content: ""; +} + +.pager:after { + clear: both; +} + +.pager li { + display: inline; +} + +.pager a { + display: inline-block; + padding: 5px 14px; + background-color: #fff; + border: 1px solid #ddd; + -webkit-border-radius: 15px; + -moz-border-radius: 15px; + border-radius: 15px; +} + +.pager a:hover { + text-decoration: none; + background-color: #f5f5f5; +} + +.pager .next a { + float: right; +} + +.pager .previous a { + float: left; +} + +.pager .disabled a, +.pager .disabled a:hover { + color: #999999; + cursor: default; + background-color: #fff; +} + +.modal-open .dropdown-menu { + z-index: 2050; +} + +.modal-open .dropdown.open { + *z-index: 2050; +} + +.modal-open .popover { + z-index: 2060; +} + +.modal-open .tooltip { + z-index: 2070; +} + +.modal-backdrop { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + z-index: 1040; + background-color: #000000; +} + +.modal-backdrop.fade { + opacity: 0; +} + +.modal-backdrop, +.modal-backdrop.fade.in { + opacity: 0.8; + filter: alpha(opacity=80); +} + +.modal { + position: fixed; + top: 50%; + left: 50%; + z-index: 1050; + width: 560px; + margin: -250px 0 0 -280px; + overflow: auto; + background-color: #ffffff; + border: 1px solid #999; + border: 1px solid rgba(0, 0, 0, 0.3); + *border: 1px solid #999; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; + -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + -webkit-background-clip: padding-box; + -moz-background-clip: padding-box; + background-clip: padding-box; +} + +.modal.fade { + top: -25%; + -webkit-transition: opacity 0.3s linear, top 0.3s ease-out; + -moz-transition: opacity 0.3s linear, top 0.3s ease-out; + -ms-transition: opacity 0.3s linear, top 0.3s ease-out; + -o-transition: opacity 0.3s linear, top 0.3s ease-out; + transition: opacity 0.3s linear, top 0.3s ease-out; +} + +.modal.fade.in { + top: 50%; +} + +.modal-header { + padding: 9px 15px; + border-bottom: 1px solid #eee; +} + +.modal-header .close { + margin-top: 2px; +} + +.modal-body { + max-height: 400px; + padding: 15px; + overflow-y: auto; +} + +.modal-form { + margin-bottom: 0; +} + +.modal-footer { + padding: 14px 15px 15px; + margin-bottom: 0; + text-align: right; + background-color: #f5f5f5; + border-top: 1px solid #ddd; + -webkit-border-radius: 0 0 6px 6px; + -moz-border-radius: 0 0 6px 6px; + border-radius: 0 0 6px 6px; + *zoom: 1; + -webkit-box-shadow: inset 0 1px 0 #ffffff; + -moz-box-shadow: inset 0 1px 0 #ffffff; + box-shadow: inset 0 1px 0 #ffffff; +} + +.modal-footer:before, +.modal-footer:after { + display: table; + content: ""; +} + +.modal-footer:after { + clear: both; +} + +.modal-footer .btn + .btn { + margin-bottom: 0; + margin-left: 5px; +} + +.modal-footer .btn-group .btn + .btn { + margin-left: -1px; +} + +.tooltip { + position: absolute; + z-index: 1020; + display: block; + padding: 5px; + font-size: 11px; + opacity: 0; + filter: alpha(opacity=0); + visibility: visible; +} + +.tooltip.in { + opacity: 0.8; + filter: alpha(opacity=80); +} + +.tooltip.top { + margin-top: -2px; +} + +.tooltip.right { + margin-left: 2px; +} + +.tooltip.bottom { + margin-top: 2px; +} + +.tooltip.left { + margin-left: -2px; +} + +.tooltip.top .tooltip-arrow { + bottom: 0; + left: 50%; + margin-left: -5px; + border-top: 5px solid #000000; + border-right: 5px solid transparent; + border-left: 5px solid transparent; +} + +.tooltip.left .tooltip-arrow { + top: 50%; + right: 0; + margin-top: -5px; + border-top: 5px solid transparent; + border-bottom: 5px solid transparent; + border-left: 5px solid #000000; +} + +.tooltip.bottom .tooltip-arrow { + top: 0; + left: 50%; + margin-left: -5px; + border-right: 5px solid transparent; + border-bottom: 5px solid #000000; + border-left: 5px solid transparent; +} + +.tooltip.right .tooltip-arrow { + top: 50%; + left: 0; + margin-top: -5px; + border-top: 5px solid transparent; + border-right: 5px solid #000000; + border-bottom: 5px solid transparent; +} + +.tooltip-inner { + max-width: 200px; + padding: 3px 8px; + color: #ffffff; + text-align: center; + text-decoration: none; + background-color: #000000; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} + +.tooltip-arrow { + position: absolute; + width: 0; + height: 0; +} + +.popover { + position: absolute; + top: 0; + left: 0; + z-index: 1010; + display: none; + padding: 5px; +} + +.popover.top { + margin-top: -5px; +} + +.popover.right { + margin-left: 5px; +} + +.popover.bottom { + margin-top: 5px; +} + +.popover.left { + margin-left: -5px; +} + +.popover.top .arrow { + bottom: 0; + left: 50%; + margin-left: -5px; + border-top: 5px solid #000000; + border-right: 5px solid transparent; + border-left: 5px solid transparent; +} + +.popover.right .arrow { + top: 50%; + left: 0; + margin-top: -5px; + border-top: 5px solid transparent; + border-right: 5px solid #000000; + border-bottom: 5px solid transparent; +} + +.popover.bottom .arrow { + top: 0; + left: 50%; + margin-left: -5px; + border-right: 5px solid transparent; + border-bottom: 5px solid #000000; + border-left: 5px solid transparent; +} + +.popover.left .arrow { + top: 50%; + right: 0; + margin-top: -5px; + border-top: 5px solid transparent; + border-bottom: 5px solid transparent; + border-left: 5px solid #000000; +} + +.popover .arrow { + position: absolute; + width: 0; + height: 0; +} + +.popover-inner { + width: 280px; + padding: 3px; + overflow: hidden; + background: #000000; + background: rgba(0, 0, 0, 0.8); + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; + -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); +} + +.popover-title { + padding: 9px 15px; + line-height: 1; + background-color: #f5f5f5; + border-bottom: 1px solid #eee; + -webkit-border-radius: 3px 3px 0 0; + -moz-border-radius: 3px 3px 0 0; + border-radius: 3px 3px 0 0; +} + +.popover-content { + padding: 14px; + background-color: #ffffff; + -webkit-border-radius: 0 0 3px 3px; + -moz-border-radius: 0 0 3px 3px; + border-radius: 0 0 3px 3px; + -webkit-background-clip: padding-box; + -moz-background-clip: padding-box; + background-clip: padding-box; +} + +.popover-content p, +.popover-content ul, +.popover-content ol { + margin-bottom: 0; +} + +.thumbnails { + margin-left: -20px; + list-style: none; + *zoom: 1; +} + +.thumbnails:before, +.thumbnails:after { + display: table; + content: ""; +} + +.thumbnails:after { + clear: both; +} + +.row-fluid .thumbnails { + margin-left: 0; +} + +.thumbnails > li { + float: left; + margin-bottom: 18px; + margin-left: 20px; +} + +.thumbnail { + display: block; + padding: 4px; + line-height: 1; + border: 1px solid #ddd; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075); +} + +a.thumbnail:hover { + border-color: #0088cc; + -webkit-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); + -moz-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); + box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); +} + +.thumbnail > img { + display: block; + max-width: 100%; + margin-right: auto; + margin-left: auto; +} + +.thumbnail .caption { + padding: 9px; +} + +.label, +.badge { + font-size: 10.998px; + font-weight: bold; + line-height: 14px; + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + white-space: nowrap; + vertical-align: baseline; + background-color: #999999; +} + +.label { + padding: 1px 4px 2px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} + +.badge { + padding: 1px 9px 2px; + -webkit-border-radius: 9px; + -moz-border-radius: 9px; + border-radius: 9px; +} + +a.label:hover, +a.badge:hover { + color: #ffffff; + text-decoration: none; + cursor: pointer; +} + +.label-important, +.badge-important { + background-color: #b94a48; +} + +.label-important[href], +.badge-important[href] { + background-color: #953b39; +} + +.label-warning, +.badge-warning { + background-color: #f89406; +} + +.label-warning[href], +.badge-warning[href] { + background-color: #c67605; +} + +.label-success, +.badge-success { + background-color: #468847; +} + +.label-success[href], +.badge-success[href] { + background-color: #356635; +} + +.label-info, +.badge-info { + background-color: #3a87ad; +} + +.label-info[href], +.badge-info[href] { + background-color: #2d6987; +} + +.label-inverse, +.badge-inverse { + background-color: #333333; +} + +.label-inverse[href], +.badge-inverse[href] { + background-color: #1a1a1a; +} + +@-webkit-keyframes progress-bar-stripes { + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } +} + +@-moz-keyframes progress-bar-stripes { + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } +} + +@-ms-keyframes progress-bar-stripes { + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } +} + +@-o-keyframes progress-bar-stripes { + from { + background-position: 0 0; + } + to { + background-position: 40px 0; + } +} + +@keyframes progress-bar-stripes { + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } +} + +.progress { + height: 18px; + margin-bottom: 18px; + overflow: hidden; + background-color: #f7f7f7; + background-image: -moz-linear-gradient(top, #f5f5f5, #f9f9f9); + background-image: -ms-linear-gradient(top, #f5f5f5, #f9f9f9); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f5f5f5), to(#f9f9f9)); + background-image: -webkit-linear-gradient(top, #f5f5f5, #f9f9f9); + background-image: -o-linear-gradient(top, #f5f5f5, #f9f9f9); + background-image: linear-gradient(top, #f5f5f5, #f9f9f9); + background-repeat: repeat-x; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#f5f5f5', endColorstr='#f9f9f9', GradientType=0); + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); +} + +.progress .bar { + width: 0; + height: 18px; + font-size: 12px; + color: #ffffff; + text-align: center; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #0e90d2; + background-image: -moz-linear-gradient(top, #149bdf, #0480be); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#149bdf), to(#0480be)); + background-image: -webkit-linear-gradient(top, #149bdf, #0480be); + background-image: -o-linear-gradient(top, #149bdf, #0480be); + background-image: linear-gradient(top, #149bdf, #0480be); + background-image: -ms-linear-gradient(top, #149bdf, #0480be); + background-repeat: repeat-x; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#149bdf', endColorstr='#0480be', GradientType=0); + -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); + -moz-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); + box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + -ms-box-sizing: border-box; + box-sizing: border-box; + -webkit-transition: width 0.6s ease; + -moz-transition: width 0.6s ease; + -ms-transition: width 0.6s ease; + -o-transition: width 0.6s ease; + transition: width 0.6s ease; +} + +.progress-striped .bar { + background-color: #149bdf; + background-image: -o-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -webkit-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -moz-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -ms-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + background-image: linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + -webkit-background-size: 40px 40px; + -moz-background-size: 40px 40px; + -o-background-size: 40px 40px; + background-size: 40px 40px; +} + +.progress.active .bar { + -webkit-animation: progress-bar-stripes 2s linear infinite; + -moz-animation: progress-bar-stripes 2s linear infinite; + -ms-animation: progress-bar-stripes 2s linear infinite; + -o-animation: progress-bar-stripes 2s linear infinite; + animation: progress-bar-stripes 2s linear infinite; +} + +.progress-danger .bar { + background-color: #dd514c; + background-image: -moz-linear-gradient(top, #ee5f5b, #c43c35); + background-image: -ms-linear-gradient(top, #ee5f5b, #c43c35); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#c43c35)); + background-image: -webkit-linear-gradient(top, #ee5f5b, #c43c35); + background-image: -o-linear-gradient(top, #ee5f5b, #c43c35); + background-image: linear-gradient(top, #ee5f5b, #c43c35); + background-repeat: repeat-x; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ee5f5b', endColorstr='#c43c35', GradientType=0); +} + +.progress-danger.progress-striped .bar { + background-color: #ee5f5b; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + background-image: -webkit-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -moz-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -ms-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); +} + +.progress-success .bar { + background-color: #5eb95e; + background-image: -moz-linear-gradient(top, #62c462, #57a957); + background-image: -ms-linear-gradient(top, #62c462, #57a957); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#57a957)); + background-image: -webkit-linear-gradient(top, #62c462, #57a957); + background-image: -o-linear-gradient(top, #62c462, #57a957); + background-image: linear-gradient(top, #62c462, #57a957); + background-repeat: repeat-x; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#62c462', endColorstr='#57a957', GradientType=0); +} + +.progress-success.progress-striped .bar { + background-color: #62c462; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + background-image: -webkit-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -moz-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -ms-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); +} + +.progress-info .bar { + background-color: #4bb1cf; + background-image: -moz-linear-gradient(top, #5bc0de, #339bb9); + background-image: -ms-linear-gradient(top, #5bc0de, #339bb9); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#339bb9)); + background-image: -webkit-linear-gradient(top, #5bc0de, #339bb9); + background-image: -o-linear-gradient(top, #5bc0de, #339bb9); + background-image: linear-gradient(top, #5bc0de, #339bb9); + background-repeat: repeat-x; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#5bc0de', endColorstr='#339bb9', GradientType=0); +} + +.progress-info.progress-striped .bar { + background-color: #5bc0de; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + background-image: -webkit-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -moz-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -ms-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); +} + +.progress-warning .bar { + background-color: #faa732; + background-image: -moz-linear-gradient(top, #fbb450, #f89406); + background-image: -ms-linear-gradient(top, #fbb450, #f89406); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406)); + background-image: -webkit-linear-gradient(top, #fbb450, #f89406); + background-image: -o-linear-gradient(top, #fbb450, #f89406); + background-image: linear-gradient(top, #fbb450, #f89406); + background-repeat: repeat-x; + filter: progid:dximagetransform.microsoft.gradient(startColorstr='#fbb450', endColorstr='#f89406', GradientType=0); +} + +.progress-warning.progress-striped .bar { + background-color: #fbb450; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + background-image: -webkit-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -moz-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -ms-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); +} + +.accordion { + margin-bottom: 18px; +} + +.accordion-group { + margin-bottom: 2px; + border: 1px solid #e5e5e5; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} + +.accordion-heading { + border-bottom: 0; +} + +.accordion-heading .accordion-toggle { + display: block; + padding: 8px 15px; +} + +.accordion-toggle { + cursor: pointer; +} + +.accordion-inner { + padding: 9px 15px; + border-top: 1px solid #e5e5e5; +} + +.carousel { + position: relative; + margin-bottom: 18px; + line-height: 1; +} + +.carousel-inner { + position: relative; + width: 100%; + overflow: hidden; +} + +.carousel .item { + position: relative; + display: none; + -webkit-transition: 0.6s ease-in-out left; + -moz-transition: 0.6s ease-in-out left; + -ms-transition: 0.6s ease-in-out left; + -o-transition: 0.6s ease-in-out left; + transition: 0.6s ease-in-out left; +} + +.carousel .item > img { + display: block; + line-height: 1; +} + +.carousel .active, +.carousel .next, +.carousel .prev { + display: block; +} + +.carousel .active { + left: 0; +} + +.carousel .next, +.carousel .prev { + position: absolute; + top: 0; + width: 100%; +} + +.carousel .next { + left: 100%; +} + +.carousel .prev { + left: -100%; +} + +.carousel .next.left, +.carousel .prev.right { + left: 0; +} + +.carousel .active.left { + left: -100%; +} + +.carousel .active.right { + left: 100%; +} + +.carousel-control { + position: absolute; + top: 40%; + left: 15px; + width: 40px; + height: 40px; + margin-top: -20px; + font-size: 60px; + font-weight: 100; + line-height: 30px; + color: #ffffff; + text-align: center; + background: #222222; + border: 3px solid #ffffff; + -webkit-border-radius: 23px; + -moz-border-radius: 23px; + border-radius: 23px; + opacity: 0.5; + filter: alpha(opacity=50); +} + +.carousel-control.right { + right: 15px; + left: auto; +} + +.carousel-control:hover { + color: #ffffff; + text-decoration: none; + opacity: 0.9; + filter: alpha(opacity=90); +} + +.carousel-caption { + position: absolute; + right: 0; + bottom: 0; + left: 0; + padding: 10px 15px 5px; + background: #333333; + background: rgba(0, 0, 0, 0.75); +} + +.carousel-caption h4, +.carousel-caption p { + color: #ffffff; +} + +.hero-unit { + padding: 60px; + margin-bottom: 30px; + background-color: #eeeeee; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; +} + +.hero-unit h1 { + margin-bottom: 0; + font-size: 60px; + line-height: 1; + letter-spacing: -1px; + color: inherit; +} + +.hero-unit p { + font-size: 18px; + font-weight: 200; + line-height: 27px; + color: inherit; +} + +.pull-right { + float: right; +} + +.pull-left { + float: left; +} + +.hide { + display: none; +} + +.show { + display: block; +} + +.invisible { + visibility: hidden; +} diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/lib/img/glyphicons-halflings-white.png b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/lib/img/glyphicons-halflings-white.png new file mode 100644 index 0000000000..3bf6484a29 Binary files /dev/null and b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/lib/img/glyphicons-halflings-white.png differ diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/lib/img/glyphicons-halflings.png b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/lib/img/glyphicons-halflings.png new file mode 100644 index 0000000000..79bc568c21 Binary files /dev/null and b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/lib/img/glyphicons-halflings.png differ diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/lib/img/grid-18px-masked.png b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/lib/img/grid-18px-masked.png new file mode 100644 index 0000000000..1bc82b03ab Binary files /dev/null and b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/lib/img/grid-18px-masked.png differ diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/login.jsp b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/login.jsp new file mode 100644 index 0000000000..0f70506567 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/login.jsp @@ -0,0 +1,98 @@ + +<%@page import="com.pizzashack.client.dto.Token"%> +<%@page import="com.pizzashack.client.web.TokenManager"%> +<% + boolean loginFailed = false; + String submitted = request.getParameter("submitted"); + if ("true".equals(submitted)) { + TokenManager manager = new TokenManager(); + String username = request.getParameter("username"); + String password = request.getParameter("password"); + Token token = manager.getToken(username, password); + if (token != null) { + session.setAttribute("access.token", token.getAccessToken()); + response.sendRedirect("index.jsp"); + } else { + loginFailed = true; + } + } +%> + + + + + + + + +
    +
    + +
    + +
    + +
    + +
    +
    +

    Login to Pizza Shack

    +
    +
    + <% + if (loginFailed) { + %> +
    Authentication failed for user
    + <% + } + %> + +
    +
    + +
    + + +
    + + +
    +
    + +
    + + +
    + + +
    +
    + +
    + +
    +
    +
    +
    +
    + +
    + + + + + diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/logout.jsp b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/logout.jsp new file mode 100644 index 0000000000..7730c7b8bf --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/logout.jsp @@ -0,0 +1,4 @@ +<% + session.removeAttribute("access.token"); + response.sendRedirect("login.jsp"); +%> diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/order-list.jsp b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/order-list.jsp new file mode 100644 index 0000000000..87b5eb036b --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/order-list.jsp @@ -0,0 +1,79 @@ + + + + + + + + + +
    + + + +
    + +
    +
    +
    +
    +

    My Orders

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    #First NameLast NameUsername
    1MarkOtto@mdo
    MarkOtto@TwBootstrap
    2JacobThornton@fat
    3Larry the Bird@twitter
    + +
    + +
    + +
    + + + + + diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/orders.jsp b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/orders.jsp new file mode 100644 index 0000000000..5ac180b480 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/orders.jsp @@ -0,0 +1,109 @@ + +<%@page import="com.pizzashack.client.dto.Order"%> +<%@page import="com.pizzashack.client.web.OrderManager"%> +<% + String token = (String) session.getAttribute("access.token"); + if (token == null) { + response.sendRedirect("login.jsp"); + return; + } +%> + + + + + + + + +
    + + + +
    + +
    +
    +
    +
    +

    My Orders

    +
    +
    + +
    +
    +
    + + +
    + + +

    Enter the order number provided during the order submission process.

    +
    +
    + +
    + + +
    +
    +
    + <% + String orderId = request.getParameter("orderId"); + if (orderId != null) { + OrderManager manager = new OrderManager(); + Order order = manager.getOrder(orderId, token); + if (order != null) { + %> + + + + + + + + + + + + + + + + + + + +
    Order Id<%=order.getOrderId()%>
    Pizza Type<%=order.getPizzaType()%>
    Quantity<%=order.getQuantity()%>
    Status<%=order.isDelivered() ? "Delivered" : "Pending"%>
    + <% + } else { + %> +

    Invalid order ID

    + <% + } + } + %> +
    +
    + +
    + + + + + diff --git a/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/place_order.jsp b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/place_order.jsp new file mode 100644 index 0000000000..9cb1ec5450 --- /dev/null +++ b/modules/samples/PizzaShack/pizza-shack-web/src/main/webapp/place_order.jsp @@ -0,0 +1,122 @@ + +<%@page import="com.pizzashack.client.dto.Order"%> +<%@page import="com.pizzashack.client.web.OrderManager"%> +<% + String token = (String) session.getAttribute("access.token"); + if (token == null) { + response.sendRedirect("login.jsp"); + return; + } + + String submitted = request.getParameter("submitted"); + if ("true".equals(submitted)) { + OrderManager manager = new OrderManager(); + String address = request.getParameter("bAddress"); + String pizzaType = request.getParameter("pizzaType"); + String quantity = request.getParameter("quantity"); + String customer = request.getParameter("userName"); + String card = request.getParameter("ccNumber"); + Order order = manager.saveOrder(address, pizzaType, quantity, customer, card, token); + response.sendRedirect("index.jsp?orderId=" + order.getOrderId()); + } +%> + + + + + + + + +
    + + + +
    + +
    + +
    +
    +

    Place your order

    +
    +
    +
    +
    + +
    + + +
    + " readonly="readonly"/> +
    +
    + +
    + + +
    + + +

    Enter the number of pizzas.

    +
    +
    + +
    + + +
    + + +
    +
    + +
    + + +
    + + +
    +
    + +
    + + +
    + +
    +
    + + +
    + + +
    +
    +
    +
    +
    + +
    + + + + + diff --git a/modules/samples/PizzaShack/pom.xml b/modules/samples/PizzaShack/pom.xml new file mode 100644 index 0000000000..b612fb2cb8 --- /dev/null +++ b/modules/samples/PizzaShack/pom.xml @@ -0,0 +1,45 @@ + + + + com.pizzashack + pizzashack + 1.0.0 + 4.0.0 + pom + PizzaShack Sample Application + + pre-processor + pizza-shack-api + pizza-shack-web + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.1 + + UTF-8 + 1.6 + 1.6 + + + + + diff --git a/modules/samples/PizzaShack/pre-processor/pom.xml b/modules/samples/PizzaShack/pre-processor/pom.xml new file mode 100644 index 0000000000..8601d42457 --- /dev/null +++ b/modules/samples/PizzaShack/pre-processor/pom.xml @@ -0,0 +1,51 @@ + + + + com.pizzashack + pizzashack + 1.0.0 + + com.pizzashack + pizzashack-preprocessor + 1.0.0 + 4.0.0 + pom + PizzaShack Sample Pre-processor + + + + + maven-antrun-plugin + 1.7 + + + validate + + + + + + + + run + + + + + + + + + + wso2-nexus + WSO2 internal Repository + http://maven.wso2.org/nexus/content/groups/wso2-public/ + + true + daily + fail + + + + diff --git a/modules/samples/TwitterSearch/APIPopulator.bat b/modules/samples/TwitterSearch/APIPopulator.bat new file mode 100644 index 0000000000..447af9ba60 --- /dev/null +++ b/modules/samples/TwitterSearch/APIPopulator.bat @@ -0,0 +1,4 @@ +set SERVER=http://localhost:9763 +curl -X POST -c cookies %SERVER%/publisher/site/blocks/user/login/ajax/login.jag -d "action=login&username=provider1&password=provider1" +curl -X POST -b cookies %SERVER%/publisher/site/blocks/item-add/ajax/add.jag -d "action=addAPI&name=TwitterSearch&version=1.0.0&description=Twitter Search&endpoint=http://search.twitter.com&wsdl=&tags=twitter,open,social&tier=Silver&thumbUrl=https://lh6.ggpht.com/RNc8dD2hXG_rWGzlj09ZwAe1sXVvLWkeYT3ePx7zePCy4ZVV2XMGIxAzup4cKM85NFtL=w124&context=/twitter&tiersCollection=Gold&resourceCount=0&resourceMethod-0=POST&resourceMethodAuthType-0=Application&uriTemplate-0=/*" +curl -X POST -b cookies %SERVER%/publisher/site/blocks/life-cycles/ajax/life-cycles.jag -d "name=TwitterSearch&version=1.0.0&provider=provider1&status=PUBLISHED&publishToGateway=true&action=updateStatus" diff --git a/modules/samples/TwitterSearch/APIPopulator.sh b/modules/samples/TwitterSearch/APIPopulator.sh new file mode 100644 index 0000000000..59a29dfd54 --- /dev/null +++ b/modules/samples/TwitterSearch/APIPopulator.sh @@ -0,0 +1,9 @@ +#!/bin/sh +START=$1 +COUNT=$2 +SERVER=http://localhost:9763 +curl -X POST -c cookies $SERVER/publisher/site/blocks/user/login/ajax/login.jag -d 'action=login&username=provider1&password=provider1'; + +curl -X POST -b cookies $SERVER/publisher/site/blocks/item-add/ajax/add.jag -d "action=addAPI&visibility=public&name=TwitterSearch&version=1.0.0&description=Twitter Search&endpoint=http://search.twitter.com&wsdl=&tags=twitter,open,social&tier=Silver&thumbUrl=https://lh6.ggpht.com/RNc8dD2hXG_rWGzlj09ZwAe1sXVvLWkeYT3ePx7zePCy4ZVV2XMGIxAzup4cKM85NFtL=w124&bizOwner=&bizOwnerMail=&techOwner=&techOwnerMail=&roles=&context=/twitter&tiersCollection=Gold&resourceCount=0&resourceMethod-0=POST&resourceMethodAuthType-0=Application&uriTemplate-0=/*"; + +curl -X POST -b cookies $SERVER/publisher/site/blocks/life-cycles/ajax/life-cycles.jag -d "name=TwitterSearch&version=1.0.0&provider=provider1&status=PUBLISHED&publishToGateway=true&action=updateStatus"; diff --git a/modules/samples/WikipediaAPI/APIPopulator.bat b/modules/samples/WikipediaAPI/APIPopulator.bat new file mode 100644 index 0000000000..c7a28638a1 --- /dev/null +++ b/modules/samples/WikipediaAPI/APIPopulator.bat @@ -0,0 +1,8 @@ +set SERVER=http://localhost:9763 +curl -X POST -c cookies %SERVER%/publisher/site/blocks/user/login/ajax/login.jag -d "action=login&username=provider1&password=provider1" + +curl -X POST -b cookies $SERVER/publisher/site/blocks/item-add/ajax/add.jag -d "action=addAPI&name=WikipediaAPI&visibility=public&version=1.0.0&description=If you want to monitor a MediaWiki installation, or create a bot to automatically maintain one, you can use the MediaWiki web service API. The web service API provides direct, high-level access to the data contained in MediaWiki databases&endpointType=nonsecured&http_checked=http&https_checked=https&wsdl=&tags=wikipedia,mediawiki&tier=Silver&thumbUrl=https://upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&context=/wikipedia&tiersCollection=Gold&resourceCount=0&resourceMethod-0=GET&resourceMethodAuthType-0=Application&resourceMethodThrottlingTier-0=Unlimited&uriTemplate-0=/*" -d 'endpoint_config={"production_endpoints":{"url":"http://en.wikipedia.org/w/api.php","config":null},"endpoint_type":"http"}'; + +curl -X POST -b cookies $SERVER/publisher/site/blocks/life-cycles/ajax/life-cycles.jag -d "name=WikipediaAPI&version=1.0.0&provider=provider1&status=PUBLISHED&publishToGateway=true&action=updateStatus"; + + diff --git a/modules/samples/WikipediaAPI/APIPopulator.sh b/modules/samples/WikipediaAPI/APIPopulator.sh new file mode 100644 index 0000000000..d66a892204 --- /dev/null +++ b/modules/samples/WikipediaAPI/APIPopulator.sh @@ -0,0 +1,11 @@ +#!/bin/sh +START=$1 +COUNT=$2 +SERVER=http://localhost:9763 +curl -X POST -c cookies $SERVER/publisher/site/blocks/user/login/ajax/login.jag -d 'action=login&username=provider1&password=provider1'; + +curl -X POST -b cookies $SERVER/publisher/site/blocks/item-add/ajax/add.jag -d "action=addAPI&name=WikipediaAPI&visibility=public&version=1.0.0&description=If you want to monitor a MediaWiki installation, or create a bot to automatically maintain one, you can use the MediaWiki web service API. The web service API provides direct, high-level access to the data contained in MediaWiki databases&endpointType=nonsecured&http_checked=http&https_checked=https&wsdl=&tags=wikipedia,mediawiki&tier=Silver&thumbUrl=https://upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&context=/wikipedia&tiersCollection=Gold&resourceCount=0&resourceMethod-0=GET&resourceMethodAuthType-0=Application&resourceMethodThrottlingTier-0=Unlimited&uriTemplate-0=/*" -d'endpoint_config={"production_endpoints":{"url":"http://en.wikipedia.org/w/api.php","config":null},"endpoint_type":"http"}'; + +curl -X POST -b cookies $SERVER/publisher/site/blocks/life-cycles/ajax/life-cycles.jag -d "name=WikipediaAPI&version=1.0.0&provider=provider1&status=PUBLISHED&publishToGateway=true&action=updateStatus"; + + diff --git a/modules/samples/YahooPlaceFinder/APIPopulator.bat b/modules/samples/YahooPlaceFinder/APIPopulator.bat new file mode 100644 index 0000000000..12a9a8d623 --- /dev/null +++ b/modules/samples/YahooPlaceFinder/APIPopulator.bat @@ -0,0 +1,8 @@ +set SERVER=http://localhost:9763 +curl -X POST -c cookies %SERVER%/publisher/site/blocks/user/login/ajax/login.jag -d "action=login&username=provider1&password=provider1" +curl -X POST -b cookies %SERVER%/publisher/site/blocks/item-add/ajax/add.jag -d "action=addAPI&name=PlaceFinder&version=1.0.0&description=Place Finder&endpoint=http://where.yahooapis.com/geocode&wsdl=&tags=finder,open,social&tier=Silver&thumbUrl=http://images.ientrymail.com/webpronews/article_pics/yahoo-placefinder.jpg&context=/placeFinder&tiersCollection=Gold&resourceCount=0&resourceMethod-0=GET&resourceMethodAuthType-0=Application&uriTemplate-0=/*" +curl -X POST -b cookies %SERVER%/publisher/site/blocks/life-cycles/ajax/life-cycles.jag -d "name=PlaceFinder&version=1.0.0&provider=provider1&status=PUBLISHED&publishToGateway=true&action=updateStatus" + + + + diff --git a/modules/samples/YahooPlaceFinder/APIPopulator.sh b/modules/samples/YahooPlaceFinder/APIPopulator.sh new file mode 100644 index 0000000000..b8b66179e4 --- /dev/null +++ b/modules/samples/YahooPlaceFinder/APIPopulator.sh @@ -0,0 +1,13 @@ +#!/bin/sh +START=$1 +COUNT=$2 +SERVER=http://localhost:9763 +curl -X POST -c cookies $SERVER/publisher/site/blocks/user/login/ajax/login.jag -d 'action=login&username=provider1&password=provider1'; + +curl -X POST -b cookies $SERVER/publisher/site/blocks/item-add/ajax/add.jag -d "action=addAPI&name=PlaceFinder&visibility=public&version=1.0.0&description=Place Finder&endpoint=http://where.yahooapis.com/geocode&wsdl=&tags=finder,open,social&tier=Silver&thumbUrl=http://images.ientrymail.com/webpronews/article_pics/yahoo-placefinder.jpg&context=/placeFinder&tiersCollection=Gold&resourceCount=0&resourceMethod-0=GET&resourceMethodAuthType-0=Application&uriTemplate-0=/*"; + +curl -X POST -b cookies $SERVER/publisher/site/blocks/life-cycles/ajax/life-cycles.jag -d "name=PlaceFinder&version=1.0.0&provider=provider1&status=PUBLISHED&publishToGateway=true&action=updateStatus"; + + + + diff --git a/modules/samples/YoutubeFeeds/APIPopulator.bat b/modules/samples/YoutubeFeeds/APIPopulator.bat new file mode 100644 index 0000000000..67cda701dc --- /dev/null +++ b/modules/samples/YoutubeFeeds/APIPopulator.bat @@ -0,0 +1,5 @@ +set SERVER=http://localhost:9763 +curl -X POST -c cookies %SERVER%/publisher/site/blocks/user/login/ajax/login.jag -d "action=login&username=provider1&password=provider1" +curl -X POST -b cookies %SERVER%/publisher/site/blocks/item-add/ajax/add.jag -d "action=addAPI&name=YoutubeFeeds&visibility=public&version=1.0.0&description=Youtube Live Feeds&endpointType=nonsecured&http_checked=http&https_checked=https&wsdl=&tags=youtube,gdata,multimedia&tier=Silver&thumbUrl=http://www.10bigideas.com.au/www/573/files/pf-thumbnail-youtube_logo.jpg&context=/youtube&tiersCollection=Gold&resourceCount=0&resourceMethod-0=GET&resourceMethodAuthType-0=Application&resourceMethodThrottlingTier-0=Unlimited&uriTemplate-0=/*" -d'endpoint_config={"production_endpoints":{"url":"http://gdata.youtube.com/feeds/api/standardfeeds","config":null},"endpoint_type":"http"}' + +curl -X POST -b cookies %SERVER%/publisher/site/blocks/life-cycles/ajax/life-cycles.jag -d "name=YoutubeFeeds&version=1.0.0&provider=provider1&status=PUBLISHED&publishToGateway=true&action=updateStatus" \ No newline at end of file diff --git a/modules/samples/YoutubeFeeds/APIPopulator.sh b/modules/samples/YoutubeFeeds/APIPopulator.sh new file mode 100644 index 0000000000..1d1bd0f279 --- /dev/null +++ b/modules/samples/YoutubeFeeds/APIPopulator.sh @@ -0,0 +1,12 @@ +#!/bin/sh +START=$1 +COUNT=$2 +SERVER=http://localhost:9763 +curl -X POST -c cookies $SERVER/publisher/site/blocks/user/login/ajax/login.jag -d 'action=login&username=provider1&password=provider1'; + +curl -X POST -b cookies $SERVER/publisher/site/blocks/item-add/ajax/add.jag -d "action=addAPI&name=YoutubeFeeds&visibility=public&version=1.0.0&description=Youtube Live Feeds&endpointType=nonsecured&http_checked=http&https_checked=https&&wsdl=&tags=youtube,gdata,multimedia&tier=Silver&thumbUrl=http://www.10bigideas.com.au/www/573/files/pf-thumbnail-youtube_logo.jpg&context=/youtube&tiersCollection=Gold&resourceCount=0&resourceMethod-0=GET&resourceMethodAuthType-0=Application&resourceMethodThrottlingTier-0=Unlimited&uriTemplate-0=/*" -d'endpoint_config={"production_endpoints":{"url":"http://gdata.youtube.com/feeds/api/standardfeeds","config":null},"endpoint_type":"http"}'; + + +curl -X POST -b cookies $SERVER/publisher/site/blocks/life-cycles/ajax/life-cycles.jag -d "name=YoutubeFeeds&version=1.0.0&provider=provider1&status=PUBLISHED&publishToGateway=true&action=updateStatus"; + + diff --git a/modules/styles/pom.xml b/modules/styles/pom.xml new file mode 100644 index 0000000000..7645def3df --- /dev/null +++ b/modules/styles/pom.xml @@ -0,0 +1,50 @@ + + + + + + + org.wso2.am + am-parent + 1.7.0-SNAPSHOT + ../../pom.xml + + + org.wso2.am + 4.0.0 + am-styles-parent + pom + WSO2 API Manager - Styles Parent + http://wso2.com/products/api-manager + WSO2 API Manager Styles Parent + + + + Apache License Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + + + + + product + service + + diff --git a/modules/styles/product/pom.xml b/modules/styles/product/pom.xml new file mode 100644 index 0000000000..6d144ec4ad --- /dev/null +++ b/modules/styles/product/pom.xml @@ -0,0 +1,111 @@ + + + + + + + + org.wso2.am + am-styles-parent + 1.7.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.am.styles + bundle + WSO2 API Manager - Styles + http://wso2.org + + + + + maven-eclipse-plugin + 2.6 + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.5 + 1.5 + + + + + org.apache.felix + maven-bundle-plugin + + true + + + ${project.artifactId} + ${project.artifactId} + org.wso2.am.styles.internal + + org.osgi.framework, + org.osgi.service.http, + org.wso2.carbon.ui, + javax.servlet.*;version="2.4.0", + *;resolution:=optional + + org.wso2.carbon.ui + UIBundle + + + + + + + + src/main/resources + + META-INF/product.xml + + true + + + src/main/resources + + META-INF/product.xml + + + + + + + + + org.apache.felix + org.apache.felix.framework + 1.0.3 + + + org.wso2.carbon + org.wso2.carbon.logging + 4.0.0 + + + + + + diff --git a/modules/styles/product/src/main/java/org/wso2/am/styles/internal/Activator.java b/modules/styles/product/src/main/java/org/wso2/am/styles/internal/Activator.java new file mode 100644 index 0000000000..8b74a2c270 --- /dev/null +++ b/modules/styles/product/src/main/java/org/wso2/am/styles/internal/Activator.java @@ -0,0 +1,41 @@ +/* + * Copyright 2004,2005 The Apache Software Foundation. + * + * 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 org.wso2.am.styles.internal; + + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + + + +/** + * Activator class for AM styles bundle + */ +public class Activator implements BundleActivator { + private static final Log log = LogFactory.getLog(Activator.class); + public void start(BundleContext bundleContext) throws Exception { + if (log.isDebugEnabled()) { + log.debug("Activating the bundle org.wso2.am.styles"); + } + + } + + public void stop(BundleContext context) throws Exception { + + } +} \ No newline at end of file diff --git a/modules/styles/product/src/main/resources/META-INF/component.xml b/modules/styles/product/src/main/resources/META-INF/component.xml new file mode 100644 index 0000000000..effd403589 --- /dev/null +++ b/modules/styles/product/src/main/resources/META-INF/component.xml @@ -0,0 +1,35 @@ + + + + + + default-context + publisher + http + API Publisher Default Context + + + default-additional-context + store + http + API Store Default Context + + + + diff --git a/modules/styles/product/src/main/resources/META-INF/product.xml b/modules/styles/product/src/main/resources/META-INF/product.xml new file mode 100644 index 0000000000..0f6dc1f83b --- /dev/null +++ b/modules/styles/product/src/main/resources/META-INF/product.xml @@ -0,0 +1,27 @@ + + + + http://wso2.org/forum/187 + http://docs.wso2.org/wiki/display/AM170/WSO2+API+Manager+Documentation + http://wso2.org/mail + https://wso2.org/jira/browse/APIMANAGER + region1_configure_menu,region3_registry_menu,region4_monitor_menu,region5_tools_menu + WSO2 API Manager + + diff --git a/modules/styles/product/src/main/resources/web/product/about.html b/modules/styles/product/src/main/resources/web/product/about.html new file mode 100644 index 0000000000..6c42180fc7 --- /dev/null +++ b/modules/styles/product/src/main/resources/web/product/about.html @@ -0,0 +1,148 @@ + + + +WSO2 API Manager - About + + + +

    Version 1.7.0

    + +

    About WSO2 API Manager

    + +

    + WSO2 API Manager is a powerful platform for creating, managing, consuming and + monitoring web APIs. It combines tried and tested SOA best practices with modern + day API management principles to solve a wide range of enterprise challenges + associated with API provisioning, governance and integration. +

    + +

    + WSO2 API Manager 1.7.0 is developed on top of the revolutionary + Carbon platform + (Middleware a' la carte), and is based on OSGi which provides + better modularity for your SOA architecture. +

    + +

    About WSO2 Carbon

    + +

    WSO2 Carbon is a component based Enterprise SOA platform. The + design of + WSO2 Carbon focuses on separating the key functionality of the SOA + platform + into separate pluggable Carbon components that can be mixed and + matched, like + customizable building blocks. This allows you to add only the + functionality + you need to start up, and continue to add product capabilities + as your + requirements grow. This helps a business to quickly adapt to + changes.

    + +

    OSGi is used as the underlying core modularization technology + to build the + Carbon platform. The Carbon framework is shipped with Eclipse Equinox + by + default, but can be supported on Spring dm Server, Felix or Knoplerfish + if + required. The OSGi technology even allows you to write your business + functionality as an OSGi component and deploy it in the existing Carbon + platform.

    + +

    For a quick start on using the WSO2 Carbon + platform, the Carbon components are pre-assembled into the following + products:

    + +

    You can assemble your own products by combining + components and + deploying them in a preferred architecture.

    + +

    The WSO2 Carbon platform gives maximum flexibility to adapt + the middleware + to your enterprise architecture, rather than adapt your architecture to + the + middleware.

    + +

    About WSO2

    + +

    WSO2 is an Open Source technology company building Open Source + middleware + platforms for Web services and SOA. WSO2 delivers integrated middleware + stacks based on components developed at Apache, offering industry + leading + performance and convenience for customers.

    + +

    Founded in August 2005 by pioneers in Web services and Open + Source, WSO2 + engineers contribute heavily to many key Apache Web services projects.

    + +

    Have you tried...

    + +

    Governance Registry

    + +

    BRS

    + +

    BPS

    + +

    IS

    + +

    DS

    + +

    BAM

    + +

    GS

    + +

    MS

    + +

    Stay connected

    + +

    Subscribe + to the WSO2 newsletter - project updates, events, articles, SOA news + and much + more.

    + + diff --git a/modules/styles/product/src/main/resources/web/styles/css/main.css b/modules/styles/product/src/main/resources/web/styles/css/main.css new file mode 100644 index 0000000000..bed0637eaf --- /dev/null +++ b/modules/styles/product/src/main/resources/web/styles/css/main.css @@ -0,0 +1,225 @@ +/* ---------------- template styles ------------------------- */ + +table#main-table td#header { + background-image: url( ../images/api-header-region-bg.png); + height:80px; +} + +table#main-table td#menu-panel { + border-right: solid 1px #91961f; + background-image: url(../images/api-server-menu-panel-bg.png); + background-position: right top; + background-repeat: repeat-y; +} + + +/* ---------------- header styles ------------------ */ +div#header-div { + background-image: url( ../images/api-header-back.png); + height:80px; +} + +div#header-div div.left-logo { + background-image: url( ../images/api-logo.png ); + margin-left: 30px; + margin-top: 25px; + + width:246px; + height:50px; +} + +div#header-div div.right-logo { + /*background-image:url("../images/right-logo-bg.gif"); + background-position:right top; + background-repeat:no-repeat;*/ + color:#cc362b; + height:32px; + margin-right:20px; + line-height: 30px; + margin-top:7px; + padding-right:0px; + padding-top:5px; +} +div#header-div div.header-links { + margin-top:-20px; +} +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:none; + padding-left: 25px; + padding-right: 15px; + padding-top: 0px; + padding-bottom: 7px; +} +#logged-user{ + color:#555; +} +/* ------------- 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 { +background-image:url(../../admin/images/menu_header.gif); +height:28px; +} + +div#menu ul.main li.menu-header { + background-image: url(../images/api-server-menu-header.gif); + background-position: left bottom; + background-repeat: repeat-x; + height: 32px; + line-height: 32px; +} + +div#menu ul.main li a.menu-default { +} + +div#menu ul.main li a.menu-default:hover { + background-color: #EFECF5; + border-bottom: solid 1px #C2B7D8; + border-top: solid 1px #C2B7D8; + color: #00447C; +} + +div#menu ul.sub { +} + +/* -------------- 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/powered-synapse.gif); + background-position: right top; +} + +/* ---- login styles ----- */ + + +/* --------------- table styles -------------------- */ + +.tableOddRow{background-color: white;} +.tableEvenRow{background-color: #EFECF5;} + +.button:hover{ + /*background-image:url(../images/esb-button-bg-hover.gif); + border:solid 1px #8268A8;*/ +} + +/* =============================================================================================================== */ + + + +.cornerExpand { + position: relative; + top: 3px; + left: -12px; + cursor: pointer; +} + +.cornerCollapse { + position: relative; + top: 3px; + left: -12px; + cursor: pointer; +} + +/* chanaka */ + +.form-table td{ + padding-bottom:5px !important; + padding-left:5px !important; + padding-top:5px !important; + padding-right:10px !important; +} +.form-table td div.indented{ + padding-left:7px !important; + color:#595959 !important; +} +.form-table-left{ +width:80px; +} +table#main-table td#header{ + height:80px; +} + +.longTextField{ +width:270px; +} +.rowAlone{ +padding-top:10px; +padding-bottom:10px; +} +.tabedBox{ +border:solid 1px #cccccc; +margin-left:10px; +padding:10px; +margin-bottom:10px; +} +/* chanaka end */ + +a.fact-selector-icon-link { + background-image: url( ../images/facts-selector.gif ); + background-repeat: no-repeat; + background-position: left top; + padding-left: 20px; + line-height: 17px; + height: 17px; + float: left; + position: relative; + margin-left: 10px; + margin-top: 5px; + margin-bottom: 3px; + white-space: nowrap; +} +table#main-table td#middle-content { +background-color:#f5f6fb; +} +div#middle{ +background-color:#f5f6fb; +} +div#middle h2{ +color:#8a2c3f; +} +div#menu ul.main li.menu-disabled-link{ + background-color:#eff1f9; +} \ No newline at end of file diff --git a/modules/styles/product/src/main/resources/web/styles/images/1px.gif b/modules/styles/product/src/main/resources/web/styles/images/1px.gif new file mode 100644 index 0000000000..f866f1db6b Binary files /dev/null and b/modules/styles/product/src/main/resources/web/styles/images/1px.gif differ diff --git a/modules/styles/product/src/main/resources/web/styles/images/api-header-back.png b/modules/styles/product/src/main/resources/web/styles/images/api-header-back.png new file mode 100644 index 0000000000..9ed3784c08 Binary files /dev/null and b/modules/styles/product/src/main/resources/web/styles/images/api-header-back.png differ diff --git a/modules/styles/product/src/main/resources/web/styles/images/api-header-region-bg.png b/modules/styles/product/src/main/resources/web/styles/images/api-header-region-bg.png new file mode 100644 index 0000000000..3ce3f9e4aa Binary files /dev/null and b/modules/styles/product/src/main/resources/web/styles/images/api-header-region-bg.png differ diff --git a/modules/styles/product/src/main/resources/web/styles/images/api-logo.png b/modules/styles/product/src/main/resources/web/styles/images/api-logo.png new file mode 100644 index 0000000000..53d05aec76 Binary files /dev/null and b/modules/styles/product/src/main/resources/web/styles/images/api-logo.png differ diff --git a/modules/styles/product/src/main/resources/web/styles/images/api-server-menu-header.gif b/modules/styles/product/src/main/resources/web/styles/images/api-server-menu-header.gif new file mode 100644 index 0000000000..1c78bbf5a5 Binary files /dev/null and b/modules/styles/product/src/main/resources/web/styles/images/api-server-menu-header.gif differ diff --git a/modules/styles/product/src/main/resources/web/styles/images/api-server-menu-panel-bg.png b/modules/styles/product/src/main/resources/web/styles/images/api-server-menu-panel-bg.png new file mode 100644 index 0000000000..436dca638b Binary files /dev/null and b/modules/styles/product/src/main/resources/web/styles/images/api-server-menu-panel-bg.png differ diff --git a/modules/styles/product/src/main/resources/web/styles/images/menu_header.gif b/modules/styles/product/src/main/resources/web/styles/images/menu_header.gif new file mode 100644 index 0000000000..3c8b5b1692 Binary files /dev/null and b/modules/styles/product/src/main/resources/web/styles/images/menu_header.gif differ diff --git a/modules/styles/product/src/main/resources/web/styles/images/right-links-bg.gif b/modules/styles/product/src/main/resources/web/styles/images/right-links-bg.gif new file mode 100644 index 0000000000..677a421bc0 Binary files /dev/null and b/modules/styles/product/src/main/resources/web/styles/images/right-links-bg.gif differ diff --git a/modules/styles/service/pom.xml b/modules/styles/service/pom.xml new file mode 100644 index 0000000000..50b6b16098 --- /dev/null +++ b/modules/styles/service/pom.xml @@ -0,0 +1,114 @@ + + + + + org.wso2.am + am-styles-parent + 1.7.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.stratos.apimgt.styles + ${stratos.version} + bundle + WSO2 Stratos API Manager - UI styles + http://wso2.org + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.5 + 1.5 + + + + + org.apache.felix + maven-bundle-plugin + + true + + + ${project.artifactId} + ${project.artifactId} + org.wso2.stratos.apimgt.styles.internal + + org.osgi.framework, + org.osgi.service.http, + org.wso2.carbon.ui, + javax.servlet.*;version="${imp.pkg.version.javax.servlet}", + *;resolution:=optional + + UIBundle + + + + + + + + + + org.wso2.carbon + org.wso2.carbon.ui + + + + org.apache.felix + org.apache.felix.framework + + + + org.apache.felix + org.apache.felix.main + + + + org.apache.felix + org.osgi.compendium + + + + org.eclipse.equinox + org.eclipse.equinox.http.servlet + + + + org.eclipse.equinox + org.eclipse.equinox.http.helper + + + + org.eclipse.equinox + org.eclipse.equinox.jsp.jasper + + + + org.eclipse.equinox + javax.servlet.jsp + ${javax.servlet.jsp.version} + + + diff --git a/modules/styles/service/src/main/resources/META-INF/product.xml b/modules/styles/service/src/main/resources/META-INF/product.xml new file mode 100644 index 0000000000..d4fd924fae --- /dev/null +++ b/modules/styles/service/src/main/resources/META-INF/product.xml @@ -0,0 +1,26 @@ + + + + http://wso2.org/forum/184 + http://docs.wso2.org/wiki/display/AM131/WSO2+API+Manager+Documentation + http://wso2.org/mail + https://wso2.org/jira/browse/APIMANAGER + WSO2 Stratos API Manager + + diff --git a/modules/styles/service/src/main/resources/web/favicon.ico b/modules/styles/service/src/main/resources/web/favicon.ico new file mode 100644 index 0000000000..f7b2bbfb1a Binary files /dev/null and b/modules/styles/service/src/main/resources/web/favicon.ico differ diff --git a/modules/styles/service/src/main/resources/web/styles/css/main.css b/modules/styles/service/src/main/resources/web/styles/css/main.css new file mode 100644 index 0000000000..61bd3f4210 --- /dev/null +++ b/modules/styles/service/src/main/resources/web/styles/css/main.css @@ -0,0 +1,225 @@ +/* ---------------- template styles ------------------------- */ + +table#main-table td#header { + background-image: url( ../images/api-header-region-bg.png); + height:80px; +} + +table#main-table td#menu-panel { + border-right: solid 1px #91961f; + background-image: url(../images/api-server-menu-panel-bg.png); + background-position: right top; + background-repeat: repeat-y; +} + + +/* ---------------- header styles ------------------ */ +div#header-div { + background-image: url( ../images/api-header-back.png); + height:80px; +} + +div#header-div div.left-logo { + background-image: url( ../images/api-logo.png ); + margin-left: 30px; + margin-top: 25px; + + width:246px; + height:50px; +} + +div#header-div div.right-logo { + /*background-image:url("../images/right-logo-bg.gif"); + background-position:right top; + background-repeat:no-repeat;*/ + color:#cc362b; + height:32px; + margin-right:20px; + line-height: 30px; + margin-top:7px; + padding-right:0px; + padding-top:5px; +} +div#header-div div.header-links { + margin-top:-20px; +} +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:none; + padding-left: 25px; + padding-right: 15px; + padding-top: 0px; + padding-bottom: 7px; +} +#logged-user{ + color:#555; +} +/* ------------- 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 { +background-image:url(../images/menu_header.gif); +height:28px; +} + +div#menu ul.main li.menu-header { + background-image: url(../images/api-server-menu-header.gif); + background-position: left bottom; + background-repeat: repeat-x; + height: 32px; + line-height: 32px; +} + +div#menu ul.main li a.menu-default { +} + +div#menu ul.main li a.menu-default:hover { + background-color: #EFECF5; + border-bottom: solid 1px #C2B7D8; + border-top: solid 1px #C2B7D8; + color: #00447C; +} + +div#menu ul.sub { +} + +/* -------------- 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/powered-synapse.gif); + background-position: right top; +} + +/* ---- login styles ----- */ + + +/* --------------- table styles -------------------- */ + +.tableOddRow{background-color: white;} +.tableEvenRow{background-color: #EFECF5;} + +.button:hover{ + /*background-image:url(../images/esb-button-bg-hover.gif); + border:solid 1px #8268A8;*/ +} + +/* =============================================================================================================== */ + + + +.cornerExpand { + position: relative; + top: 3px; + left: -12px; + cursor: pointer; +} + +.cornerCollapse { + position: relative; + top: 3px; + left: -12px; + cursor: pointer; +} + +/* chanaka */ + +.form-table td{ + padding-bottom:5px !important; + padding-left:5px !important; + padding-top:5px !important; + padding-right:10px !important; +} +.form-table td div.indented{ + padding-left:7px !important; + color:#595959 !important; +} +.form-table-left{ +width:80px; +} +table#main-table td#header{ + height:80px; +} + +.longTextField{ +width:270px; +} +.rowAlone{ +padding-top:10px; +padding-bottom:10px; +} +.tabedBox{ +border:solid 1px #cccccc; +margin-left:10px; +padding:10px; +margin-bottom:10px; +} +/* chanaka end */ + +a.fact-selector-icon-link { + background-image: url( ../images/facts-selector.gif ); + background-repeat: no-repeat; + background-position: left top; + padding-left: 20px; + line-height: 17px; + height: 17px; + float: left; + position: relative; + margin-left: 10px; + margin-top: 5px; + margin-bottom: 3px; + white-space: nowrap; +} +table#main-table td#middle-content { +background-color:#f5f6fb; +} +div#middle{ +background-color:#f5f6fb; +} +div#middle h2{ +color:#8a2c3f; +} +div#menu ul.main li.menu-disabled-link{ + background-color:#eff1f9; +} diff --git a/modules/styles/service/src/main/resources/web/styles/images/api-header-back.png b/modules/styles/service/src/main/resources/web/styles/images/api-header-back.png new file mode 100644 index 0000000000..9ed3784c08 Binary files /dev/null and b/modules/styles/service/src/main/resources/web/styles/images/api-header-back.png differ diff --git a/modules/styles/service/src/main/resources/web/styles/images/api-header-region-bg.png b/modules/styles/service/src/main/resources/web/styles/images/api-header-region-bg.png new file mode 100644 index 0000000000..3ce3f9e4aa Binary files /dev/null and b/modules/styles/service/src/main/resources/web/styles/images/api-header-region-bg.png differ diff --git a/modules/styles/service/src/main/resources/web/styles/images/api-logo.png b/modules/styles/service/src/main/resources/web/styles/images/api-logo.png new file mode 100644 index 0000000000..53d05aec76 Binary files /dev/null and b/modules/styles/service/src/main/resources/web/styles/images/api-logo.png differ diff --git a/modules/styles/service/src/main/resources/web/styles/images/api-server-menu-header.gif b/modules/styles/service/src/main/resources/web/styles/images/api-server-menu-header.gif new file mode 100644 index 0000000000..1c78bbf5a5 Binary files /dev/null and b/modules/styles/service/src/main/resources/web/styles/images/api-server-menu-header.gif differ diff --git a/modules/styles/service/src/main/resources/web/styles/images/api-server-menu-panel-bg.png b/modules/styles/service/src/main/resources/web/styles/images/api-server-menu-panel-bg.png new file mode 100644 index 0000000000..436dca638b Binary files /dev/null and b/modules/styles/service/src/main/resources/web/styles/images/api-server-menu-panel-bg.png differ diff --git a/modules/styles/service/src/main/resources/web/styles/images/menu_header.gif b/modules/styles/service/src/main/resources/web/styles/images/menu_header.gif new file mode 100644 index 0000000000..3c8b5b1692 Binary files /dev/null and b/modules/styles/service/src/main/resources/web/styles/images/menu_header.gif differ diff --git a/modules/styles/service/src/main/resources/web/styles/images/right-links-bg.gif b/modules/styles/service/src/main/resources/web/styles/images/right-links-bg.gif new file mode 100644 index 0000000000..677a421bc0 Binary files /dev/null and b/modules/styles/service/src/main/resources/web/styles/images/right-links-bg.gif differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000000..28cafb1294 --- /dev/null +++ b/pom.xml @@ -0,0 +1,520 @@ + + + + + + 4.0.0 + org.wso2.am + am-parent + pom + 1.7.0-SNAPSHOT + WSO2 API Manager - Aggregator Module + http://wso2.com/products/api-manager + WSO2 API Manager + + + + Apache License Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + + + + + + + + + + + + + modules/integration + + + + scm:svn:http://wso2.org/repos/wso2/trunk/carbon/products/esb + scm:svn:https://wso2.org/repos/wso2/trunk/carbon/products/esb + + https://wso2.org/repos/wso2/trunk/carbon/products/esb + + + + + wso2-nexus + WSO2 internal Repository + http://maven.wso2.org/nexus/content/groups/wso2-public/ + + true + daily + ignore + + + + + wso2.releases + WSO2 internal Repository + http://maven.wso2.org/nexus/content/repositories/releases/ + + true + daily + ignore + + + + + wso2.snapshots + WSO2 Snapshot Repository + http://maven.wso2.org/nexus/content/repositories/snapshots/ + + true + daily + + + false + + + + + + + wso2.releases + WSO2 internal Repository + http://maven.wso2.org/nexus/content/repositories/releases/ + + true + daily + ignore + + + + + wso2.snapshots + Apache Snapshot Repository + http://maven.wso2.org/nexus/content/repositories/snapshots/ + + true + daily + + + false + + + + wso2-nexus + WSO2 internal Repository + http://maven.wso2.org/nexus/content/groups/wso2-public/ + + true + daily + ignore + + + + + + + + wso2.releases + WSO2 internal Repository + http://maven.wso2.org/nexus/content/repositories/releases/ + + + wso2.snapshots + WSO2 Snapshot Repository + http://maven.wso2.org/nexus/content/repositories/snapshots/ + + + + + + jdk14 + + 1.4 + + + + bouncycastle + bcprov-jdk13 + ${bcprov.jdk13.version} + + + + + + jdk15 + + true + 1.5 + + + + bouncycastle + bcprov-jdk15 + ${bcprov.jdk15.version} + + + + + + signed-build + + + sign + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.0-alpha-3 + + + sign-artifacts + verify + + sign + + + + + + + + + + + WSO2 Inc + http://wso2.com + + + + JIRA + http://wso2.org/jira/browse/ESBJAVA + + + + + WSO2 ESB Users' list + mailto:esb-java-user@wso2.org + http://wso2.org/mailarchive/esb-java-user/ + mailto:esb-java-user-request@wso2.org?subject=subscribe + mailto:esb-java-user-request@wso2.org?subject=unsubscribe + + + WSO2 ESB/Carbon Developers' List + mailto:carbon-dev@wso2.org + http://wso2.org/mailarchive/carbon-dev/ + mailto:carbon-dev-request@wso2.org?subject=subscribe + mailto:carbon-dev-request@wso2.org?subject=unsubscribe + + + + + + + org.wso2.carbon + org.wso2.carbon.ui + ${carbon.kernel.version} + + + org.eclipse.osgi + org.eclipse.osgi + ${version.equinox.osgi} + + + org.eclipse.equinox + org.eclipse.equinox.jsp.jasper + ${version.equinox.jsp.jasper} + + + org.eclipse.equinox + org.eclipse.equinox.http.helper + ${version.equinox.http.helper} + + + org.eclipse.osgi + org.eclipse.osgi.services + ${version.equinox.osgi.services} + + + org.eclipse.equinox + javax.servlet + ${javax.servlet.version} + + + org.apache.derby.wso2 + derby + ${apache.derby.version} + + + org.hibernate.wso2 + hibernate + 3.2.5.ga-wso2v1 + + + org.apache.bcel.wso2 + bcel + ${bcel.version} + + + asm.wso2 + asm + ${asm.version} + + + cglib.wso2 + cglib + ${cglib.version} + + + org.apache.axis2.wso2 + axis2-jibx + ${axis2.jibx.version} + + + org.jibx.wso2 + jibx + ${jibx.version} + + + org.apache.axis2.wso2 + axis2-jaxbri + ${axis2.jaxb.version} + + + + org.apache.axis2.wso2 + axis2 + ${axis2.wso2.version} + + + log4j + log4j + ${log4j.version} + + + commons-logging + commons-logging + ${commons.logging.version} + + + + javax.servlet + servlet-api + ${servlet-api.version} + + + org.apache.ws.commons.axiom.wso2 + axiom + ${axiom.wso2.version} + + + + org.apache.felix + org.apache.felix.framework + 1.0.3 + + + org.apache.felix + org.apache.felix.main + 1.0.3 + + + org.apache.felix + org.osgi.compendium + 1.0.0 + + + org.eclipse.equinox + org.eclipse.equinox.http.servlet + ${version.equinox.http.servlet} + + + org.eclipse.equinox + javax.servlet.jsp + ${javax.servlet.jsp.version} + + + + + org.wso2.carbon.automation + org.wso2.carbon.automation.engine + ${automation.framework.verion} + test + + + org.wso2.carbon.automation + org.wso2.carbon.automation.extensions + ${automation.framework.verion} + + + org.apache.jmeter + ApacheJMeter + + + org.apache.jmeter + ApacheJMeter_core + + + test + + + org.wso2.carbon.automation + org.wso2.carbon.automation.test.utils + ${automation.framework.verion} + + + + org.wso2.carbon + org.wso2.carbon.integration.common.admin.client + ${automation.framework.utills.version} + test + + + org.wso2.carbon + org.wso2.carbon.integration.common.extensions + ${automation.framework.utills.version} + test + + + org.wso2.carbon + org.wso2.carbon.integration.common.utils + ${automation.framework.utills.version} + test + + + org.wso2.carbon + org.wso2.carbon.integration.common.tests + ${automation.framework.utills.version} + test + + + + org.wso2.carbon + org.wso2.carbon.endpoint.stub + ${carbon.platform.version} + test + + + org.wso2.carbon + org.wso2.carbon.localentry.stub + ${carbon.platform.version} + test + + + org.wso2.carbon + org.wso2.carbon.proxyadmin.stub + ${carbon.platform.version} + test + + + org.wso2.carbon + org.wso2.carbon.sequences.stub + ${carbon.platform.version} + test + + + org.wso2.carbon + org.wso2.carbon.task.stub + ${carbon.platform.version} + test + + + org.wso2.carbon + org.wso2.carbon.security.mgt.stub + ${carbon.platform.version} + test + + + org.wso2.carbon + org.wso2.carbon.aarservices.stub + ${carbon.platform.version} + test + + + org.wso2.carbon + org.wso2.carbon.rest.api.stub + ${carbon.platform.version} + test + + + org.wso2.carbon + org.wso2.carbon.logging.admin.stub + ${carbon.platform.version} + test + + + + + + + + 4.3.0-SNAPSHOT + 4.3.0-SNAPSHOT + 1.7.0-SNAPSHOT + 4.3.0-SNAPSHOT + UTF-8 + 1.2.13 + 1.1 + 1.8 + 3.0-FINAL + 4.3.0-SNAPSHOT + 2.1.3-wso2v1-SNAPSHOT + 1.1.0-wso2v6 + 1.0.0 + 1.0.2 + 1.6.1.wso2v11-SNAPSHOT + 1.2.11.wso2v5 + 2.4 + 1.2.13 + 1.1 + 3.0.0.v201112011016 + 2.2.0.v201112011158 + 10.3.2.1wso2v1 + 3.2.5.ga-wso2v1 + 5.2.0.wso2v1 + 1.5.3.wso2v1 + 2.2.wso2v1 + 1.6.1.wso2v11-SNAPSHOT + ${orbit.version.axis2} + 1.2.1.wso2v1 + ${orbit.version.axis2} + 2.2.5.wso2v1 + 2.2.0 + 140 + 132 + 1.1.300.v20120522-1841 + 1.0.400.v20120522-2049 + 1.1.0.wso2v1 + 1.5.3 + 2.1.5320 + 1.2.140.wso2v3 + 1.3.4.wso2v1 + 3.3.100.v20120522-1822 + 3.8.1.v20120830-144521 + + 4.3.1 + 4.3.0-SNAPSHOT + + + diff --git a/release-notes.html b/release-notes.html new file mode 100644 index 0000000000..74a7071f95 --- /dev/null +++ b/release-notes.html @@ -0,0 +1,942 @@ + + + + + + + + WSO2 API Manager v1.7.0 - 23rd May 2014 + + +
    +

    The WSO2 API Manager 1.7.0 Released!

    + +

    + The WSO2 API Manager team is pleased to announce the release of version 1.7.0 of + the Open Source API Manager. +

    + +

    + WSO2 API Manager is a platform for creating, managing, consuming and monitoring + APIs. It employs proven SOA best practices to solve a wide range of API + management challenges such as API provisioning, API governance, API security + and API monitoring. It combines some of the most powerful and mature components + of the WSO2's state-of-the-art Carbon platform to deliver a smooth and end-to-end + API management experience while catering to both API publisher and API consumer + requirements. +

    + +

    + WSO2 API Manager is comprised of several modules. +

    +
      +
    • API Provider: Define new APIs and manage them
    • +
    • API Store: Browse published APIs and subscribe to them
    • +
    • API Gateway: The underlying API runtime based on WSO2 ESB
    • +
    • API Key Manager: Performs Key Generation and Key Validation functionalities
    • +
    + +

    + WSO2 API Manager is developed on top of the revolutionary + WSO2 Carbon platform + (Middleware a' la carte), + an OSGi based framework that provides seamless modularity to your SOA via + componentization. This release also contains many new features and a range of + optional components (add-ons) that can be installed to customize the behavior + of the API Manager. Further, any existing features of the product which are not + required in your environment can be easily removed using the underlying + provisioning framework of Carbon. In brief, WSO2 API Manager can be fully + customized and tailored to meet your exact API management needs. +

    + +

    + For more information on WSO2 API Manager please visit + http://wso2.com/products/api-manager. Also take a look at the online product + documentation. +

    + +

    How to Run

    +
      +
    1. Extract the downloaded zip
    2. +
    3. Go to the bin directory in the extracted folder
    4. +
    5. Run the wso2server.sh or wso2server.bat as appropriate
    6. +
    7. Launch a web browser and navigate to https://localhost:9443/publisher + to access the API provider webapp +
    8. +
    9. Navigate to https://localhost:9443/store to access the API store
    10. +
    11. Navigate to https://localhost:9443/admin-dashboard to access Admin dashboard
    12. +
    13. Use "admin", "admin" as the username and password to login as an admin
    14. +
    + +

    New Features in WSO2 API Manager 1.7.0

    +
  • API Design Wizard
  • +
  • Support for OAuth2 Scopes
  • +
  • Statistics Dashboard for developers
  • +
  • Workflow integration for token generation
  • +
  • URL templating support for API definition
  • +
  • Customisable Store themes for tenants
  • +
  • Forum Support - API Store
  • +
  • Visibility Control for Documentation
  • +
  • Statistics dashboard for southbound API calls
  • +
  • Using Windows Authentication for OAuth2 Token generation
  • +
  • Ability to plugin reusable fault handling logic to APIs
  • +
  • Multi tenancy support for defining external stores, workflows & Google Analytics
  • +
  • Improvements to prevent Cross Site Scripting
  • + + + + +

    Bug Fixes +

    +
      +
    • [APIMANAGER-1775] - Add api fails with a registry error - during a volume test +
    • +
    • [APIMANAGER-1790] - Install Keymanager feature on top of WSO2 IS failed +
    • +
    • [APIMANAGER-1862] - User Token is still generated even when an additional character is appended at the end of the base 64 encoded value +
    • +
    • [APIMANAGER-1864] - Access token generation fails when username and password are similar +
    • +
    • [APIMANAGER-1870] - Jag Exception for API Created with metadata +
    • +
    • [APIMANAGER-1873] - Minor UI issue in Token Validity configuration in store +
    • +
    • [APIMANAGER-1886] - API Can be invoked after removing subscription +
    • +
    • [APIMANAGER-1901] - API-M 1.6.0 start up time is high +
    • +
    • [APIMANAGER-1910] - [Failover endpoint] When production endpoint is down, api invocation fails +
    • +
    • [APIMANAGER-1917] - [KeyManager] [Intermittent] While running a load test get 'ERROR {AUDIT_LOG} - Illegal access attempt' in keyManager +
    • +
    • [APIMANAGER-1925] - [Tenant store] APIs are shown only in recently added section, it does not show up in api list +
    • +
    • [APIMANAGER-1932] - wsdl validation does not validate whether the input is a wsdl or a URI +
    • +
    • [APIMANAGER-1940] - Even if the API fails to get published the state is mentioned as 'Published' +
    • +
    • [APIMANAGER-1957] - Observed error when starting IS after installing key manager feature +
    • +
    • [APIMANAGER-1958] - ResourceNotFoundException observed in key manager nodes +
    • +
    • [APIMANAGER-1967] - [Intermittent] [KeyM] System failed to authorize.null +
    • +
    • [APIMANAGER-1990] - The APIMgtFaultHandler mediator is content aware +
    • +
    • [APIMANAGER-1993] - API Store CSS does not render in IE 8 +
    • +
    • [APIMANAGER-2002] - Updating an API is not possible due to WSDL rewrites +
    • +
    • [APIMANAGER-2003] - Could not subscribe to API's - when a user role/(s) are revoked and trying to subscribe again +
    • +
    • [APIMANAGER-2006] - Re-written WSDL has only the IP:PORT of gateway endpoint +
    • +
    • [APIMANAGER-2013] - Issues in CORS headers management +
    • +
    • [APIMANAGER-2014] - Tryit now feature sends null key, later causes insert error in BAM +
    • +
    • [APIMANAGER-2020] - APIM Tier Permission page not loading +
    • +
    • [APIMANAGER-2028] - Cannot provide a registry resource as the wsdl url and create an API +
    • +
    • [APIMANAGER-2030] - Unable to add an API to external store once it was deleted +
    • +
    • [APIMANAGER-2031] - Exception on first log in attempt to key manager/gateway on a distributed setup +
    • +
    • [APIMANAGER-2037] - When adding an API, and when the API name contains special characters, the API addition fails, but the appeared UI message is not descriptive enough for the user to identify what went wrong. +
    • +
    • [APIMANAGER-2038] - Fix "alg" attribute +
    • +
    • [APIMANAGER-2041] - Workflow admin web application login.jag not loaded for the http url +
    • +
    • [APIMANAGER-2043] - User Sign up(Store) workflow : Rejected/Pending users are not removed +
    • +
    • [APIMANAGER-2045] - Any user with a camel case user name can't see generated sand box key. +
    • +
    • [APIMANAGER-2047] - Warning + Exception in the backend while listing Sequences from the Carbon Management Console +
    • +
    • [APIMANAGER-2048] - Cannot view any sequence in the Main -> Manage -> Sequences page in the Carbon Management Console +
    • +
    • [APIMANAGER-2049] - Task not updated/removed when user is deleted +
    • +
    • [APIMANAGER-2050] - Workflow admin web app does not load Application creation Approval tasks +
    • +
    • [APIMANAGER-2051] - Missing column in PostgreSQL db script +
    • +
    • [APIMANAGER-2052] - API gray-scaling for unapproved subscriptions does not work on firefox +
    • +
    • [APIMANAGER-2053] - User sign up is enabled in API store for read only external primary user stores. +
    • +
    • [APIMANAGER-2054] - Tenant user sign up through store is not restricted when sign up work flow is enabled +
    • +
    • [APIMANAGER-2057] - Cannot log in to publisher, store when a <WebContextRoot> is used +
    • +
    • [APIMANAGER-2059] - Error when invoking APIs with WSDL endpoints +
    • +
    • [APIMANAGER-2061] - Correct the spelling mistake in "API Usage from Destination" - statistics table title +
    • +
    • [APIMANAGER-2064] - Statistics update issue in API invocations with load balanced endpoints ( when an endpoint is not available) +
    • +
    • [APIMANAGER-2065] - API Invocation fails intermittently with Unclassified Authentication Failure. +
    • +
    • [APIMANAGER-2066] - Issues with faulty invocation statistics update +
    • +
    • [APIMANAGER-2067] - API stat publishing : Total duration does not show the usage for the entire period in API usage by user table +
    • +
    • [APIMANAGER-2068] - Error in storing OAuth2 token which is from SAML assertion in h2 database for the users who has capital letters in their name. +
    • +
    • [APIMANAGER-2069] - Cannot generate access tokens for the users who have capital letters in their username in h2 database +
    • +
    • [APIMANAGER-2071] - The traverse link add for APIStore and Publisher not working in sso mode +
    • +
    • [APIMANAGER-2076] - Embed solr indexing to APIStore search and add search by API description +
    • +
    • [APIMANAGER-2077] - Tenant support not available for Application grant type restriction +
    • +
    • [APIMANAGER-2081] - External API stores which are configured for the super tenant can be viewed by other tenants, in Publisher +
    • +
    • [APIMANAGER-2082] - External API stores which are configured for tenants cannot be seen in publisher +
    • +
    • [APIMANAGER-2083] - APIs which are not even in published state can be made visible to external stores +
    • +
    • [APIMANAGER-2084] - Once an API is published to an external store there is no way of removing it from that external store other than deleting the API +
    • +
    • [APIMANAGER-2086] - APIs published to external stores shows incorrect original publisher in Recently added API list +
    • +
    • [APIMANAGER-2087] - 'Test Endpoint button' says valid for some invalid endpoints +
    • +
    • [APIMANAGER-2088] - NPE when invoking the /token API for the first time with tenant user credentials +
    • +
    • [APIMANAGER-2091] - Cannot create an API with secured endpoints using Failover endpoints +
    • +
    • [APIMANAGER-2092] - Never Ending loop of retries with secured endpoints when using Loadbalanced endpoints +
    • +
    • [APIMANAGER-2094] - Application Token regeneration is broken in Store +
    • +
    • [APIMANAGER-2095] - Swagger doc gets overridden if two publishers create two APIs with the same name +
    • +
    • [APIMANAGER-2098] - Edit a published API throwing exception +
    • +
    • [APIMANAGER-2099] - workflow-admin application dosn't work when it accessed from management console url due to redirection issue. +
    • +
    • [APIMANAGER-2100] - New API resource definition UI wizard in publisher, is not visible in IE +
    • +
    • [APIMANAGER-2101] - [UI] 'Add new resource' button in API creation wizard is not working with IE +
    • +
    • [APIMANAGER-2102] - When a scope is added to a resource path in API creation wizard it does not get saved +
    • +
    • [APIMANAGER-2104] - Removing the doc type called 'API message format',which is not useful In Publisher documentation view +
    • +
    • [APIMANAGER-2105] - Cannot add callback URLs with 'localhost' +
    • +
    • [APIMANAGER-2108] - Access token generation based on grant types Authorization code/ Implicit fails for API-M 1.7.0 +
    • +
    • [APIMANAGER-2109] - SSO fails for work flow admin +
    • +
    • [APIMANAGER-2110] - SSO support is not available for tenants +
    • +
    • [APIMANAGER-2112] - SAML2 bearer token exchange with OAuth2 fails for APIM 1.7.0 +
    • +
    • [APIMANAGER-2114] - Typo in the apimgt/postgresql.sql script +
    • +
    • [APIMANAGER-2115] - NTLM grant type -Sample client is not working +
    • +
    • [APIMANAGER-2116] - Error when logging out of SSO enabled Management console +
    • +
    • [APIMANAGER-2118] - Error when loading web apps while SSO is enabled for management console + publisher store web apps +
    • +
    • [APIMANAGER-2119] - Key Validation fails for KeyValidatorClientType:WSClient (api-manager.xml) +
    • +
    • [APIMANAGER-2122] - Blocker for SSO configuration in a setup with Identity server as the key manager +
    • +
    • [APIMANAGER-2123] - APIs can only be editted once +
    • +
    • [APIMANAGER-2124] - API search by part of the name works only when the starting characters are given ( Store) +
    • +
    • [APIMANAGER-2125] - User Sign up(Store) workflow : Rejected/Pending users can generate access tokens +
    • +
    • [APIMANAGER-2127] - Add scopes button not functioning in edit page of APIPublisher +
    • +
    • [APIMANAGER-2128] - OPTIONS retrieves all methods regardless of those which are allowed for the resource path +
    • +
    • [APIMANAGER-2131] - APIManager samples [Youtube.,wikipedia] not working +
    • +
    • [APIMANAGER-2132] - Tenant wise theme uploading gets failed +
    • +
    • [APIMANAGER-2133] - Southbound stat publishing - Destination based usage tracking option no more available on publisher +
    • +
    • [APIMANAGER-2134] - Theme related error when the user store is shared +
    • +
    • [APIMANAGER-2138] - API Docs - Issues with updating /adding new documents +
    • +
    • [APIMANAGER-2139] - Issues with statistic display using Google Analytics +
    • +
    • [APIMANAGER-2140] - APIM version has not been updated in carbon.xml file +
    • +
    • [APIMANAGER-2143] - When an API is created with a "WSDL Endpoint" it does not show the link to the wsdl in store +
    • +
    • [APIMANAGER-2144] - Error when running API-Manager on Keymanager and Gateway profiles +
    • +
    • [APIMANAGER-2147] - Error when publishing to gateway in tenant mode in distributed setup +
    • +
    • [APIMANAGER-2148] - Error on first login attempt from a tenant in a distributed set up +
    • +
    • [APIMANAGER-2149] - [Intermittent] Get the below error when logging in to store as a tenant +
    • +
    • [APIMANAGER-2151] - [Intermittent] Error when logging in to publisher/store after logging into the other node (either publisher or store) +
    • +
    • [APIMANAGER-2152] - Error while publishing the first API of a tenant +
    • +
    • [APIMANAGER-2153] - APIs which are created as "visible to all tenants" are not visible to other tenants +
    • +
    • [APIMANAGER-2154] - NPE when accessing an API in tenant store with out logging in to it +
    • +
    • [APIMANAGER-2155] - Error on store for API changes on publisher +
    • +
    • [APIMANAGER-2162] - API Manager Consent page Deny Action doesn't work +
    • +
    • [APIMANAGER-2164] - Error while trying to validate access token when invoking APIs in tenant mode +
    • +
    • [APIMANAGER-2165] - When sending a multi-rooted JSON message as the payload, with an invalid token you get the payload back in the response converted to xml +
    • +
    • [APIMANAGER-2168] - Error when retrieving tasks to workflow admin when port offset takes a value other than 2 +
    • +
    • [APIMANAGER-2169] - Error when retrieving tasks to workflow admin when port offset takes a value other than 2 +
    • +
    • [APIMANAGER-2174] - Error on key manager start up +
    • +
    • [APIMANAGER-2182] - Exception when shutting down a node in a cluster +
    • +
    • [APIMANAGER-2187] - [Store] Statistics page redirecting to an error page in anonymous mode +
    • +
    • [APIMANAGER-2188] - Error on gateway node start up +
    • +
    • [APIMANAGER-2189] - Menu headers looks same as links in new 'publisher' theme +
    • +
    • [APIMANAGER-2192] - Error when invoking APIs in a cluster when fronted by an ELB +
    • +
    • [APIMANAGER-2193] - Function getPublishedAPIsByProvider ("api" module) returns only a maximum of 5 apis in its result +
    • +
    • [APIMANAGER-2195] - API Manager regenerate the same old token which is already time-out in the gateway +
    • +
    • [APIMANAGER-2198] - API Publisher Statistics - UI unresponsiveness on large amount of data +
    • +
    • [APIMANAGER-2199] - Table 'configDB.REG_LOG' doesn't exist when started with -Dsetup +
    • +
    • [APIMANAGER-2200] - [startup] Error in instantiating class : org.wso2.carbon.apimgt.usage.publisher.APIMgtFaultHandler +
    • +
    • [APIMANAGER-2201] - Error when logging in to publisher (when custom keystores are used instead of the default wso2carbon.jks) +
    • +
    • [APIMANAGER-2202] - Cannot access store in the distributed setup (when custom keystores are used instead of the default wso2carbon.jks) +
    • +
    • [APIMANAGER-2203] - Error setting up API-Manager with PostgreSQL +
    • +
    • [APIMANAGER-2205] - API status get updated even when an error occurs when publishing +
    • +
    • [APIMANAGER-2206] - [intermittent] ResourceNotFoundException +
    • +
    • [APIMANAGER-2207] - Error on first start up attempt of API-M after setting up with oracle +
    • +
    • [APIMANAGER-2208] - [Store] Token Validity period specified when 're-generating' Application token, does not have an effect +
    • +
    • [APIMANAGER-2209] - Different 'scope's set, when generating and regenerating Application tokens +
    • +
    • [APIMANAGER-2211] - Default application in store is missing in the oracle setup +
    • +
    • [APIMANAGER-2212] - SQL Exception when loading an API in the store (Oracle setup) +
    • +
    • [APIMANAGER-2213] - Cannot create applications in the store (Oracle set up) +
    • +
    • [APIMANAGER-2214] - [Usability] After subscribing to an API, page re-direction does not go to the exact subscribed application +
    • +
    • [APIMANAGER-2215] - [Store] Application Tokens does not re-generate after 2nd attempt +
    • +
    • [APIMANAGER-2216] - Destination Statistics table in publisher is not updated +
    • +
    • [APIMANAGER-2217] - NullPointerException on Publisher when loading statistics page +
    • +
    • [APIMANAGER-2219] - Tenant statistics mixup +
    • +
    • [APIMANAGER-2220] - java.lang.IllegalStateException: Trying to set the domain from 2 to 3 +
    • +
    • [APIMANAGER-2222] - Store statistics display per application is limited +
    • +
    • [APIMANAGER-2223] - [LoadTest] PersistenceException: Unable to handle new service addition. Service: wso2carbon-sts +
    • +
    • [APIMANAGER-2224] - Error when loading APIs in the store +
    • +
    • [APIMANAGER-2225] - Carbon server store key display issue +
    • +
    • [APIMANAGER-2228] - Error while updating wso2carbon-sts in STSDeploymentInterceptor +
    • +
    • [APIMANAGER-2229] - When there's a new keystore is used, it's looking for default wso2carbon.jks while the tenant is loaded first time in keymanager +
    • +
    • [APIMANAGER-2230] - Tenant loading issue on gateway (cluster setup) +
    • +
    • [APIMANAGER-2231] - [intermittent] [BAM] Published data does not get written in to database due to constraint violation exception +
    • +
    • [APIMANAGER-2232] - [Intermittent] API invocation count keeps continuously increasing in the cluster set up +
    • +
    • [APIMANAGER-2233] - Tenant user name format in publisher statistics pages +
    • +
    • [APIMANAGER-2234] - [Intermittent] API Usage by User graph is not updated initially +
    • +
    • [APIMANAGER-2236] - Cannot edit an API created with scope restrictions +
    • +
    • [APIMANAGER-2237] - Soap action is not set when logging into workflow admin +
    • +
    • [APIMANAGER-2242] - Gateway message tracing - EndPointURL=null +
    • +
    • [APIMANAGER-2243] - Message tracing does not function properly +
    • +
    • [APIMANAGER-2244] - "AM_API_DEFAULT_VERSION" table is not added in mysql script +
    • +
    • [APIMANAGER-2246] - Cannot add a 'scope' for an API +
    • +
    • [APIMANAGER-2247] - A not properly initiated thrift client will serve key validation requests,when the thrift client initialize during the key manager [thrift server down] +
    • +
    • [APIMANAGER-2248] - Message tracing on gateway does not occur when an API is invoked with an invalid key +
    • +
    • [APIMANAGER-2249] - [UI] Cannot specify advanced options for an endpoint +
    • +
    • [APIMANAGER-2251] - Cannot view the API-Dashboard of an API +
    • +
    • [APIMANAGER-2252] - API hot update fails on gateway +
    • +
    • [APIMANAGER-2255] - "There is no default version for the current API" +
    • +
    • [APIMANAGER-2256] - Issue with POST requests +
    • +
    • [APIMANAGER-2257] - Sends the request back as the response when response caching is enabled, and API moved back to created state +
    • +
    • [APIMANAGER-2258] - Cannot delete API with Subscriptions which is not the default version API +
    • +
    • [APIMANAGER-2260] - Remove JS alerts added to the Publisher/Store UIs +
    • +
    • [APIMANAGER-2262] - [Publisher] - UI issues +
    • +
    • [APIMANAGER-2264] - Cannot get API dashboard when using oracle as the database +
    • +
    • [APIMANAGER-2265] - Cannot view created APIs (Oracle setup) +
    • +
    • [APIMANAGER-2266] - "AM_API_DEFAULT_VERSION" table is not added to AM_DB Oracle script +
    • +
    • [APIMANAGER-2268] - 8 Tables are not getting created in AM_DB oracle script with -Dsetup +
    • +
    • [APIMANAGER-2271] - tiers.xml added values are shown incorrectly +
    • +
    • [APIMANAGER-2272] - NPE when invoking Token API with about 500 concurrency +
    • +
    • [APIMANAGER-2273] - Tier information mess up in API subscription page in Store, after denying certain tiers to some roles +
    • +
    • [APIMANAGER-2274] - Error message printed when statistics datasource is not properly configured +
    • +
    • [APIMANAGER-2275] - Cannot publish API statistics when BAM server is changed +
    • +
    • [APIMANAGER-2279] - Generic error message on publisher UI for several scenarios +
    • +
    • [APIMANAGER-2281] - Obsolete copyright in management UI +
    • +
    • [APIMANAGER-2282] - Publisher does not work in IE9 +
    • +
    • [APIMANAGER-2284] - Error when loading APIs containing documents with denied read permission for wso2.anonymous.role +
    • +
    • [APIMANAGER-2285] - HTTP 404 error returns when adding an application in IE (9 or 10) +
    • +
    • [APIMANAGER-2286] - Document read 'deny' permission of wso2.anonymous.role is applied to all documents of an API +
    • +
    • [APIMANAGER-2287] - Cannot add a tenant in MSSQL setup +
    • +
    • [APIMANAGER-2288] - AM_API_DEFAULT_VERSION table is missing in MSSQL script +
    • +
    • [APIMANAGER-2289] - Invalid column name 'TENANT_ID' error thrown continously when accessing carbon/idpmgt/idp-mgt-edit.jsp +
    • +
    • [APIMANAGER-2290] - Unable to regenerate access token +
    • +
    • [APIMANAGER-2291] - NPE thrown when generating tokens with external LDAP +
    • +
    • [APIMANAGER-2292] - Need migration scripts from AM 1.6.0 to 1.7.0 +
    • +
    • [APIMANAGER-2293] - Roles/Users created in primary store get created in other secondary stores as well +
    • +
    • [APIMANAGER-2294] - User mgt features are not updated with IS 5.0.0 +
    • +
    • [APIMANAGER-2295] - Cannot add identity providers +
    • +
    • [APIMANAGER-2296] - If you try to two documents with the same name for the same API there is no error/ warning message for the user +
    • +
    • [APIMANAGER-2297] - Tenant specific SSO does not work +
    • +
    • [APIMANAGER-2302] - Cannot generate tokens when AM_DB pointed to Oracle +
    • +
    • [APIMANAGER-2304] - [Intermittent] ORA-12516, TNS:listener could not find available handler with matching protocol stack +
    • +
    • [APIMANAGER-2306] - No response for MT API invocations - MT broken +
    • +
    • [APIMANAGER-2309] - Token re-generation fails when WebContextRoot is defined +
    • +
    • [APIMANAGER-2310] - Registry Browsing broken +
    • +
    • [APIMANAGER-2311] - Can log in to store and publisher from 2 different users in an SSO enabled set up when user permissions differ +
    • +
    • [APIMANAGER-2312] - Publisher login page loaded in an SSO enabled set up on attempts to log in with a user without publisher permission +
    • +
    • [APIMANAGER-2315] - Cannot create tenants in AM cluster setup [openLDAP, oracle] +
    • +
    • [APIMANAGER-2316] - Error when executing am_stats_analyzer in the oracle setup +
    • +
    • [APIMANAGER-2317] - Error when executing am_stats_analyzer in the oracle setup +
    • +
    • [APIMANAGER-2319] - AM_* tables are not created when running -Dsetup with MSSQL +
    • +
    • [APIMANAGER-2322] - [UI]APIM quick start dashbaord is wrong +
    • +
    • [APIMANAGER-2323] - Swagger console does not work in IE (10) +
    • +
    • [APIMANAGER-2325] - Document content is not shown in tenant's API store +
    • +
    • [APIMANAGER-2326] - Console URLs are not comprised with proxy ports, in cluster setup +
    • +
    • [APIMANAGER-2327] - Repetitive Error messages on server startup when APIUSageTracking enabled in store +
    • +
    • [APIMANAGER-2329] - [API Resource] Edit an existing API and provide a URL pattern not working +
    • +
    • [APIMANAGER-2330] - The same Access Token and User Token, for the Store user, gives a wrong Expiration time with the token API +
    • +
    • [APIMANAGER-2334] - Error when running Youtube API sample +
    • +
    • [APIMANAGER-2336] - 8th May 2014 pack reports syntax errors when executing MySQL db script +
    • +
    • [APIMANAGER-2337] - Sandbox keys are not generated for users who have capital letters in their user name +
    • +
    • [APIMANAGER-2338] - Please remove obsolete BPSWorkFlow sample from AM-1.7 distribution +
    • +
    • [APIMANAGER-2339] - [Intermittent] Issue with subscription confirmation pop up message +
    • +
    • [APIMANAGER-2340] - Store users can edit (change tiers) apps which are not ACTIVE +
    • +
    • [APIMANAGER-2344] - NPE thrown when pushing API to an external store +
    • +
    • [APIMANAGER-2346] - Error when starting API manager on gateway profile +
    • +
    • [APIMANAGER-2347] - Error when logging into workflow admin +
    • +
    • [APIMANAGER-2355] - Cannot assign a scope to an API resource [Oracle] +
    • +
    • [APIMANAGER-2358] - publisher/store is really slow to respond in cluster setup with Oracle +
    • +
    • [APIMANAGER-2359] - Subscriber role is not assinged to users created through user sign up work flow +
    • +
    • [APIMANAGER-2360] - Exceptions logged when approving/rejecting workflow tasks +
    • +
    • [APIMANAGER-2361] - Notification for pending approval is not displayed for Application Creation tasks on the Oracle setup +
    • +
    • [APIMANAGER-2362] - Invalid Subscription confirmation message shown +
    • +
    • [APIMANAGER-2364] - Application is added in "inactive" state even if the app creation workflow fails +
    • +
    • [APIMANAGER-2368] - Copy API feature does not work in IE +
    • +
    • [APIMANAGER-2369] - NPE when tenant unloading on gateway nodes +
    • +
    • [APIMANAGER-2370] - Auto subscribed new APIs can be invoked even if the subscription for the original API is not approved +
    • +
    • [APIMANAGER-2372] - Multiple tasks created for the same subscription +
    • +
    • [APIMANAGER-2373] - [Intermittent] 403: Resource forbidden error on gateway nodes when doing a load test +
    • +
    • [APIMANAGER-2374] - Sandbox application token generation not working for a subscriber having upper case username +
    • +
    • [APIMANAGER-2375] - Resource not found exception when tenant getting loaded on gateway node +
    • +
    • [APIMANAGER-2376] - Tenant loading fails in Gateway after restarting the server, due to 'Resource does not exist at path /_system/config/repository/transports/https/listener' +
    • +
    • [APIMANAGER-2378] - Cannot create APIs +
    • +
    • [APIMANAGER-2379] - [samples]Two statements failed in userPopulater.sql +
    • +
    • [APIMANAGER-2381] - Key validation fails when gateway caching is enabled (workflow related) +
    • +
    • [APIMANAGER-2382] - Sandbox Application-user token scope is stored as PRODUCTION in IDN_OAUTH2_ACCESS_TOKEN +
    • +
    • [APIMANAGER-2387] - Tenant API store loading when SSO is enabled +
    • +
    • [APIMANAGER-2391] - Visible to Role option is given as mandatory only when the API creaion time. Editing an existing API can be done without filling the Visible to Roles textbox +
    • +
    • [APIMANAGER-2393] - Publisher node trying to publish stats to the BAM +
    • +
    • [APIMANAGER-2394] - Too many INFO/ WARN logs when connecting registry mounts +
    • +
    • [APIMANAGER-2397] - [Intermittent] Resource not found exception at KeyManager node when tenant is logging in to Publisher node +
    • +
    • [APIMANAGER-2398] - Cannot publish to gateway while a mild load test happening (Connection timed out) +
    • +
    • [APIMANAGER-2399] - [intermittent] [loadtest] NPE when changing API status, while running a mild load test +
    • +
    • [APIMANAGER-2400] - [intermittent] ResourceNotFoundException on one tenat's resource while logged in to the store with some other tenant. +
    • +
    • [APIMANAGER-2402] - SQLException: ORA-02292 - After removing a scope restriction from a resource and saving the API +
    • +
    • [APIMANAGER-2403] - http 403 error response for POST requests sent inside a SOAP envelope but for GET requests response comes as a plain xml +
    • +
    • [APIMANAGER-2405] - Workflow admin multiple role log in issue (Intermittant) +
    • +
    • [APIMANAGER-2408] - when registry path is there as wsdl url test option will not work. +
    • +
    • [APIMANAGER-2409] - Cannot install APIM 1.7.0 Key manager feature in IS 5.0.0 +
    • +
    • [APIMANAGER-2411] - SOAPAction header is removed by the Gateway +
    • +
    • [APIMANAGER-2419] - Same token is regenerated when token encryption enabled +
    • +
    • [APIMANAGER-2420] - Subscription related usability issue +
    • +
    • [APIMANAGER-2421] - [Cluster] Session with the ELB breaks in 'store' when the redirection happens after creating a new application +
    • +
    • [APIMANAGER-2422] - [Publisher Stats] 'API Usage by User' displays super tenant information in tenant mode for All Statistics +
    • +
    • [APIMANAGER-2424] - Design Issue in <RevokeAPIURL> +
    • +
    • [APIMANAGER-2427] - [IS as KeyManager] http 500 error when regenerating APPLICATION tokens +
    • +
    • [APIMANAGER-2428] - Remove <GoogleAnalyticsTracking> from api-manager.xml +
    • +
    • [APIMANAGER-2430] - Error on gateway when invoking token API +
    • +
    • [APIMANAGER-2434] - CLONE - Add api fails with a registry error - during a volume test +
    • +
    • [APIMANAGER-2436] - When publishing to external API stores the context get appended with external tenants context in API console +
    • +
    • [APIMANAGER-2437] - Inappropriate error message when a tenant is not available in an external store +
    • +
    • [APIMANAGER-2438] - Cannot authenticate when publishing to external wso2 store in https mode +
    • +
    • [APIMANAGER-2439] - Error when publishing to external tenant store in the same node +
    • +
    • [APIMANAGER-2440] - HTTP 500 page when click in "Visit publisher store" due to an invalid url +
    • +
    • [APIMANAGER-2447] - Error thrown when the swagger doc permissions changed to restrict for registered users +
    • +
    • [APIMANAGER-2448] - Add documentation button not working in 21/05/14 nightly built AM 1.7.0 pack +
    • +
    • [APIMANAGER-2449] - Swagger doc update function not working +
    • +
    • [APIMANAGER-2451] - [Pulisher] Exception "Invalid number of parameters or their types" thrown when selecting 'Add' or 'New API' +
    • +
    • [APIMANAGER-2457] - Error when saving the API in Design stage +
    • +
    • [APIMANAGER-2458] - Cannot Create Copies of the Published API +
    • +
    • [APIMANAGER-2459] - Tenant Store-Anonymous view documents listing shwoing without considering doc permissions +
    • +
    • [APIMANAGER-2460] - Exceptions in store when you click on lifecycles for APIs in Design stage +
    • +
    • [APIMANAGER-2461] - Swagger UI not showing in tenant store -API Browse view +
    • +
    • [APIMANAGER-2462] - Resource path is not mandatory and neither checked or validated or generated when creating API +
    • +
    • [APIMANAGER-2463] - [Tenant mode]Doc permissions not propagating when the API visibility is 'Restricted by roles' +
    • +
    • [APIMANAGER-2465] - Workflow admin login fails when the key manager has a web context root +
    • +
    • [APIMANAGER-2466] - Store is taking a very long time to load when connected to OpenLDAP +
    • +
    • [APIMANAGER-2469] - Cannot remove a resource completely +
    • +
    • [APIMANAGER-2470] - Tenant contexts mixes up when two tenants/super admin doing operations on store +
    • +
    • [APIMANAGER-2471] - Cannot create a tenant +
    • +
    • [APIMANAGER-2472] - How to configure <RevokeAPIURL> in distributed setup +
    • +
    • [APIMANAGER-2473] - Application creation - UI issue +
    • +
    • [APIMANAGER-2478] - API_M doc links should be directed v1.7.0 docs +
    • +
    • [APIMANAGER-2479] - Cannot arrange the order of precedence of resources +
    • +
    • [APIMANAGER-1883] - Token generation fails with 'org.wso2.carbon.identity.oauth.tokenprocessor.EncryptionDecryptionPersistenceProcessor' TokenPersistenceProcessor +
    • +
    • [APIMANAGER-1890] - Resource base URI is shown in wadl and shouldn't we replace it with gateway parameters as we do for wsdls +
    • +
    • [APIMANAGER-1988] - No UI message showing when no subscriptions available for logged user +
    • +
    • [APIMANAGER-1999] - Make the API LC executor independent from G-Reg. +
    • +
    • [APIMANAGER-2042] - Provide the ability for the tenants to customise their Store theme +
    • +
    • [APIMANAGER-2097] - Add more help contexts for add/edit API form in publisher +
    • +
    • [APIMANAGER-2177] - Better to have direct filter options in publisher API page +
    • +
    • [APIMANAGER-2280] - Production and Sandbox URLs are not validated +
    • +
    • [APIMANAGER-2352] - make Store names configurable in a multi tenanted environment +
    • +
    • [APIMANAGER-2356] - Seperate configuration used to cache Token and API Resource cache in APIM gateway node +
    • +
    • [APIMANAGER-2404] - Add API resource sub-context based search to APIStore +
    • +
    • [APIMANAGER-2432] - Add more granular level permissions to API documents +
    • +
    • [APIMANAGER-2444] - [API publisher] Add ability to store roles against API Scopes +
    • +
    • [APIMANAGER-2450] - Change the way how swagger content retrieving in APIStore without using registry permlinks +
    • +
    + +

    Patches for previous release version

    +
      +
    • [APIMANAGER-1992] - API Usage By User report in WSO2 Api publisher does not work on Postgres +
    • +
    • [APIMANAGER-1997] - APIM 1.6.0 WSDL reference points to absolute GRed resource location in a mounted setup +
    • +
    • [APIMANAGER-2033] - HTTP endpoints get replaced with HTTPS gateway URL +
    • +
    • [APIMANAGER-2036] - If an API is deleted from External API Store, the publishing to External API Store again fails +
    • +
    • [APIMANAGER-2204] - User claims are not included in JWT token +
    • +
    • [APIMANAGER-2241] - ConcurrentModificationException at server startup +
    • +
    • [APIMANAGER-2254] - Fields under endpoint type are not rendered in IE 9 and below +
    • +
    + + + + + + + + +

    All resolved issues

    + + +

    Key Features of WSO2 API Manager

    +

    + Following is a categorization of the core features supported by WSO2 API Manager + based on the target user group. +

    +
      +
    • Create a Store of all Available APIs: +
        +
      • Graphical experience similar to Android Marketplace or Apple App Store.
      • +
      • Browse APIs by provider, tags or name.
      • +
      • Self-registration to developer community to subscribe to APIs.
      • +
      • Subscribe to APIs and manage subscriptions on per-application basis.
      • +
      • Subscriptions can be at different service tiers based on expected usage levels.
      • +
      • Role based access to API Store; manage public and private APIs.
      • +
      • Manage subscriptions at a per-developer level.
      • +
      • Browse API documentation, download helpers for easy consumption.
      • +
      • Comment on and rate APIs.
      • +
      • Forum for discussing API usage issues (Available soon in future version).
      • +
      • Try APIs directly on the store front.
      • +
      • Internationalization (i18n) support.
      • +
      + +
    • +
    • Publishing and Governing API Use: +
        + +
      • Publish APIs to external consumers and partners, as well as internal users.
      • +
      • Supports publishing multiple protocols including SOAP, REST, JSON and XML style services as APIs.
      • +
      • Manage API versions and deployment status by version.
      • +
      • Govern the API lifecycle (publish, deprecate, retire).
      • +
      • Attach documentation (files, external URLs) to APIs.
      • +
      • Apply Security policies to APIs (authentication, authorization).
      • +
      • Associate API available to system defined service tiers.
      • +
      • Provision and Manage API keys.
      • +
      • Track consumers per API.
      • +
      • One-click deployment to API Gateway for immediate publishing.
      • +
      + +
    • +
    • Route API Traffic: +
        + +
      • Supports API authentication with OAuth2.
      • +
      • Extremely high performance pass-through message routing with sub-millisecond latency.
      • +
      • Enforce rate limiting and throttling policies for APIs by consumer.
      • +
      • Horizontally scalable with easy deployment into cluster using proven routing infrastructure.
      • +
      • Scales to millions of developers/users.
      • +
      • Capture all statistics and push to pluggable analytics system.
      • +
      • Configure API routing policies with capabilities of WSO2 Enterprise Service Bus.
      • +
      • Powered by WSO2 Enterprise Service Bus.
      • +
      +
    • + +
    • Manage Developer Community: +
        +
      • Self-sign up for API consumption.
      • +
      • Manage user account including password reset.
      • +
      • Developer interaction with APIs via comments and ratings.
      • +
      • Support for developer communication via forums (Available soon in future version).
      • +
      • Powered by WSO2 Identity Server.
      • +
      +
    • + +
    • Govern Complete API Lifecycle: +
        +
      • Manage API lifecycle from cradle to grave: create, publish, block, deprecate and retire.
      • +
      • Publish both production and sandbox keys for APIs to enable easy developer testing.
      • +
      • Publish APIs to partner networks such as ProgrammableWeb (Available soon in future version).
      • +
      • Powered by WSO2 Governance Registry.
      • +
      +
    • + +
    • Monitor API Usage and Performance: +
        +
      • All API usage published to pluggable analytics framework.
      • +
      • Out of the box support for WSO2 Business Activity Monitor and Google Analytics.
      • +
      • View metrics by user, API and more.
      • +
      • Customized reporting via plugging reporting engines.
      • +
      • Monitor SLA compliance.
      • +
      • Powered by WSO2 Business Activity Monitor.
      • +
      +
    • + +
    • Pluggable, Extensible and Themeable: +
        +
      • All components are highly customizable thru styling, theming and open source code.
      • +
      • Storefront implemented with Jaggery (jaggeryjs.org) for easy customization.
      • +
      • Pluggable to third party analytics systems and billing systems (Available soon in future version).
      • +
      • Pluggable to existing user stores including via JDBC and LDAP.
      • +
      • Components usable separately - storefront can be used to front APIs gatewayed via third party gateways such as Intel Expressway Service Gateway.
      • +
      • Support for Single Sign On (SSO) using SAML 2.0 for easy integration with existing web apps
      • +
      +
    • + +
    • Easily Deployable in Enterprise Setting: +
        +
      • Role based access control for managing users and their authorization levels.
      • +
      • Store front can be deployed in DMZ for external access with Publisher inside the firewall for private control.
      • +
      • Different user stores for developer focused store-front and internal operations in publisher.
      • +
      • Integrates with enterprise identity systems including LDAP and Microsoft Active Directory.
      • +
      • Gateway can be deployed in DMZ with controlled access to WSO2 Identity Server (for authentication/authorization) and governance database behind firewall.
      • + +
      +
    • + +
    • Support for creating multi-tenanted APIs +
        +
      • Run a single instance and provide API Management to multiple customers
      • +
      • Share APIs between different departments in a large enterprise
      • +
      +
    • + +
    • Publishing and Governing API Use +
        +
      • Document an API using Swagger
      • +
      • Restrict API Access tokens to domains/IPs
      • +
      • Ability to block a subscription and restricting a complete application
      • +
      • Ability to revoke access tokens
      • +
      • Separate validity period configuration for Application Access Token
      • +
      • OAuth2 Authorization Code Grant Type Support
      • +
      • Configuring execution point of mediation extensions
      • +
      +
    • + +
    • Monitor API Usage and Performance +
        +
      • Improved dashboard for monitoring usage statistics (Filtering data for a date range, More visually appealing widgets)
      • +
      +
    • +
    + +

    Known Issues

    +

    + All the open issues pertaining to WSO2 API Manager are reported at the following + location: +

    + + +

    How You Can Contribute

    +

    + Mailing Lists +

    +

    + Join our mailing list and correspond with the developers directly. +

    + +

    + Reporting Issues +

    +

    + We encourage you to report issues, documentation faults and feature requests + regarding + WSO2 API Manager through the public API Manager + JIRA. You + can use the + Carbon JIRA + to report any + issues related to the Carbon base framework or associated Carbon components. +

    + +

    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 more details and to take advantage of this unique opportunity please + visit http://wso2.com/support. +

    +

    + To learn more about WSO2 API Manager and WSO2 support offerings please visit + http://wso2.com/products/api-manager. +

    + +

    + -- The WSO2 API Manager Team -- +

    +
    + +