securesocial 3.0 doesn't work with play framework 2.3 - playframework-2.3

1.When i upgrade my play framework from 2.2.6 to 2.3.8 and securesocial from 2.1.4 to 3.0-M3. I got the following error. How to fix it?
[error] /Work/test.scala:81: not found: value SecuredAction
[error] def findStats = SecuredAction {
2.The following line used to work but now it gets an error message:trait SecureSocial takes type parameters.How to fix this?
object ToolbarHandler extends Controller with SecureSocial with CookieLang{
3.Request needs a parameter.How to add the parameter though?
def findStats = SecuredAction {
implicit request =>

You have to use the snapshot version.
As stated here : http://securesocial.ws/guide/getting-started.html
add:
resolvers += "Sonatype OSS Snapshots" at "https://repo.typesafe.com/typesafe/snapshots/"
then add the library dependency:
"ws.securesocial" % "securesocial_2.11" % "master-SNAPSHOT"
Hope that helps.

Related

Android-JUnit5 No instrumentation registered! when getting context

I know this is "common" error but I am trying to make a JUnit5 Android Room test working.
I found out that JUnit5 does not support the instrumentation test (or google does not support JUnit 5 I should say) but I discovered that https://github.com/mannodermaus/android-junit5 is supposed to help me.
I modified my graddle to have the plugin added in my module and the classpath at the top of the project.
classpath("de.mannodermaus.gradle.plugins:android-junit5:1.7.1.1")
id("kotlin-android")
I also added the specific dependencies from it
androidTestImplementation("de.mannodermaus.junit5:android-test-core:1.2.2")
androidTestRuntimeOnly("de.mannodermaus.junit5:android-test-runner:1.2.2")
And in the android defaultConfig of my module I added
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
testInstrumentationRunnerArgument("runnerBuilder", "de.mannodermaus.junit5.AndroidJUnit5Builder")
The graddle builds fine but the issue is when I run my simple test
class DbTest
{
private lateinit var myDao : MyDao
#BeforeEach
fun init()
{
val context : Context = ApplicationProvider.getApplicationContext();
val db = Room.inMemoryDatabaseBuilder(
context,
ConfigDatabase::class.java).build()
tcdDao = db.getMyDao()
}
[...]
}
The error occurs when I get the context :
No instrumentation registered! Must run under a registering instrumentation.
I want to specify that I cannot use JUnit4.
Am I missing something ? Can I actually test my database with JUnit5 ? Or should I use another solution ?

System.InvalidOperationException: A second operation started on this context before a previous operation completed in Blazor and EFCore

I have method like the DeleteSettingAbout() after in text, where I am still getting error: "System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.".
Code of the method is:
public async Task DeleteSettingAbout(int Id)
{
SettingAbout setting = await _context.SettingsAbout.FirstOrDefaultAsync(o => o.Id == Id);
if (setting != null)
{
_context.SettingsAbout.Remove(setting);
await _context.SaveChangesAsync();
}
}
In sartup.cs I set DBContext and DBRepository as Transient:
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("AppDBConnection")),
ServiceLifetime.Transient);
services.AddTransient<IAppDbRepository, SQLAppDbRepository>();
But I am still getting this error.
How to solve this behavior? Thanks for answers.
UPDATE 2021-01-06
I tried the approach with creating the "DbContextFactory" and it solved my problem. I got inspiration from sample app https://github.com/dotnet/AspNetCore.Docs/tree/master/aspnetcore/blazor/common/samples/3.x/BlazorServerEFCoreSample (mentioned here: https://learn.microsoft.com/en-us/aspnet/core/blazor/blazor-server-ef-core?view=aspnetcore-3.1#sample-app-3x).
Now I have in my startup.cs this:
// new way suitable for Blazor - register factory and configure the options (new instance for each method call)
services.AddDbContextFactory<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("AppDBConnection")));
services.AddScoped<IAppDbRepository, SQLAppDbRepository>();
I tried the approach with creating the "DbContextFactory" (mentioned by Stephen Cleary) and it solved my problem. I got inspiration from sample app https://github.com/dotnet/AspNetCore.Docs/tree/master/aspnetcore/blazor/common/samples/3.x/BlazorServerEFCoreSample (mentioned here: https://learn.microsoft.com/en-us/aspnet/core/blazor/blazor-server-ef-core?view=aspnetcore-3.1#sample-app-3x).
Now I have in my startup.cs this:
// new way suitable for Blazor - register factory and configure the options (new instance for each method call)
services.AddDbContextFactory<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("AppDBConnection")));
services.AddScoped<IAppDbRepository, SQLAppDbRepository>();
Note: I needed to solve the problem in EF/Blazor = v3.1 (because my web-hosting does not support v5 for now)
Thank you all for answers!

EF Core 2.1 InvalidCastException on DbContext.Query<T>()

Given:
public class MyClass
{
public MyClass(ApplicationDbContext db)
{
var query = db.Query<IdentityUser>();
}
}
Using ASP.NET Core 2.1, I am getting this exception on the db.Query<IdentityUser>() call:
System.InvalidCastException: 'Unable to cast object of type 'Microsoft.EntityFrameworkCore.Internal.InternalDbSet\`1[Microsoft.AspNetCore.Identity.IdentityUser]' to type 'Microsoft.EntityFrameworkCore.DbQuery\`1[Microsoft.AspNetCore.Identity.IdentityUser]'.'
I ran into this with my own entities and reproduced it with minimal code using the canned ApplicationDbContext/IdentityUser. Is this a bug in .NET Core 2.1 or am I doing something incorrectly?
This is the source code from github for DbContext.Query<T>():
public virtual DbQuery<TQuery> Query<TQuery>()
where TQuery : class
=> (DbQuery<TQuery>)((IDbQueryCache)this)
.GetOrAddQuery(DbContextDependencies.QuerySource, typeof(TQuery));
It appears to be throwing the exception casting ((IDbQueryCache)this).GetOrAddQuery(DbContextDependencies.QuerySource, typeof(TQuery)) to (DbQuery<TQuery>)
I've opened an issue on github since this seems to be a bug from what I can tell.
Comment on my github issued had the solution:
You cannot call Query<> method for EntityTypes. You must use Set<>
method.
It might be helpful for TQuery to be more constrained than just class if that is possible.

Microsoft.EntityFrameworkCore 2.1-rc with MySql.Data.EntityFrameworkCore

I'm trying to use mysql with Microsoft.EntityFrameworkCore 2.1-rc-final and MySql.Data.EntityFrameworkCore 8.0.11 as provider. But when I'm trying to execute the mugrations command i get this exception:
System.MissingMethodException: Method not found: 'Void Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilderFactory..ctor(Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger`1, Microsoft.EntityFrameworkCore.Storage.IRelationalTypeMapper)'.
This is my IDesignTimeDbContextFactory code implementation:
public class DesignLocationFactory:IDesignTimeDbContextFactory<LocationDbContext>
{
public LocationDbContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<LocationDbContext>();
builder.UseMySQL("server=localhost;port=3306;user=***;passsword=***;database=locationdb");
return new LocationDbContext(builder.Options);
}
}
Please how can I fix this or at least some sample of how to use with another providers
Finally, with this provider Pomelo.EntityFrameworkCore.MySql version 2.1.0-rc1-final everything works perfect.
To install it execute the command:
Install-Package Pomelo.EntityFrameworkCore.MySql -Version 2.1.0-rc1-final
I can confirm that 2.1.0-rc1-final resolves this issue. Also, take note of Pomelo's case sensitivity vs Microsoft.EntityFrameworkCore.
Pomelo = UseMySql (Sql)
EntityFrameworkCore = UseMySQL (SQL)
Using Core 2.1
Id Versions
-- --------
Microsoft.AspNetCore.App {2.1.0}
Microsoft.VisualStudio.Web.CodeGeneration.Design {2.1.0}
Microsoft.EntityFrameworkCore.Tools {2.1.0}
Microsoft.NETCore.App {2.1.0}
MySql.Data.EntityFrameworkCore.Design {8.0.11}
MySql.Data.EntityFrameworkCore {8.0.11}
Pomelo.EntityFrameworkCore.MySql {2.1.0-rc1-final}

Pretty print JSON output of Spring Boot Actuator endpoints

Spring Boot Actuator provides several endpoints to monitor an application as:
/metrics
/beans
/health
...
Checking the endpoints with:
curl http://localhost:8080/metrics
results in:
{"counter.status.200.env":1,"counter.status.200.health":1,"counter.status.200.info":2,"counter.status.200.metrics":2,"gauge.response.env":5.0,"gauge.response.health":22.0,"gauge.response.info":1.0,"gauge.response.metrics":1.0,"mem":1030144,"mem.free":56118,"processors":8,"uptime":5108095,"instance.uptime":5102906,"heap.committed":1030144,"heap.init":262144,"heap.used":974031,"heap":3728384,"threads.peak":81,"threads.daemon":21,"threads":77,"classes":8854,"classes.loaded":8860,"classes.unloaded":6,"gc.ps_scavenge.count":119,"gc.ps_scavenge.time":7223,"gc.ps_marksweep.count":12,"gc.ps_marksweep.time":17573}
This is fine for machine consumption but hard to read by humans.
I'd like to format (i.e. pretty print) the JSON output of the Spring Boot Actuator endpoints to make them easier to read by operations personel.
Something like:
{
"counter.status.200.env":1,
"counter.status.200.health":1,
"counter.status.200.info":2,
"counter.status.200.metrics":2,
"gauge.response.env":5.0,
"gauge.response.health":22.0,
"gauge.response.info":1.0,
...
}
I tried setting
http.mappers.json-pretty-print=true
but this setting didn't affect the Actuator output.
Is there a configuration to enable pretty print of the Spring Boot Actuator JSON output?
UPDATE:
The official sample works for me.
It's important to follow the comments from #DaveSyer: the property to set is
http.mappers.jsonPrettyPrint=true
Investigation is still under way.
In the meantime I use the the json pretty print command line as workaround:
Install jsonpp (e.g. for OS X):
brew install jsonpp
Then pipe the curl output trough jsonpp which formats the json file on the fly:
curl http://localhost:8080/metrics | jsonpp
Results in:
{
"counter.status.200.env": 1,
"counter.status.200.health": 1,
"counter.status.200.info": 2,
"counter.status.200.metrics": 2,
...
}
As per http://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-customize-the-jackson-objectmapper, the official way to enable pretty print with Jackson in Spring Boot (1.2.2 at least) is to set the following property:
# Pretty-print JSON responses
spring.jackson.serialization.indent_output=true
For Spring Boot 1.5.1 I have in my YML file:
spring:
jackson:
serialization:
INDENT_OUTPUT: true
#BertrandRenuart answer was the closest, but by IDE did not see indent_output as correct.
The "http.mappers" property works for me but I think you might need it camel cased ("jsonPrettyPrint").
Do the following:
#Configuration
public class JacksonConfig {
#Autowired
private ObjectMapper objectMapper; //reuse the pre-configured mapper
#PostConstruct
public void setup() {
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
//whatever else you need
}
}
This works because Spring Boot uses an ObjectMapper bean to perform all the JSON related operations.
Note however that this configuration will pretty print all JSON outputs, not just the actuator related stuff.
UPDATE
The answer from #DaveSyer is obviously better! I hadn't found the HttpMapperProperties object which is used to configure Jackson. This is it's Javadoc
Actually I wanted to do the same. But then I asked: why? To debug my service better which comes with a small performance penalty.
Just use a browser extension, like this one :) to get a view like this one
With spring-boot 1.2.6, you need to use:
spring.jackson.serialization.INDENT_OUTPUT=true
From my log when using the old http.mappers.*:
http.mappers.json-pretty-print is deprecated. If you are using Jackson, spring.jackson.serialization.INDENT_OUTPUT=true should be used instead.
I use Python's commonly installed json.tool module:
curl --silent http://localhost:8080/metrics | python -mjson.tool
If you're using gson serialization with Spring, then none of the other answers will work for you. You'll have to use this configuration option:
spring.gson.pretty-printing=true
Confirmed working with Spring Boot as of version 2.0.3.Release.
I use jq for pretty printing JSON as well as filtering it. It's basically sed for JSON. On the mac, it can be installed with homebrew. (https://stedolan.github.io/jq/)
curl http://localhost:8080/metrics | jq
Instead of using curl I like to use httpie as a http command line client:
http http://localhost:8080/metrics
This would already format and syntax highlight the json response without having to pipe the output into another command. Also the command syntax is a bit more human friendly.
Spring Boot Actuator uses its own isolated ObjectMapper instance by default in which indent-output is disabled. To enable pretty-print of actuator output, you must set the following properties:
spring.jackson.serialization.indent-output=true
management.endpoints.jackson.isolated-object-mapper=false
Unfortunately, the application property
spring.jackson.serialization.INDENT_OUTPUT
did not work for me (spring boot versions 1.2.6 to 1.4.0.RELEASE). Instead, in my extension of WebMvcConfigurerAdapter, I've overridden configureMessageConverters() and added my own Jackson2ObjectMapperBuilder:
#Configuration
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
...
private MappingJackson2HttpMessageConverter jacksonMessageConverter() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
.featuresToDisable(SerializationFeature.FAIL_ON_EMPTY_BEANS,
SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS)
.featuresToEnable(SerializationFeature.INDENT_OUTPUT).modulesToInstall(hibernate4Module());
// can use this instead of featuresToEnable(...)
builder.indentOutput(true);
return new MappingJackson2HttpMessageConverter(builder.build());
}
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(jacksonMessageConverter());
super.configureMessageConverters(converters);
}
...
}
That seem to do the trick for me on Spring boot 1.4.0.RELEASE and my actuator output is now pretty printed (along with every other json output)
Here is my Emacs function to retrieve Spring Actuator Json from endpoints:
(defvar my/spring-actuator-server-history nil)
(defvar my/spring-actuator-last-server "http://localhost:8080")
(defvar my/spring-actuator-path-history nil)
(defvar my/spring-actuator-path-completion
'("actuator" "auditevents" "autoconfig" "beans" "configprops" "dump" "env" "flyway" "health" "heapdump"
"info" "jolokia" "liquibase" "logfile" "loggers" "mappings" "metrics" "shutdown" "trace")))
(defun my/spring-actuator (server path)
(interactive (list (read-string "Server: " my/spring-actuator-last-server 'my/spring-actuator-server-history)
(completing-read "Path: " my/spring-actuator-path-completion nil nil "" 'my/spring-actuator-path-history)))
(setq my/spring-actuator-last-server server)
(let ( (bufname (format "actuator: %s" path)) )
(when (get-buffer bufname)
(kill-buffer bufname))
(switch-to-buffer (url-retrieve-synchronously (format "%s/%s" server path)))
(rename-buffer bufname)
(goto-char (point-min))
(re-search-forward "^$" nil 'move)
(forward-char)
(delete-region (point-min) (point))
(json-pretty-print-buffer)
(json-mode) ))
If you don't like dependency on external json-mode library replace it with js-mode.
In case somebody with Spring Boot 2 (2.1.1 in my case) stumbles over this question as I did: We faced the same problem, and none of the answers helped for 2.1.1.
So what we did was to replace the existing endpoint (health in our case) with a new one. I described it at the end of this answer. And yes, this limits our solution to this single endpoint, but on the other hand it has the advantage of being able to format the output in any way you want - including pretty print JSON, but also output styled HTML if requested (by a service technician in a browser in our case). Note the produces attribute of #ReadOperation to achieve that.
This is the latest as of 12/27/2022. The below works.
-For application.yml config.
spring:
jackson:
serialization:
indent-output: true
But the above config won't work, if you implement WebMvcConfigurer class. In that case, override like below to make it work.
#Override
public void extendMessageConverters( List<HttpMessageConverter<?>> converters ) {
for ( HttpMessageConverter<?> converter : converters ) {
if ( converter instanceof MappingJackson2HttpMessageConverter) {
MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) converter;
jacksonConverter.setPrettyPrint( true );
}
}
}
this not working
spring.jackson.serialization.INDENT_OUTPUT=true
this is working spring.jackson.serialization.indent-output=true