how to invoke adapters hybrid application MobileFirst Platform 6.3 - ibm-mobilefirst

i have some error
Caused by: FWLSE0099E: An error occurred while invoking procedure [project EMoney]InquiryAdapters/HttpRequestFWLSE0100E: parameters: [project EMoney]
Http request failed: org.apache.http.conn.HttpHostConnectException: Connect to rss.cnn.com:80 [rss.cnn.com/74.125.200.121] failed: Connection timed out: connect
FWLSE0101E: Caused by: [project EMoney]org.apache.http.conn.HttpHostConnectException: Connect to rss.cnn.com:80 [rss.cnn.com/74.125.200.121] failed: Connection timed out: connectjava.lang.RuntimeException: Http request failed: org.apache.http.conn.HttpHostConnectException: Connect to rss.cnn.com:80 [rss.cnn.com/74.125.200.121] failed: Connection timed out: connect
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to rss.cnn.com:80 [rss.cnn.com/74.125.200.121] failed: Connection timed out: connect
Caused by: java.net.ConnectException: Connection timed out: connect
inquiryAdapters.xml
<wl:adapter name="InquiryAdapters"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:wl="http://www.ibm.com/mfp/integration"
xmlns:http="http://www.ibm.com/mfp/integration/http">
<displayName>InquiryAdapters</displayName>
<description>InquiryAdapters</description>
<connectivity>
<connectionPolicy xsi:type="http:HTTPConnectionPolicyType">
<protocol>http</protocol>
<domain>rss.cnn.com</domain>
<port>80</port>
<connectionTimeoutInMilliseconds>30000</connectionTimeoutInMilliseconds>
<socketTimeoutInMilliseconds>30000</socketTimeoutInMilliseconds>
<maxConcurrentConnectionsPerNode>50</maxConcurrentConnectionsPerNode>
<!-- Following properties used by adapter's key manager for choosing specific certificate from key store
<sslCertificateAlias></sslCertificateAlias>
<sslCertificatePassword></sslCertificatePassword>
-->
</connectionPolicy>
</connectivity>
<procedure name="getStories"/>
<procedure name="getStoriesFiltered"/>
<procedure name="getFeedsFiltered"/>
</wl:adapter>
inquiryAdapters.impl
function getStories(interest) {
path = getPath(interest);
var input = {
method : 'get',
returnedContentType : 'xml',
path : path
};
return WL.Server.invokeHttp(input);}
function getStoriesFiltered(interest) {
path = getPath(interest);
var input = {
method : 'get',
returnedContentType : 'xml',
path : path,
transformation : {
type : 'xslFile',
xslFile : 'filtered.xsl'
}
};
return WL.Server.invokeHttp(input);}
function getFeedsFiltered() {
var input = {
method : 'get',
returnedContentType : 'xml',
path : "rss.xml",
transformation : {
type : 'xslFile',
xslFile : 'filtered.xsl'
}
};
return WL.Server.invokeHttp(input);}
function getPath(interest) {
if (interest == undefined || interest == '') {
interest = '';
}else {
interest = '_' + interest;
}
return 'rss/edition' + interest + '.rss';}
when i want to invoke the adapters (http adapters).

If you have followed the next steps yet you get a "Connection timed out" error, you likely have a network issue unrelated to MobileFirst Platform 6.3: check for any firewalls that prevent your connection to arrive to CNN.com
Created a new project
Create a new HTTP adapter
Right-click on adapter folder > Deploy MobileFirst Adapter
Right-click on adapter folder > Call MobileFirst Adapter
Now a browser window with the response should've opened.

Related

Ktor-server-test-host did not cleaned up Exposed database instannce across tests

I'm working on a web service using Ktor 1.6.8 and Exposed 0.39.2.
My application module and database is setup as following:
fun Application.module(testing: Boolean = false) {
val hikariConfig =
HikariConfig().apply {
driverClassName = "org.postgresql.Driver"
jdbcUrl = environment.config.propertyOrNull("ktor.database.url")?.getString()
username = environment.config.propertyOrNull("ktor.database.username")?.getString()
password = environment.config.propertyOrNull("ktor.database.password")?.getString()
maximumPoolSize = 10
isAutoCommit = false
transactionIsolation = "TRANSACTION_REPEATABLE_READ"
validate()
}
val pool = HikariDataSource(hikariConfig)
val db = Database.connect(pool, {}, DatabaseConfig { useNestedTransactions = true })
}
I use ktor-server-test-host, Test Containers and junit 5 to test the service. My test looks similar like below:
#Testcontainers
class SampleApplicationTest{
companion object {
#Container
val postgreSQLContainer = PostgreSQLContainer<Nothing>(DockerImageName.parse("postgres:13.4-alpine")).apply {
withDatabaseName("database_test")
}
}
#Test
internal fun `should make request successfully`() {
withTestApplication({
(environment.config as MapApplicationConfig).apply {
put("ktor.database.url", postgreSQLContainer.jdbcUrl)
put("ktor.database.user", postgreSQLContainer.username)
put("ktor.database.password", postgreSQLContainer.password)
}
module(testing = true)
}) {
handleRequest(...)
}
}
}
I observed an issue that if I ran multiple test classes together, some requests ended up using old Exposed db instance that was setup in a previous test class, causing the test case failed because the underlying database was already stopped.
When I ran one test class at a time, all were running fine.
Please refer to the log below for the error stack trace:
2022-10-01 08:00:36.102 [DefaultDispatcher-worker-5 #request#103] WARN Exposed - Transaction attempt #1 failed: java.sql.SQLTransientConnectionException: HikariPool-4 - Connection is not available, request timed out after 30001ms.. Statement(s): INSERT INTO cards (...)
org.jetbrains.exposed.exceptions.ExposedSQLException: java.sql.SQLTransientConnectionException: HikariPool-4 - Connection is not available, request timed out after 30001ms.
at org.jetbrains.exposed.sql.statements.Statement.executeIn$exposed_core(Statement.kt:49)
at org.jetbrains.exposed.sql.Transaction.exec(Transaction.kt:143)
at org.jetbrains.exposed.sql.Transaction.exec(Transaction.kt:128)
at org.jetbrains.exposed.sql.statements.Statement.execute(Statement.kt:28)
at org.jetbrains.exposed.sql.QueriesKt.insert(Queries.kt:73)
at com.example.application.services.CardService$createCard$row$1.invokeSuspend(CardService.kt:53)
at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt$suspendedTransactionAsyncInternal$1.invokeSuspend(Suspended.kt:127)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
Caused by: java.sql.SQLTransientConnectionException: HikariPool-4 - Connection is not available, request timed out after 30001ms.
at com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:695)
at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:197)
at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:162)
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:100)
at org.jetbrains.exposed.sql.Database$Companion$connect$3.invoke(Database.kt:142)
at org.jetbrains.exposed.sql.Database$Companion$connect$3.invoke(Database.kt:139)
at org.jetbrains.exposed.sql.Database$Companion$doConnect$3.invoke(Database.kt:127)
at org.jetbrains.exposed.sql.Database$Companion$doConnect$3.invoke(Database.kt:128)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManager$ThreadLocalTransaction$connectionLazy$1.invoke(ThreadLocalTransactionManager.kt:69)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManager$ThreadLocalTransaction$connectionLazy$1.invoke(ThreadLocalTransactionManager.kt:68)
at kotlin.UnsafeLazyImpl.getValue(Lazy.kt:81)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManager$ThreadLocalTransaction.getConnection(ThreadLocalTransactionManager.kt:75)
at org.jetbrains.exposed.sql.Transaction.getConnection(Transaction.kt)
at org.jetbrains.exposed.sql.statements.InsertStatement.prepared(InsertStatement.kt:157)
at org.jetbrains.exposed.sql.statements.Statement.executeIn$exposed_core(Statement.kt:47)
... 19 common frames omitted
Caused by: org.postgresql.util.PSQLException: Connection to localhost:49544 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:303)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:51)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:223)
at org.postgresql.Driver.makeConnection(Driver.java:465)
at org.postgresql.Driver.connect(Driver.java:264)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477)
at com.zaxxer.hikari.pool.HikariPool.access$100(HikariPool.java:71)
at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:725)
at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:711)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.net.ConnectException: Connection refused
at java.base/sun.nio.ch.Net.pollConnect(Native Method)
at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:672)
at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:542)
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
I tried to add some cleanup code for Exposed's TransactionManager in my application module as following:
fun Application.module(testing: Boolean = false) {
// ...
val db = Database.connect(pool, {}, DatabaseConfig { useNestedTransactions = true })
if (testing) {
environment.monitor.subscribe(ApplicationStopped) {
TransactionManager.closeAndUnregister(db)
}
}
}
However, the issue still happened, and I also observed additional error as following:
2022-10-01 08:00:36.109 [DefaultDispatcher-worker-5 #request#93] ERROR Application - Unexpected error
java.lang.RuntimeException: database org.jetbrains.exposed.sql.Database#3bf4644c don't have any transaction manager
at org.jetbrains.exposed.sql.transactions.TransactionApiKt.getTransactionManager(TransactionApi.kt:149)
at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt.closeAsync(Suspended.kt:85)
at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt.access$closeAsync(Suspended.kt:1)
at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt$suspendedTransactionAsyncInternal$1.invokeSuspend(Suspended.kt:138)
(Coroutine boundary)
at org.mpierce.ktor.newrelic.KtorNewRelicKt$runPipelineInTransaction$2.invokeSuspend(KtorNewRelic.kt:178)
at org.mpierce.ktor.newrelic.KtorNewRelicKt$setUpNewRelic$2.invokeSuspend(KtorNewRelic.kt:104)
at io.ktor.routing.Routing.executeResult(Routing.kt:154)
at io.ktor.routing.Routing$Feature$install$1.invokeSuspend(Routing.kt:107)
at io.ktor.features.ContentNegotiation$Feature$install$1.invokeSuspend(ContentNegotiation.kt:145)
at io.ktor.features.StatusPages$interceptCall$2.invokeSuspend(StatusPages.kt:102)
at io.ktor.features.StatusPages.interceptCall(StatusPages.kt:101)
at io.ktor.features.StatusPages$Feature$install$2.invokeSuspend(StatusPages.kt:142)
at io.ktor.features.CallLogging$Feature$install$2.invokeSuspend(CallLogging.kt:188)
at io.ktor.server.testing.TestApplicationEngine$callInterceptor$1.invokeSuspend(TestApplicationEngine.kt:296)
at io.ktor.server.testing.TestApplicationEngine$2.invokeSuspend(TestApplicationEngine.kt:50)
Caused by: java.lang.RuntimeException: database org.jetbrains.exposed.sql.Database#3bf4644c don't have any transaction manager
at org.jetbrains.exposed.sql.transactions.TransactionApiKt.getTransactionManager(TransactionApi.kt:149)
at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt.closeAsync(Suspended.kt:85)
at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt.access$closeAsync(Suspended.kt:1)
at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt$suspendedTransactionAsyncInternal$1.invokeSuspend(Suspended.kt:138)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
Could someone show me what could be the issue here with my application code & test setup?
Thanks and regards.

Mobilefirst 7.1 Adapter - CLI

I am using MobileFirst CLI 7.1. I am following the tutorial (https://developer.ibm.com/mobilefirstplatform/documentation/getting-started-7-1/foundation/hello-world/integrating-mfpf-sdk-in-cordova-applications/) and almost everything works fine. I am using the RSSAdapter and I keep getting the following error when I deploy the app to the phone:
status : 500
responseHeaders {5}
X-Powered-By : Servlet/3.0
Content-Type : application/json
Content-Length : 430
Connection : Close
Date : Mon, 24 Aug 2015 09:55:41 GMT
responseText : {\"statusCode\":404,\"errors\":[\"White spaces are required between publicId and systemId.\",\"Failed to parse the payload from backend (procedure: HttpRequest)\"],\"isSuccessful\":false,\"statusReason\":\"Not Found\",\"responseHeaders\":{\"Date\":\"Mon, 24 Aug 2015 09:55:41 GMT\",\"Content-Length\":\"149\",\"Content-Type\":\"text/html;charset=UTF-8\",\"Connection\":\"close\",\"Server\":\"FeedsPortal\"},\"warnings\":[],\"totalTime\":276,\"responseTime\":244,\"info\":[]}
responseJSON {9}
statusCode : 404
errors [2]
0 : White spaces are required between publicId and systemId.
1 : Failed to parse the payload from backend (procedure: HttpRequest)
isSuccessful : false
statusReason : Not Found
responseHeaders {5}
warnings [0]
totalTime : 276
responseTime : 244
info [0]
invocationContext : null
This is how my code looks like:
--- RSSAdapter.xml ----
<?xml version="1.0" encoding="UTF-8"?>
<wl:adapter name="RSSAdapter"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:wl="http://www.ibm.com/mfp/integration"
xmlns:http="http://www.ibm.com/mfp/integration/http">
<displayName>RSSAdapter</displayName>
<description>RSSAdapter</description>
<connectivity>
<connectionPolicy xsi:type="http:HTTPConnectionPolicyType">
<protocol>http</protocol>
<domain>rss.cnn.com</domain>
<port>80</port>
<connectionTimeoutInMilliseconds>30000</connectionTimeoutInMilliseconds>
<socketTimeoutInMilliseconds>30000</socketTimeoutInMilliseconds>
<maxConcurrentConnectionsPerNode>50</maxConcurrentConnectionsPerNode>
<!-- Following properties used by adapter's key manager for choosing specific certificate from key store
<sslCertificateAlias></sslCertificateAlias>
<sslCertificatePassword></sslCertificatePassword>
-->
</connectionPolicy>
</connectivity>
<procedure name="getStories"/>
<procedure name="getStoriesFiltered"/>
</wl:adapter>
----- RSSAdapter-impl.js ---
function getStories(interest) {
path = getPath(interest);
var input = {
method : 'get',
returnedContentType : 'xml',
path : path
};
return WL.Server.invokeHttp(input);
}
function getStoriesFiltered(interest) {
path = getPath(interest);
var input = {
method : 'get',
returnedContentType : 'xml',
path : path,
transformation : {
type : 'xslFile',
xslFile : 'filtered.xsl'
}
};
return WL.Server.invokeHttp(input);
}
function getPath(interest) {
if (interest == undefined || interest == '') {
interest = '';
}else {
interest = '_' + interest;
}
return 'rss/edition' + interest + '.rss';
}
--- JS ---
function invokeAdapter() {
var resourceRequest = new WLResourceRequest(
"/adapters/RSSAdapter/getStories",
WLResourceRequest.GET);
resourceRequest.send().then(success,error);
}
function success(res) {
console.log('Success');
console.log('res ', res);
/*console.log('Text ', res.responseJSON.rss.channel.item.length);*/
console.log('Text ', res.responseJSON);
alert("Total RSS Feed items received:"+res.responseJSON);
}
function error(error) {
console.log('Nei');
console.log('error ', JSON.stringify(error));
alert("Response error"+ JSON.stringify(error));
}
Update: in recent iFixes, the default adapter was changed to no longer point to CNN. If you haven't, please upgrade.
There is nothing wrong with your project. For whatever reason it appears that the default adapter created has stopped working with the CNN website; it is being investigated.
In the meanwhile you can either use an adapter from a different project (that is working with the engadget website), or create your own.
See for example the adapter that is provided as part of the Starter Application sample (you can copy the adapter folder to your MobileFirst project and use "mfp push" to deploy it to the server; make sure to update the adapter and procedure names in your applicative code).

Worklight Single Step Authentication and SQL adapter

I am developing jQuery based mobile app and trying to use Single Step authentication using my custom login page. The login page collects loan# and pin from the user and use them to query MS SQL Server database as shown below.
I created SQL adapter to access MS SQL Server database and it works successfully from workspace when I select adapter -> Run As -> Invoke Adapter procedure. But it does not work from my challaengerHandler.js and throws the exception. I already stored the sqljdbc4.jar file into project's server/lib folder.
Here is the contents from adapter.xml
<displayName>LoanInfoMSSQLAdapter</displayName>
<description>LoanInfoMSSQLAdapter</description>
<connectivity>
<connectionPolicy xsi:type="sql:SQLConnectionPolicy">
<!-- Example for using a JNDI data source, replace with actual data source name -->
<!-- <dataSourceJNDIName>java:/data-source-jndi-name</dataSourceJNDIName> -->
<!-- Example for using MySQL connector, do not forget to put the MySQL connector library in the project's lib folder -->
<dataSourceDefinition>
<driverClass>com.microsoft.sqlserver.jdbc.SQLServerDriver</driverClass>
<url>jdbc:sqlserver://9.22.93.21:1433;database=CustDB</url>
<user>lbps</user>
<password>lbps</password>
</dataSourceDefinition>
</connectionPolicy>
<loadConstraints maxConcurrentConnectionsPerNode="5" />
</connectivity>
<!-- Replace this with appropriate procedures -->
<procedure name="getLoanInfoFromDB"/>
Here is the contents from adapter-impl.js
var getLoanInfoStatement = WL.Server.createSQLStatement(
"SELECT account_id, pin, borr_ssn " +
"FROM vw_wcc_cust " +
"WHERE vw_wcc_cust.account_id = ? AND pin = ?;"
);
function getLoanInfoFromDB(loan, pin) {
return WL.Server.invokeSQLStatement({
preparedStatement : getLoanInfoStatement,
parameters : [loan, pin]
});
}
Here is the contents Challangerhandler.js
$("#AuthSubmitButton").bind('click', function () {
WL.Logger.debug("SUBMIT button clicked...");
var loan = $("#AuthLoan").val();
var pin = $("#AuthPin").val();
WL.Logger.debug("AuthLoan = " + loan);
WL.Logger.debug("AuthPin = " + pin);
WL.Logger.debug("Invoking WL.Client.connect() function to check for connectivity...");
var connectOptions = {
onSuccess : function() {
WL.Logger.debug("Device is connected to WL server");
var invocationData = {
adapter : "SetSnapshotAuthAdapter",
procedure : "submitAuthentication",
parameters : [ loan, pin ]
};
SetSnapshotAuthRealmChallengeHandler.submitAdapterAuthentication(invocationData, {});
},
onFailure: function() {
WL.Logger.debug("Device is NOT connected to WL server");
alert("Worklight Server Unavailable. Try your request later-001");
}
};
WL.Client.connect(connectOptions);
});
Here is the contents of submitAuthentication () function for SIngle Step Authentication Adapeter's js file
function submitAuthentication(loan, pin){
WL.Logger.info("Inside submitAuthentication");
WL.Logger.info("Loan = " + loan);
WL.Logger.info("Pin = " + pin);
var loanInfos = WL.Server.invokeSQLStatement({
preparedStatement : getLoanInfoStatement,
parameters : [loan, pin]
});
var username = "seterus";
// if (username === "seterus" && password === "seterus"){
if (loanInfos) {
var userIdentity = {
userId: username,
displayName: username,
attributes: {
foo: "bar",
loan: loan,
pin: pin,
isSuccessful: loanInfos.isSuccessful
}
};
WL.Logger.info("Loan from userIdentity = " + userIdentity.attributes.loan);
WL.Logger.info("Pin from userIdentity = " + userIdentity.attributes.pin);
WL.Server.setActiveUser("SetSnapshotAuthRealm", userIdentity);
WL.Logger.info("Returning authRequired as FALSE to display loan info...");
return {
authRequired: false
};
}
return onAuthRequired(null, "Invalid login credentials");
}
Upon entering the loan# and pin and then slicking Submit button, I get the following exception in the eclipse console view:
[ERROR ] FWLSE0099E: An error occurred while invoking procedure [project SeterusSnapShotJQ]SetSnapshotAuthAdapter/SqlStatementFWLSE0100E: parameters: [project SeterusSnapShotJQ]{
"arr": [
{
"parameters": [
"1111111",
"3333"
],
"preparedStatement": "SELECT account_id, pin, borr_ssn FROM vw_wcc_cust WHERE vw_wcc_cust.account_id = ? AND pin = ?;"
}
]
}
com.worklight.adapters.http.HttpClientContext cannot be cast to java.sql.Connection
FWLSE0101E: Caused by: [project SeterusSnapShotJQ]nulljava.lang.ClassCastException: com.worklight.adapters.http.HttpClientContext cannot be cast to java.sql.Connection
at com.worklight.adapters.sql.SQLQuery.invoke(SQLQuery.java:71)
at com.worklight.integration.model.ProcedureInvoker.invokeProcedure(ProcedureInvoker.java:57)
at com.worklight.integration.model.Procedure.invoke(Procedure.java:166)
at com.worklight.integration.model.InvocationContext.call(InvocationContext.java:169)
at com.worklight.integration.model.InvocationContext.call(InvocationContext.java:38)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at com.worklight.integration.model.InvocationContext$DirectExecutorService.execute(InvocationContext.java:284)
at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
at com.worklight.integration.model.InvocationContext.submit(InvocationContext.java:138)
at com.worklight.integration.model.InvocationContextManager.submitInvocation(InvocationContextManager.java:58)
at com.worklight.integration.services.impl.DataAccessServiceImpl.callProcedure(DataAccessServiceImpl.java:484)
at com.worklight.integration.services.impl.DataAccessServiceImpl.access$100(DataAccessServiceImpl.java:56)
at com.worklight.integration.services.impl.DataAccessServiceImpl$4.execute(DataAccessServiceImpl.java:387)
at com.worklight.core.auth.impl.AuthenticationServiceBean.accessResource(AuthenticationServiceBean.java:76)
at com.worklight.integration.services.impl.DataAccessServiceImpl.invokeProcedureInternal(DataAccessServiceImpl.java:384)
at com.worklight.integration.services.impl.DataAccessServiceImpl.invokeDynamicProcedure(DataAccessServiceImpl.java:443)
at com.worklight.integration.services.impl.DataAccessServiceImpl.invokeDynamicProcedure(DataAccessServiceImpl.java:427)
at com.worklight.integration.js.JavaScriptIntegrationLibraryImplementation.invokeDynamicProcedure(JavaScriptIntegrationLibraryImplementation.java:125)
at sun.reflect.GeneratedMethodAccessor206.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.mozilla.javascript.MemberBox.invoke(MemberBox.java:126)
at org.mozilla.javascript.NativeJavaMethod.call(NativeJavaMethod.java:225)
at org.mozilla.javascript.optimizer.OptRuntime.callN(OptRuntime.java:52)
at org.mozilla.javascript.gen._integration_js_16._c_anonymous_19(/integration.js:226)
at org.mozilla.javascript.gen._integration_js_16.call(/integration.js)
at org.mozilla.javascript.optimizer.OptRuntime.call1(OptRuntime.java:32)
at org.mozilla.javascript.gen.C_3A_5CUsers_5CIBM_ADMIN_5CDesktop_5CworkspaceJQuery_5CSeterusSnapShotJQ_5Cadapters_5CSetSnapshotAuthAdapter_SetSnapshotAuthAdapter_impl_js_78._c_submitAuthentication_2(C%3A%5CUsers%5CIBM_ADMIN%5CDesktop%5CworkspaceJQuery%5CSeterusSnapShotJQ%5Cadapters%5CSetSnapshotAuthAdapter/SetSnapshotAuthAdapter-impl.js:57)
at org.mozilla.javascript.gen.C_3A_5CUsers_5CIBM_ADMIN_5CDesktop_5CworkspaceJQuery_5CSeterusSnapShotJQ_5Cadapters_5CSetSnapshotAuthAdapter_SetSnapshotAuthAdapter_impl_js_78.call(C%3A%5CUsers%5CIBM_ADMIN%5CDesktop%5CworkspaceJQuery%5CSeterusSnapShotJQ%5Cadapters%5CSetSnapshotAuthAdapter/SetSnapshotAuthAdapter-impl.js)
at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:394)
at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3091)
at org.mozilla.javascript.gen.C_3A_5CUsers_5CIBM_ADMIN_5CDesktop_5CworkspaceJQuery_5CSeterusSnapShotJQ_5Cadapters_5CSetSnapshotAuthAdapter_SetSnapshotAuthAdapter_impl_js_78.call(C%3A%5CUsers%5CIBM_ADMIN%5CDesktop%5CworkspaceJQuery%5CSeterusSnapShotJQ%5Cadapters%5CSetSnapshotAuthAdapter/SetSnapshotAuthAdapter-impl.js)
at com.worklight.integration.js.JavaScriptManager.callFunction(JavaScriptManager.java:240)
at com.worklight.integration.js.JavaScriptManager.invokeFunction(JavaScriptManager.java:214)
at com.worklight.integration.js.JavaScriptManager.invokeFunction(JavaScriptManager.java:194)
at com.worklight.integration.services.impl.AdapterManagerImpl.invokeFunction(AdapterManagerImpl.java:104)
at com.worklight.integration.js.JavaScriptProcedureInvoker.invoke(JavaScriptProcedureInvoker.java:42)
at com.worklight.integration.model.ProcedureInvoker.invokeProcedure(ProcedureInvoker.java:57)
at com.worklight.integration.model.Procedure.invoke(Procedure.java:166)
at com.worklight.integration.model.InvocationContext.call(InvocationContext.java:169)
at com.worklight.integration.model.InvocationContext.call(InvocationContext.java:38)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at com.worklight.server.util.ProjectLocal$1RunnableWrapper.run(ProjectLocal.java:267)
at java.lang.Thread.run(Unknown Source)
com.worklight.common.log.filters.ErrorFilter
I tried to follow the SQL Adapter example along with Single step auth adapter example. The code works fine with Single step auth adapter and hard coded data but it is giving me this problem as soon as I tried to include SQL adapter for hard coded data.
There are some postings which had same issue and I tried to follow there code in implementing this, but I am still not getting the desired the results.
Please let me know if you need anything more. Please forgive me if the code snippets don't come out good in the posting as I am new with Stack Overflow site.
Thanks,
Shailesh
I successfully connected to database and executed the query in the test application. I used the sample exercise for "Advanced adapter usage and mashup" section of Worklight InfoCenter. I used the same style in my actual app and I was successful in retrieving the records from Microsft SQL Server. Thanks for your suggestion. - Shailesh

How to solve jms activemq error?

I have downloaded sample work light project from getting started tutorials that implements JMS adapter with activeMQ Messsage broker. I got the following error.
[ERROR ] FWLSE0005W: JMS connection exception received:
org.apache.activemq.ActiveMQConnectionFactory cannot be cast to
javax.jms.ConnectionFactory. Closing the connection. [project Adapters].
I don't know what jars needed to add in this project.I have added activemq-all-5.3.0
only.
JMSAdapter.xml:
<displayName>JMSAdapter</displayName>
<description>JMSAdapter</description>
<connectivity>
<connectionPolicy xsi:type="jms:JMSConnectionPolicyType">
<!-- uncomment this if you want to use an external JNDI repository
<namingConnection url="MY_JNDI_URL"
initialContextFactory="providers_intial_context_factory_class_name"
user="JNDIUserName"
password="JNDIPassword"/>
-->
<namingConnection url="tcp:/9.148.225.170:61616"
initialContextFactory="org.apache.activemq.jndi.ActiveMQInitialContextFactory"
user="admin"
password="admin"/>
<jmsConnection
connectionFactory="ConnectionFactory"
user="admin"
password="admin"
/>
</connectionPolicy>
<loadConstraints maxConcurrentConnectionsPerNode="10"/>
</connectivity>
<procedure name="writeMessage"/>
<procedure name="readMessage"/>
<procedure name="readAllMessages"/>
</wl:adapter>
JMSAdapter-impl.xml:
// The name of the JMS Administered object that you have already placed in the
repository of your choice
var DESTINATION = "dynamicQueues/IBMWorklight";
/**
* Write a message to the destination with a user defined property.
* #param messagebody
*
* #returns the result which includes the MessageID
*/
function writeMessage(messagebody) {
var inputData = {
destination: "dynamicQueues/IBMWorklight",
message:{
body: messagebody,
properties:{
MY_USER_PROPERTY:123456
}
}
};
return WL.Server.writeJMSMessage(inputData);
}
/**
* Read a message from the destination.
*
* #returns the message
*/
function readMessage() {
var result = WL.Server.readSingleJMSMessage({
destination: "dynamicQueues/IBMWorklight",
timeout: 60
});
/*var inputData = {
destination: "dynamicQueues/IBMWorklight",
timeout: 60
};
return WL.Server.readSingleJMSMessage(inputData);*/
return result;
}
/**
*
* Write some messages to a queue then read all available messages from the
destination.
* #return - the read messages.
*/
function readAllMessages() {
// As this is a test module write some test messages by calling the above
function.
writeMessage();
writeMessage();
writeMessage();
var inputData = {
destination: DESTINATION,
timeout: 60
};
// Now call the JMSAdapter function to read all the messages that we just wrote
return WL.Server.readAllJMSMessages(inputData);
}
The jar files that need to be added to your project in case you are using ActiveMQ are :
activemq-client... (the rest of the name depends on your activeMQ version)
geronimo-j2ee... (the rest of the name depends on your activeMQ version)

IBM Worklight Adapters and OAuth -- header values in adapter

I'm currently working on an adapter call that takes an OAuth token in the Authorization header. The request works just fine in a FireFox RestClient AND an xhr get... but is failing from the Worklight adapter with an error saying the user needs to login. Which is the same error that the user would see if they didn't pass in the authorization header.
wl adapter:
function getFriends(accessToken) {
var authtok = 'Bearer ' + accessToken;
var input = {
method : 'get',
headers: {Authorization: authtok},
path : '/connections/opensocial/rest/people/#me/#self'
};
return WL.Server.invokeHttp(input);
}
Anyone else seeing an error like this? Is there a way to trace the worklight adapter invocation to inspect that the headers sent into the request are as expected?
Looks like your server was also expecting the hostname in the headers. Try changing your input to this:
var input = {
method : 'get',
returnedContentType : 'json',
path : '/connections/opensocial/rest/people/#me/#self',
headers: {
'Authorization': authtok,
Host: "HOSTNAME THAT IS USED IN THE .XML FILE"
}
};
So if your adapter's xml file looks like this:
<connectionPolicy xsi:type="http:HTTPConnectionPolicyType">
<protocol>https</protocol>
<domain>jeremy.server.whatever.com</domain>
<port>443</port>
-->
</connectionPolicy>
Then your headers should look like this:
headers: {
'Authorization': authtok,
Host: "jeremy.server.whatever.com"
}