Publishing messages to ActiveMQ using Gatling - scala

I have been using Gatling to publish messages to ActiveMq server. I get "java.lang.SecurityException: Invalid username: null or empty" tho I use valid username and password. Here is my test code and the exception were thrown. Any inputs on how to fix this will be of help.
import io.gatling.core.Predef.Simulation
import io.gatling.core.Predef._
import io.gatling.jms.Predef._
import io.gatling.core.config.Credentials
import org.apache.activemq.ActiveMQConnectionFactory
import org.apache.activemq.jndi.ActiveMQInitialContextFactory
import javax.jms._
class WebProducer extends Simulation{
val jmsUsername:String="userName"
val jmsPwd:String="Password"
val jmsConfig = jms
.connectionFactoryName("ConnectionFactory")
.url("ssl://message01-dev.platform.net:61617")
.credentials(jmsUsername,jmsPwd)
.disableAnonymousConnect
.contextFactory(classOf[org.apache.activemq.jndi.ActiveMQInitialContextFactory].getName)
.listenerCount(1)
.usePersistentDeliveryMode
.receiveTimeout(6000)
val scn = scenario("JMS DSL test").repeat(1) {
exec(jms("req reply testing").
reqreply
.queue("YourJMSQueueName")
.replyQueue("YourJMSQueueName")
.textMessage("payload To be posted")
.property("company_id", "1234598776665")
.property("event_type","EntityCreate")
.property("event_target_entity_type","Account")
)
}
setUp(scn.inject(atOnceUsers(1)))
.protocols(jmsConfig)
}
Following is the exception was thrown :
java.lang.SecurityException: Invalid username: null or empty

Ok, I got this working adding two things :
- .disableAnonymousConnect after .credentials(jmsUsername,jmsPwd)
- .replyQueue(jmsQueueName) after .queue(jmsQueueName)
I edited the above code to reflect the same.
Happy Gatling !

Related

Unsupported authentication token, scheme='none' only allowed when auth is disabled: { scheme='none' } - Neo4j Authentication Error

I am trying to connect to Neo4j from Spark using neo4j-spark-connector. I am facing an authentication issue when I try to connect to the Neo4j org.neo4j.driver.v1.exceptions.AuthenticationException: Unsupported authentication token, scheme='none' only allowed when auth is disabled: { scheme='none' }
I have checked and the credentials I am passing are correct. Not sure why is it failing.
import org.neo4j.spark._
import org.apache.spark._
import org.graphframes._
import org.apache.spark.sql.SparkSession
import org.neo4j.driver.v1.GraphDatabase
import org.neo4j.driver.v1.AuthTokens
val config = new SparkConf()
config.set(Neo4jConfig.prefix + "url", "bolt://localhost")
config.set(Neo4jConfig.prefix + "user", "neo4j")
config.set(Neo4jConfig.prefix + "password", "root")
val sparkSession :SparkSession = SparkSession.builder.config(config).getOrCreate()
val neo = Neo4j(sparkSession.sparkContext)
val graphFrame = neo.pattern(("Person","id"),("KNOWS","null"), ("Employee","id")).partitions(3).rows(1000).loadGraphFrame
println("**********Graphframe Vertices Count************")
graphFrame.vertices.count
println("**********Graphframe Edges Count************")
graphFrame.edges.count
val pageRankFrame = graphFrame.pageRank.maxIter(5).run()
val ranked = pageRankFrame.vertices
ranked.printSchema()
val top3 = ranked.orderBy(ranked.col("pagerank").desc).take(3)
Can someone please have a look and let me know the reason for the same?
It might be a configuration issue with your neo4j.conf file. Is this line commented out:
dbms.security.auth_enabled=false
I had a similar problem, creating the following spring beans fixed the issue.
#Bean
public org.neo4j.ogm.config.Configuration getConfiguration() {
return new org.neo4j.ogm.config.Configuration.Builder()
.credentials("neo4j", "secret")
.uri("bolt://localhost:7687").build();
}
#Bean
public SessionFactory sessionFactory(org.neo4j.ogm.config.Configuration configuration) {
return new SessionFactory(configuration,
"<your base package>");
}

How to save a header from an http response

i'm trying to build a scenario where the user log in first, then do something before logging out.
The problem is that i want to save the header response from the log in request to use it in my next request.
When a user log in, he gets an header response containing the Authorization header, with the token.
Here is my code, but it's not working :
val LoggingTest = scenario("Basic Scenario")
.exec(http("Logging")
.post("/login")
.body(
StringBody("""{"name" : "test",
"password" : "test"}""")
)
.check(header("Authorization").saveAs("token"),status.is(200))
).pause(15)
.exec(http("check")
.get("/sayhi")
.header("Authorization",s"${token}")
.check(status.is(200))
).pause(15)
How can i fix it please ?
This is how you can do it:
import io.gatling.core.Predef._
import io.gatling.http.Predef._
val LoggingTest: ScenarioBuilder = scenario("Basic Scenario")
.exec(http("Logging")
.post("/login")
.body(
StringBody("""{"name" : "test",
"password" : "test"}""")
)
.check(header("Authorization").saveAs("token"),status.is(200))
).pause(15)
.exec(
http("check")
.get("/sayhi")
.header("Authorization", session => session("token").validate[String])
.check(status.is(200))
).pause(15)
It's not s"${token}" but "${token}" without the s.
Sadly, IntelliJ automatically adds this s because it thinks you want to use Scala's String interpolation while you want to use Gatling Expression Language.

How to publish data to using MQTT

I used this docker image to install Mosquitto MQTT.
Now it's running and showing the following message in the terminal:
1515680808: mosquitto version 1.4.14 (build date Mon, 10 Jul 2017 23:48:43 +0100) starting
1515680808: Config loaded from /mqtt/config/mosquitto.conf.
1515680808: Opening websockets listen socket on port 9001.
1515680808: Opening ipv4 listen socket on port 1883.
1515680808: Opening ipv6 listen socket on port 1883.
Then I created a simple Maven project:
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming-mqtt_2.11</artifactId>
<version>1.6.3</version>
</dependency>
I tried to publish some data to a topic using the code shown below. I point to localhost:1883 as the MqttBrokerUrl and a topic test. However, I get this error:
Exception in thread "main" java.lang.NullPointerException at
org.eclipse.paho.client.mqttv3.MqttConnectOptions.validateURI(MqttConnectOptions.java:457)
at
org.eclipse.paho.client.mqttv3.MqttAsyncClient.(MqttAsyncClient.java:273)
at
org.eclipse.paho.client.mqttv3.MqttAsyncClient.(MqttAsyncClient.java:167)
at
org.eclipse.paho.client.mqttv3.MqttClient.(MqttClient.java:224)
at org.test.MQTTPublisher$.main(MQTTPublisher.scala:37) at
org.test.MQTTPublisher.main(MQTTPublisher.scala)
Code:
package org.test
import org.apache.log4j.{Level, Logger}
import org.eclipse.paho.client.mqttv3._
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
import org.apache.spark.storage.StorageLevel
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.mqtt._
import org.apache.spark.SparkConf
object MQTTPublisher {
def main(args: Array[String]) {
if (args.length < 2) {
System.err.println("Usage: MQTTPublisher <MqttBrokerUrl> <topic>")
System.exit(1)
}
// Set logging level if log4j not configured (override by adding log4j.properties to classpath)
if (!Logger.getRootLogger.getAllAppenders.hasMoreElements) {
Logger.getRootLogger.setLevel(Level.WARN)
}
val Seq(brokerUrl, topic) = args.toSeq
var client: MqttClient = null
try {
val persistence = new MemoryPersistence()
client = new MqttClient("localhost:1883", MqttClient.generateClientId(), persistence)
client.connect()
val msgtopic = client.getTopic(topic)
val msgContent = "test test test"
val message = new MqttMessage(msgContent.getBytes("utf-8"))
while (true) {
try {
msgtopic.publish(message)
println(s"Published data. topic: ${msgtopic.getName()}; Message: $message")
} catch {
case e: MqttException if e.getReasonCode == MqttException.REASON_CODE_MAX_INFLIGHT =>
Thread.sleep(10)
println("Queue is full, wait for to consume data from the message queue")
}
}
} catch {
case e: MqttException => println("Exception Caught: " + e)
} finally {
if (client != null) {
client.disconnect()
}
}
}
}
The MqttClient() constructor takes a URI.
What you have provided is just a hostname and port number (localhost:1883), it's missing a protocol section which should be tcp:// (which is what the library is expecting and getting null back. This really should throw a better error.)
You need to change the line to be
client = new MqttClient("tcp://localhost:1883", MqttClient.generateClientId(), persistence);
I think you are giving the wrong Url i.e you are not specifying the protocol over which it has to connect that is my hunch.
Try changing the url to :
tcp://localhost:1883
I think it would work ! Rest all seems fine to me.
For a working example See this : https://github.com/shiv4nsh/scala-mqtt-client-rasberrypi-starter-kit/blob/master/src/main/scala/com/knoldus/MQTTPublisher.scala

Apple store receipt validation through Twisted server

I'm trying to validate a transaction receipt from an inApp purchase with the Apple store server from my Twisted server. I have sent the (SKPaymentTransaction *)transaction.transactionReceipt from my app to my server.
But now, sending the JSON object to the Apple server, I keep getting an unhandled error in Deferred from my Agent.request(). I suspect this is because I'm not listening on port 443 for response from Apple store, but I don't want my app to communicate with my Twisted server on port 443 also. Here is my code:
from twisted.application import internet, service
from twisted.internet import protocol, reactor
from zope.interface import implements
from twisted.web.iweb import IBodyProducer
from twisted.internet import defer
from twisted.web.client import Agent
from twisted.web.http_headers import Headers
import json
import base64
class StringProducer(object):
implements(IBodyProducer)
def __init__(self, body):
self.body = body
self.length = len(body)
def startProducing(self, consumer):
consumer.write(self.body)
return succeed(None)
def pauseProducing(self):
pass
def stopProducing(self):
pass
def printResponse(response):
print response # just testing to see what I have
def httpRequest(url, values, headers={}, method='POST'):
agent = Agent(reactor)
d = agent.request(method,
url,
Headers(headers),
StringProducer(values)
)
d.addCallback(printResponse)
class storeServer(protocol.Protocol):
def dataReceived(self, data):
receiptBase64 = base64.standard_b64encode(data)
jsonReceipt = json.dumps({'receipt-data':receiptBase64})
print jsonReceipt # verified that my data is correct
d = httpRequest(
"https://buy.itunes.apple.com/verifyReceipt",
jsonReceipt,
{'Content-Type': ['application/x-www-form-urlencoded']}
)
factory = protocol.Factory()
factory.protocol = storeServer
tcpServer = internet.TCPServer(30000, factory)
tcpServer.setServiceParent(application)
How can I fix this error? Do I have to create another service listening on port 443? If so, how might I have the service connecting to my app communicate with the service connecting through https?
The comment style in your code sample is incorrect. Python uses # for comments, not //.
After fixing that and running the snippet through pyflakes, I see these errors:
program.py:1: 'service' imported but unused
program.py:6: 'defer' imported but unused
program.py:21: undefined name 'succeed'
program.py:48: local variable 'd' is assigned to but never used
program.py:57: undefined name 'application'
It seems likely that the undefined name on line 21 is the cause of the NameError you've encountered. NameError is how Python signals this sort of bug:
x = y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined

Scalate ResourceNotFoundException in Scalatra

I'm trying the following based on scalatra-sbt.g8:
class FooWeb extends ScalatraServlet with ScalateSupport {
beforeAll { contentType = "text/html" }
get("/") {
templateEngine.layout("/WEB-INF/scalate/templates/hello-scalate.jade")
}
}
but I'm getting the following exception (even though the file exists) - any clues?
Could not load resource: [/WEB-INF/scalate/templates/hello-scalate.jade]; are you sure it's within [null]?
org.fusesource.scalate.util.ResourceNotFoundException: Could not load resource: [/WEB-INF/scalate/templates/hello-scalate.jade]; are you sure it's within [null]?
FWIW, the innermost exception is coming from org.mortbay.jetty.handler.ContextHandler.getResource line 1142: _baseResource==null.
Got an answer from the scalatra mailing list. The problem was that I was starting the Jetty server with:
import org.mortbay.jetty.Server
import org.mortbay.jetty.servlet.{Context,ServletHolder}
val server = new Server(8080)
val root = new Context(server, "/", Context.SESSIONS)
root.addServlet(new ServletHolder(new FooWeb()), "/*")
server.start()
I needed to insert this before start():
root.setResourceBase("src/main/webapp")