Klint and spotless: com.pinterest.ktlint.core.ParseException: Expecting a parameter declaration - kotlin

I'm getting weird exception when trying to run ./gradlew spotlessApply on my project in Kotlin.
Class causing the problem:
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class CurrentFluttering(
#PrimaryKey var id: Long = 0,
var currentCoinsHeap: Int = 0,
var currentEarnedCoins: Int = 0,
var startTime: Long = 0,
var pauseTime: Long = 0,
var time: Long = 0,
var firstCycle: Boolean = true,
var inBackground: Boolean = false,
var currentMissedCoins: Int = 0,
var isPaused: Boolean = false,
) : RealmObject()
Stack trace:
> Task :spotlessKotlin FAILED
Step 'ktlint' found problem in 'app/src/main/java/com/cfhero/android/model/state/CurrentFluttering.kt':
Expecting a parameter declaration
com.pinterest.ktlint.core.ParseException: Expecting a parameter declaration
at com.pinterest.ktlint.core.KtLint.format(KtLint.kt:357)
at sun.reflect.GeneratedMethodAccessor35.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.diffplug.spotless.kotlin.KtLintStep$State.lambda$createFormat$1(KtLintStep.java:173)
at com.diffplug.spotless.FormatterFunc.apply(FormatterFunc.java:31)
at com.diffplug.spotless.FormatterStepImpl$Standard.format(FormatterStepImpl.java:78)
at com.diffplug.spotless.FormatterStep$Strict.format(FormatterStep.java:76)
at com.diffplug.spotless.Formatter.compute(Formatter.java:230)
at com.diffplug.spotless.Formatter.applyToAndReturnResultIfDirty(Formatter.java:192)
at com.di
Have anybody experienced same or similar problem?

I found it. The problem was dangling ',' after last parameter in constructor (which Kotlin allows ).
var isPaused: Boolean = false, <- here ლ(ಠ益ಠლ)
) : RealmObject()

This is caused due to the default ktlint version used by the plugin. As of this time it's private static final String DEFAULT_VERSION = "0.35.0" which does not support trailing commas, although kotlin 1.4 does. In fact they had updated it to 0.40.0 at some point but got some formatting issues whiplash and eventually reverted the changes.
If you want though you can manually point to the latest version with something like
spotless {
kotlin {
target '**/*.kt'
ktlint("0.40.0")
}
}

Related

Kotlin and SimpleXML - Unable to satisfy ElementList Error

I'm struggling to get simpleXML and Kotlin to read a XML file properly.
I've got the following Root class:
class ServerConfiguration {
#field:Root(strict = false, name = "serverConfiguration")
#field:ElementList(required = true, name = "channels", entry = "channel", inline = true, type=Channel::class)
lateinit var channels: List<Channel>
#field:Element(name = "serverSettings", required = true, type = ServerSettings::class)
lateinit var serverSettings: ServerSettings
}
(The Channel class itself has also Lists, but even if I leave it with simple Attributes (ie Strings), it won't work.)
The XML contains:
<serverConfiguration version="3.5.2">
<date>2022-07-12 10:57:47</date>
<channelGroups>
[... lots of groups]
</channelGroups>
<channels>
<channel version="3.5.2">
<id>b7cb6bf9-d3a5-4a74-8399-b6689d915a15</id>
<nextMetaDataId>6</nextMetaDataId>
<name>cANACR_1_Fhir2Hl7Omg</name>
<connector class="[...].TcpReceiverProperties" version="3.5.2">
[... more ]
</channel>
[... a lot of channels]
</channels>
[... even more data]
</serverConfiguration>
Since there are multiple Tags in the xml that contain a "class" Attribute, I understand that I need to use inline = true in my #field:ElementList
I got through a lot of errors up until this point which I could resolve by myself but this one eludes me.
I run the Serializer via:
val serializer: Serializer = Persister()
val dataFetch = serializer.read(ServerConfiguration::class.java, myFile!!, false)
The Error (I cut out classpaths):
org.simpleframework.xml.core.ValueRequiredException: Unable to satisfy #org.simpleframework.xml.ElementList(entry="channel", data=false, inline=true, name="channels", type=Channel.class, required=true, empty=true) on field 'channels' private java.util.List ServerConfiguration.channels for class ServerConfiguration at line 1
If anyone could nudge me in the right direction, I'd be very grateful.
Addendum:
If I set required=false the program runs, but not a single channel is read.
I've tried ArrayList, List, and Set as datatype
I've tried to circumvent lateinit with var channels: List<Channel> = mutableListOf()
I've got it working through adding a wrapper class for the nested lists:
ServerConfiguration.kt:
[...]
#field:Element(name="channels", required = true, type=ChannelList::class)
lateinit var channelList: ChannelList
ChannelList.kt:
class ChannelList {
#field:ElementList(required = true, inline = true,name = "channels", entry = "channel", type=Channel::class, data = true, empty=false)
var channels: List<Channel> = mutableListOf()
}
And finally Channel.kt:
class Channel {
#field:Element(name = "destinationConnectors", required = true, type = DestinationConnectorList::class)
lateinit var destinationConnectorList: DestinationConnectorList
#field:Element(name = "exportData", required = true, type=ExportData::class)
lateinit var exportData: ExportData
[...]
While this is working, I would have expected simpleXML to be able to add the Elements of the List directly without needing to use a wrapper class (ChannelList).
If anyone knows how to achieve this, please feel free to comment or add your solution.
Kind regards,
K

How to load .NET 6 project in a .NET 6 console application

I am attempting to load a .NET 6 project (SDK Style) in a .NET 6 console application. My entire project is fairly simple - it actually attempts to load its own .csproj file when it runs from the default output folder:
using Microsoft.Build.Evaluation;
namespace ProjLoading
{
internal class Program
{
static void Main(string[] args)
{
var projectLocation = "../../../ProjLoading.csproj";
var project = new Project(projectLocation, null, null, new ProjectCollection());
}
}
}
I am using the following nuget packages:
Microsoft.Build (17.2.0)
Microsoft.Build.Utilities.Core (17.2.0)
When I run the code, I get the following exception:
Microsoft.Build.Exceptions.InvalidProjectFileException: 'The SDK 'Microsoft.NET.Sdk' specified could not be found. C:\Users\vchel\source\repos\ProjLoading\ProjLoading\ProjLoading.csproj'
This exception was originally thrown at this call stack:
Microsoft.Build.Shared.ProjectErrorUtilities.ThrowInvalidProject(string, Microsoft.Build.Shared.IElementLocation, string, object[])
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.ExpandAndLoadImportsFromUnescapedImportExpressionConditioned(string, Microsoft.Build.Construction.ProjectImportElement, out System.Collections.Generic.List<Microsoft.Build.Construction.ProjectRootElement>, out Microsoft.Build.BackEnd.SdkResolution.SdkResult, bool)
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.ExpandAndLoadImports(string, Microsoft.Build.Construction.ProjectImportElement, out Microsoft.Build.BackEnd.SdkResolution.SdkResult)
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.EvaluateImportElement(string, Microsoft.Build.Construction.ProjectImportElement)
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.PerformDepthFirstPass(Microsoft.Build.Construction.ProjectRootElement)
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.Evaluate()
Microsoft.Build.Evaluation.Project.ProjectImpl.Reevaluate(Microsoft.Build.BackEnd.Logging.ILoggingService, Microsoft.Build.Evaluation.ProjectLoadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext)
Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(Microsoft.Build.BackEnd.Logging.ILoggingService, Microsoft.Build.Evaluation.ProjectLoadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext)
Microsoft.Build.Evaluation.Project.ProjectImpl.Initialize(System.Collections.Generic.IDictionary<string, string>, string, string, Microsoft.Build.Evaluation.ProjectLoadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext)
Microsoft.Build.Evaluation.Project.Project(string, System.Collections.Generic.IDictionary<string, string>, string, string, Microsoft.Build.Evaluation.ProjectCollection, Microsoft.Build.Evaluation.ProjectLoadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext, Microsoft.Build.FileSystem.IDirectoryCacheFactory)
...
[Call Stack Truncated]
I am building/running this console application from Visual Studio 2022 (17.2.2).
How can I solve this problem?
I don't understand why, but I ran across this solution and it has solved the problem:
https://blog.rsuter.com/missing-sdk-when-using-the-microsoft-build-package-in-net-core/
In case the link dies in the future, my full project now sets the environment variable MSBUILD_EXE_PATH to the latest version of msbuild as shown in the following code:
using Microsoft.Build.Evaluation;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace ProjLoading
{
internal class Program
{
static void Main(string[] args)
{
var startInfo = new ProcessStartInfo("dotnet", "--list-sdks")
{
RedirectStandardOutput = true
};
var process = Process.Start(startInfo);
process.WaitForExit(1000);
var output = process.StandardOutput.ReadToEnd();
var sdkPaths = Regex.Matches(output, "([0-9]+.[0-9]+.[0-9]+) \\[(.*)\\]")
.OfType<Match>()
.Select(m => System.IO.Path.Combine(m.Groups[2].Value, m.Groups[1].Value, "MSBuild.dll"));
var sdkPath = sdkPaths.Last();
Environment.SetEnvironmentVariable("MSBUILD_EXE_PATH", sdkPath);
var projectLocation = "../../../ProjLoading.csproj";
var project = new Project(projectLocation, null, null, new ProjectCollection());
}
}
}

I am trying to get data over an OpenWeather API in Rust but I am facing some iusse regarding parsing I guess

extern crate openweather;
use openweather::LocationSpecifier;
static API_KEY: &str = "e85e0a3142231dab28a2611888e48f22";
fn main() {
let loc = LocationSpecifier::Coordinates {
lat: 24.87,
lon: 67.03,
};
let weather = openweather::get_current_weather(loc, API_KEY).unwrap();
print!(
"Right now in Minneapolis, MN it is {}K",
weather.main.humidity
);
}
error : thread 'main' panicked at 'called Result::unwrap() on an
Err value: ErrorReport { cod: 0, message: "Got unexpected response:
\"{\\"coord\\":{\\"lon\\":67.03,\\"lat\\":24.87},\\"weather\\":[{\\"id\\":803,\\"main\\":\\"Clouds\\",\\"description\\":\\"broken
clouds\\",\\"icon\\":\\"04n\\"}],\\"base\\":\\"stations\\",\\"main\\":{\\"temp\\":294.15,\\"pressure\\":1018,\\"humidity\\":60,\\"temp_min\\":294.15,\\"temp_max\\":294.15},\\"visibility\\":6000,\\"wind\\":{\\"speed\\":5.1,\\"deg\\":30},\\"clouds\\":{\\"all\\":70},\\"dt\\":1574012543,\\"sys\\":{\\"type\\":1,\\"id\\":7576,\\"country\\":\\"PK\\",\\"sunrise\\":1573955364,\\"sunset\\":1573994659},\\"timezone\\":18000,\\"id\\":1174872,\\"name\\":\\"Karachi\\",\\"cod\\":200}\""
}
The issue is a JSON parsing error due to the deserialized struct not matching OpenWeather's JSON, perhaps the API recently added this? With your example, the OpenWeatherCurrent struct is missing timezone.
But it looks like there is an open PR that will fix this, you can test it by doing the following:
Change your Cargo.toml dependency to openweather = { git = "https://github.com/caemor/openweather" }.
The PR author has also updated the get_current_weather signature so you'll need to change lines 2, 10 to the following:
use openweather::{LocationSpecifier, Settings};
let weather = openweather::get_current_weather(&loc, API_KEY, &Settings::default()).unwrap();

Why I receive an error when I use exposed in Kotlin?

I need to receive region_name by region_code from Oracle DB
I use Exposed for my program, but I receive error
in thread "main" java.lang.AbstractMethodError
at org.jetbrains.exposed.sql.Transaction.closeExecutedStatements(Transaction.kt:181)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManagerKt.inTopLevelTransaction(ThreadLocalTransactionManager.kt:137)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManagerKt.transaction(ThreadLocalTransactionManager.kt:75)
Code is
object Codes : Table("REGIONS") {
val region_code = varchar("region_code",32)
val region_name = varchar("region_name",32)}
The main fun contains
.......
val conn = Database.connect("jdbc:oracle:thin:#//...", driver = "oracle.jdbc.OracleDriver",
user = "...", password = "...")
transaction(java.sql.Connection.TRANSACTION_READ_COMMITTED, 1, conn) {
addLogger(StdOutSqlLogger)
Codes.select { Codes.region_code eq "a" }.limit(1).forEach {
print(it[Codes.region_name])
}
}
AbstractMethodError usually means that you compiled the code with one version of a library, but are running it against a different (incompatible) version.  (See for example these questions.)
So I'd check your dependencies &c carefully.

ScalikeJDBC: Connection pool is not yet initialized.(name:'default)

I'm playing with ScalikeJdbc library. I want to retrieve the data from PostgreSQL database. The error I get is quite strange for me. Even if I configure manually the CP:
val poolSettings = new ConnectionPoolSettings(initialSize = 100, maxSize = 100)
ConnectionPool.singleton("jdbc:postgresql://localhost:5432/test", "user", "pass", poolSettings)
I still see the error. Here is my DAO:
class CustomerDAO {
case class Customer(id: Long, firstname: String, lastname: String)
object Customer extends SQLSyntaxSupport[Customer]
val c = Customer.syntax("c")
def findById(id: Long)(implicit session: DBSession = Customer.autoSession) =
withSQL {
select.from(Customer as c)
}.map(
rs => Customer(
rs.int("id"),
rs.string("firstname"),
rs.string("lastname")
)
).single.apply()
}
The App:
object JdbcTest extends App {
val dao = new CustomerDAO
val res: Option[dao.Customer] = dao.findById(2)
}
My application.conf file
# PostgreSQL
db.default.driver = "org.postgresql.Driver"
db.default.url = "jdbc:postgresql://localhost:5432/test"
db.default.user = "user"
db.default.password = "pass"
# Connection Pool settings
db.default.poolInitialSize = 5
db.default.poolMaxSize = 7
db.default.poolConnectionTimeoutMillis = 1000
The error:
Exception in thread "main" java.lang.IllegalStateException: Connection pool is not yet initialized.(name:'default)
at scalikejdbc.ConnectionPool$$anonfun$get$1.apply(ConnectionPool.scala:57)
at scalikejdbc.ConnectionPool$$anonfun$get$1.apply(ConnectionPool.scala:55)
at scala.Option.getOrElse(Option.scala:120)
at scalikejdbc.ConnectionPool$.get(ConnectionPool.scala:55)
at scalikejdbc.ConnectionPool$.apply(ConnectionPool.scala:46)
at scalikejdbc.NamedDB.connectionPool(NamedDB.scala:20)
at scalikejdbc.NamedDB.db$lzycompute(NamedDB.scala:32)
What did I miss?
To load application.conf, scalikejdbc-config's DBs.setupAll() should be called in advance.
http://scalikejdbc.org/documentation/configuration.html#scalikejdbc-config
https://github.com/scalikejdbc/hello-scalikejdbc/blob/9d21ec7ddacc76977a7d41aa33c800d89fedc7b6/test/settings/DBSettings.scala#L3-L22
In my case I omit play.modules.enabled += "scalikejdbc.PlayModule" in conf/application.conf using ScalikeJDBC Play support...