here is my problem. I can't seem to use gatling for aggregation. I have this error: "invalid basic authentication header encoding" HTTP code 401.
here is my simplified code:
package app
import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._
import java.util.Base64
class Aggregation extends Simulation {
val httpConf = http
.baseUrl("http://localhost:9200")
.acceptHeader("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
val body = StringBody("""{
"aggs": {
"genres": {
"terms": { "field": "genre" }
}
}
}""".stripMargin.replaceAll("\n", " "))
// surely here there is an error but I don't know why
val auth = Base64.getEncoder.encodeToString("elastic:changeme".getBytes())
val scn = scenario("Test aggregation")
.exec(
http("Aggregation")
.get("/_search")
.header("Authorization", "Basic " + auth)
.body(body).asJson
.check(status.is(200)))
var users: Integer = 1
var duration: Integer = 1
setUp(
scn.inject(rampUsers(users) during (duration seconds))
).protocols(httpConf)
}
If your auth scheme is really Basic, you should use Gatling's built-in support instead of crafting the header yourself, see https://gatling.io/docs/gatling/reference/current/http/request/#authentication
http("Aggregation")
.get("/_search")
.basicAuth("elastic", "changeme")
.body(body).asJson
.check(status.is(200)))
I try to navigate from list page to detail page, when i tried with the below code. I got error stating that field error. For that I've tried with adding a empty Slug field in models, it shows an page not found error.
#urls.py
from django.urls import path
from .views import (TaskListView,TaskDetailView)
app_name = 'Tasks'
urlpatterns = [
path('', TaskListView.as_view(), name='list'),
path('<slug:slug>/', TaskDetailView.as_view(), name='detail'),
]
#views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from django.views.generic import ListView, DetailView, View
from .models import Taskmanager
def home(request):
return render(request, 'home.html')
class TaskListView(ListView):
template_name = 'Tasks.html'
model = Taskmanager
context_object_name = 'data'
class TaskDetailView(DetailView):
template_name = 'detail.html'
model = Taskmanager
context_object_name = 'data'
#models.py
from django.db import models
from django.urls import reverse
# Create your models here.
week_number = (("week01", "week01"),
("week02", "week02"),
("week03", "week03"),
("week04", "week04"),
("week05", "week05"),
("week06", "week06"),
("week07", "week07"),
("week08", "week08"),
("week09", "week09"),
("week10", "week10"),
("week11", "week11"),
("week12", "week12"),
("week13", "week13"),
("week14", "week14"),
("week15", "week15"),
("week16", "week16"),
("week17", "week17"),
("week18", "week18"),
("week19", "week19"),
("week20", "week20"),
("week21", "week21"),
("week22", "week22"),
("week23", "week23"),
("week24", "week24"),
("week25", "week25"),
("week26", "week26"),
("week27", "week27"),
("week28", "week28"),
("week29", "week29"),
("week30", "week30"),
("week31", "week31"),
("week32", "week32"),
("week33", "week33"),
("week34", "week34"),
("week35", "week35"),
("week36", "week36"),
("week37", "week37"),
("week38", "week38"),
("week39", "week39"),
("week40", "week40"),
("week41", "week41"),
("week42", "week42"),
("week43", "week43"),
("week44", "week44"),
("week45", "week45"),
("week46", "week46"),
("week47", "week47"),
("week48", "week48"),
("week49", "week49"),
("week50", "week50"),
("week51", "week51"),
("week52", "week52"),
("week53", "week53"),
)
class Taskmanager(models.Model):
CurrentSprint = models.CharField(max_length=10, default="week01",
choices=week_number)
todaydate = models.DateField()
taskname = models.SlugField(max_length=200)
testrun = models.URLField(max_length=300)
comments = models.CharField(max_length=300)
assignedto = models.EmailField(max_length=70)
def __str__(self):
return self.taskname
def get_absolute_url(self):
return reverse('Tasks:detail', kwargs={'slug': self.taskname})
#Tasks.html
<a href="{% url 'Tasks:detail' slug='detail'%}"> {{Taskmanager.todaydate}}
</a>
I need an output when I click the link, it needs to navigate to the details page where the details of the task needs to be displayed.
try adding this
#views.py
class TaskDetailView(DetailView):
...
def get_object(self):
instance = get_object_or_404(Taskmanager, slug=self.kwargs['slug'])
return instance
#models.py
django.db.models.signals import pre_save
class Taskmanager(models.Model):
...
taskname = models.CharField(max_length=200)
slug = models.SlugField(max_length=100)
...
def pre_save_Taskmanager_receiver(instance, *args, **kwargs):
if not instance.slug:
instance.slug = instance.taskname
pre_save.connect(pre_save_Taskmanager_receiver, sender= Taskmanager)
# task.html
{{ data.todaydate }}
I have a simple setup:
routes:
# creates new ticket
PUT /projects/:projectId/tickets controllers.ProjectsController.add(projectId)
App Controller code looks like:
case class TicketData(ticketId: Option[String], ticketName: String, ticketDescription: String)
val addUpdateForm = Form(
mapping(
"ticketId" -> optional(text),
"ticketName" -> text,
"ticketDescription" -> text
)(TicketData.apply)(TicketData.unapply))
def add(projectId: String) = Action { implicit request =>
val ticket = addUpdateForm.bindFromRequest.bindFromRequest.get
Ok(Json.toJson(cassandraClient.addTicket(projectId, ticket.ticketName, ticket.ticketDescription)))
}
When I try to send a req from postman (tried several combos, I have no oauth) I just always get 403 ... there is nothing really useful in logs:
[debug] i.n.u.i.JavassistTypeParameterMatcherGenerator - Generated: io.netty.util.internal.__matchers__.io.netty.channel.ChannelMatcher
[debug] i.n.u.i.JavassistTypeParameterMatcherGenerator - Generated: io.netty.util.internal.__matchers__.io.netty.handler.codec.http.HttpObjectMatcher
[debug] i.n.u.i.JavassistTypeParameterMatcherGenerator - Generated: io.netty.util.internal.__matchers__.io.netty.handler.codec.http.HttpContentMatcher
I'm missing something here and have no idea what to be honest.
It looks like you have a problem with the CORS configuration.
To verify it just allow every request (in application.conf):
play.filters.cors {
pathPrefixes = ["/"]
allowedOrigins = null
allowedHttpMethods = ["GET", "POST", "PUT", "DELETE"]
allowedHttpHeaders = null
}
This post looks very similar:
Trouble-shooting CORS in Play Framework 2.4.x
How to do HTTP PUT/POSTs from inside Groovy code without having to import any libraries (if at all possible)? I know there is a simple getText() methods that Groovy adds to the java.net.URL class, that could be used without adding any dependencies. Is there a way to do Rest PUT in the same fashion?
You can do it with HttpURLConnection in a similar way as you would do it with java:
def url = new URL('http://your_rest_endpoint')
def http = url.openConnection()
http.setDoOutput(true)
http.setRequestMethod('PUT')
http.setRequestProperty('User-agent', 'groovy script')
def out = new OutputStreamWriter(http.outputStream)
out.write('data')
out.close()
http.inputStream // read server response from it
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
url = "http://restapi3.apiary.io"
#Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient(url)
def jsonObj = new JsonSlurper().parseText('{ "title": "Pick-up posters from Post-Office" }')
def response = client.put(path: "/notes/id",
contentType: JSON,
body: jsonObj,
headers: [Accept: 'application/json'])
println("Status: " + response.status)
if (response.data) {
println("Content Type: " + response.contentType)
println("Headers: " + response.getAllHeaders())
println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Is application.conf already loaded when the code in Global.scala is executed? I'm asking because I've tried to read some configuration items from Global.scala and I always get None. Is there any workaround?
In Java it's available beforeStart(Application app) already
public class Global extends GlobalSettings {
public void beforeStart(Application app) {
String secret = Play.application().configuration().getString("application.secret");
play.Logger.debug("Before start secret is: " + secret);
super.beforeStart(app);
}
}
As it's required to i.e. configuring DB connection, most probably Scala works the same way (can't check)
Here below is how to read the configuration just after it has been loaded but before the application actually starts:
import play.api.{Configuration, Mode}
import play.api.GlobalSettings
import java.io.File
import utils.apidocs.InfoHelper
object Global extends GlobalSettings {
override def onLoadConfig(
config: Configuration,
path: File, classloader:
ClassLoader,
mode: Mode.Mode): Configuration = {
InfoHelper.loadApiInfo(config)
config
}
}
And here below, just for your info, is the source of InfoHelper.loadApiInfo – it just loads API info for Swagger UI:
package utils.apidocs
import play.api.Configuration
import com.wordnik.swagger.config._
import com.wordnik.swagger.model._
object InfoHelper {
def loadApiInfo(config: Configuration) = {
config.getString("application.name").map { appName =>
config.getString("application.domain").map { appDomain =>
config.getString("application.emails.apiteam").map { contact =>
val apiInfo = ApiInfo(
title = s"$appName API",
description = s"""
Fantastic application that makes you smile. You can find our
more about $appName at $appDomain.
""",
termsOfServiceUrl = s"//$appDomain/terms",
contact = contact,
license = s"$appName Subscription and Services Agreement",
licenseUrl = s"//$appDomain/license"
)
ConfigFactory.config.info = Some(apiInfo)
}}}
}
}
I hope it helps.