No bean exists of type error in Kotlin-micronaut - kotlin

I have a class which creates custom-named bean (test-index), but if I try to change the name of the bean to some other name (say test-index-new), it results in following error whereas the same works if the bean name is not changed:
Code:
#Singleton
#Requires("data-source-config.files-to-load.bigram-corpus")
class Service(
#Named("test-index") val biGramIndexManagerService: BigramIndexManagerService // changing it to test-index-new results in below error
)
BigramIndexManagerService.kt
class BigramIndexManagerService {
// business-service class
}
No bean of type exists for the given qualifier: #Named('test-index-new'): Make sure the bean is not disabled by bean requirements (enable trace logging for 'io.micronaut.context.condition' to check) and if the bean is enabled then ensure the class is declared a bean and annotation processing is enabled (for Java and Kotlin the 'micronaut-inject-java' dependency should be configured as an annotation processor).
I have enabled annotation processing at dependencies.gradle like below:
annotationProcessor "io.micronaut:micronaut-inject-java"
And I have bigram-corpus at the application.yml file
data-source-config:
files-to-load:
bigram-corpus:
file-path: <file_path>
....
Please let me know if I am missing something, thanks in advance!

After doing clean build, the issue has been fixed. Whoever encounters this issue, please do a delete of your build folder and run it again or do a clean build. Hope this helps!

Related

spring.sql.init.schema-locations Not Working

I'm using profiles to determine which data connector to use (dev=h2, prod=mySQL).
I'm attempting to use
spring.sql.init.schema-locations=
To set the location to the relevant path with properties from the active profile but I keep getting:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]:
Invocation of init method failed; nested exception is java.lang.IllegalStateException: No schema scripts found at location './database/h2/schema-h2.sql'
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.15.jar:5.3.15]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.15.jar:5.3.15]
and the same error no matter where I point the property to.
Is there any other special syntax for declaring which file or which directory under resources for this property? When I edit this property autocomplete in Idea happily shows the folder/file structure, but Spring can't see what I'm pointing to!
Answer as per #Andy Wilkinson's comment above:
Adding classpath: as a prefix resolved the issue.

apache camel REST failing with [Error creating bean with name 'rest-configuration']

My route looks like below -
#Override
public void configure() throws Exception {
from("kafka:adapterTopic")
.to("rest://post:gatewayinbound-dev11.devsite.com");
}
I have tried with this as well,
.to("rest:post:gatewayinbound-dev11.devsite.com");
and this as well,
restConfigutation().host("gatewayinbound-dev11.devsite.com");
from("kafka:adapterTopic")
.to("rest:post:provideStatus/");
I have tried with camel-rest-starter dependency in the classpath and without it as well.
I have tried putting camel-rest instead of camel-rest-starter in the pom.
But nothing is making the exception go away, below is the stacktrace-
{"timestamp":"2020-04-21 18:17:45.327","severity":"ERROR","class":"org.springframework.boot.SpringApplication","crId":"","msg":"Application run failed","exception":"org.apache.camel.RuntimeCamelException","cause":"org.apache.camel.FailedToCreateRouteException: Failed to create route route10 at: >>> To[rest:post:gatewayinbound-dev11.devsite.com] <<< in route: Route(route10)[[From[kafka:adapterTopic]] -> [To[rest:... because of Failed to resolve endpoint: rest:\/\/post:gatewayinbound-dev11.devsite.com due to: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'rest-configuration' defined in class path resource [org\/apache\/camel\/model\/rest\/springboot\/RestConfigurationDefinitionAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.camel.spi.RestConfiguration]: Factory method 'configureRestConfigurationDefinition' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot configure option [useXForwardHeaders] with value [true] as the bean class [org.apache.camel.spi.RestConfiguration] has no suitable setter method, or not possible to lookup a bean with the id [true] in Spring Boot registry"
Please help me here. Looking at the examples at Camel's website it looks quite easy to configure a rest producer endpoint but for me it has been very difficult.
Edit-
As Rest component is part of camel-core, I was using camel-core-2.22.1.
Then as suggested by Raúl Cancino, I tried this as well-
to("rest:post:provideStatus?host=gatewayinbound-dev11.devsite.com:443")
please try the following uri format on your to(), as a starting point:
to("rest:post:provideStatus?host=gatewayinbound-dev11.devsite.com:443")
then you can switch to rest configuration
restConfiguration().host("gatewayinbound-dev11.devsite.com:443");
also, using camel-http this would be:
.setHeader(Exchange.HTTP_METHOD,constant(org.apache.camel.component.http.HttpMethods.POST))
.to("https:gatewayinbound-dev11.devsite.com/provideStatus?bridgeEndpoint=true")
Hope it works for you
The problem was with the version of camel-core library my applcation was using (as transitive dependency), when I switched to camel-core-2.24.2 the problem got resolved.
I compared org.apache.camel.spi.RestConfiguration classes from both versions of camel-core, 2.22.1 and 2.24.2 and found that property useXForwardHeaders was missing in older version.

Kotlin Script Engine throws "unresolved reference", even if the package and class is valid

When using Kotlin's Script Engine, trying to import packages or use any class throws an "unresolved reference"
javax.script.ScriptException: error: unresolved reference: mrpowergamerbr
fun loritta(context: com.mrpowergamerbr.loritta.commands.CommandContext) {
^
This doesn't happen when running the class within IntelliJ IDEA, however it does happen when running the class on production.
While this YouTrack issue is related to fat JARs, this also can happen if you aren't using fat JARs (loading all the libraries via the startup classpath option or the Class-Path manifest option)
To fix this, or you can all your dependencies on your startup script like this:
-Dkotlin.script.classpath=jar1:jar2:jar3:jar4
Example:
java -Dkotlin.script.classpath=libs/dependency1.jar:libs/dependency2.jar:yourjar.jar -jar yourjar.jar
Or, if you prefer, set the property via code, using your Class-Path manifest option.
val path = this::class.java.protectionDomain.codeSource.location.path
val jar = JarFile(path)
val mf = jar.manifest
val mattr = mf.mainAttributes
// Yes, you SHOULD USE Attributes.Name.CLASS_PATH! Don't try using "Class-Path", it won't work!
val manifestClassPath = mattr[Attributes.Name.CLASS_PATH] as String
// The format within the Class-Path attribute is different than the one expected by the property, so let's fix it!
// By the way, don't forget to append your original JAR at the end of the string!
val propClassPath = manifestClassPath.replace(" ", ":") + ":Loritta-0.0.1-SNAPSHOT.jar"
// Now we set it to our own classpath
System.setProperty("kotlin.script.classpath", propClassPath)
While I didn't test this yet, in another unrelated answer it seems you can also supply your own classpath if you initialize the KotlinJsr223JvmLocalScriptEngine object yourself (as seen here)

facing issues while loading bean defined in cache.xml of another .jar file

Background : I have two projects, proj A and proj B. Now, in proj A i have a cache.xml file , a java bean(say customer bean), a repository class(RecordRepository). I am loading the repository class in the cache.xml
Cache.xml
</gfe:client-region>
<!--Scan for annotated GemFire Repositories-->
<gfe-data:repositories base-package="cache.repository" />
In proj B, I import the jar of proj A and then try to load the bean and the repository.
My goal is to create an object of customer bean and then call the repository class to save the customer bean.
Employee emp = (Employee)facilityCacheLoader.getRegionBean();
emp.setRecordId("2001");
emp.setRecordString("record string 2002");
// update the Bean and save
RecordRepository rep = (RecordRepository)facilityCacheLoader.getRepository();
rep.save(emp);
But I am getting the following exception:
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [cache.repository.RecordRepository] is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:296)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1125)
at com.rxc.cacheclient.CacheLoaderClient.main(CacheLoaderClient.java:40)
What do you mean by?
In proj B, I import the jar of proj A and then try to load the bean and the repository.
And specifically... "I 'import' the jar of proj A"?
Effectively, proj A's JAR file must be on the classpath of the application created by proj B, assuming, of course, cache.repository.RecordRepository is the fully qualified class name (FQCN) of the Repository class defined in proj A, and which you expect to be picked up in Spring's classpath component scanning, used by SD's infrastructure to locate application-defined Repositories (such as your RecordRepository) in proj B's application, i.e. ...
<!--Scan for annotated GemFire Repositories-->
<gfe-data:repositories base-package="cache.repository" />
Perhaps you could share a GitHub project with you application code and configuration
Thanks!
-John

Sylius - How to implement a custom EntityRepository

I'm getting a bit frustrated trying to override the repository of my own Entity.
I need to create a custom repository method to get a list of my entities with special way. One queryBuilder with Having and OrderBy.
Te question is how can I setup my config to say Sylius, take my custom repositor, not the default.
I try this:
sylius_resource:
resources:
dinamic.category:
classes:
model: App\Bundle\SyliusBlogBundle\Entity\PostCategory
repository: App\Bundle\SyliusBlogBundle\Repository\PostCategoryRepository
This is my Repository:
<?php
namespace App\Bundle\SyliusBlogBundle\Repository;
use Doctrine\ORM\EntityRepository;
class PostCategoryRepository extends EntityRepository
{
public function findCategoriesMenu()
{
$queryBuilder = $this->createQueryBuilder('c');
return $queryBuilder
->addSelect('COUNT(p.id) as totalPosts')
->leftJoin('c.posts', 'p')
->andWhere('p.published = true')
->having('totalPosts > 0')
->addGroupBy('p.id')
;
}
}
When I try to use this method, Symfony throws me this error:
An exception has been thrown during the rendering of a template ("Undefined method 'findCategoriesMenu'. The method name must start with either findBy or findOneBy!")
Well you aren't subclassing the correct repository. The ResourceController expects a repository based on the Sylius\Component\Resource\Repository\RepositoryInterface. Since you are subclassing from Doctrine\ORM\EntityRepository that won't be the case.
Your repository should inherit from Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository (or implement the interface yourself).
I answer to the post to paste correctly the response of app/console debug:container dinamic.repository.category
Information for Service "dinamic.repository.category"
=====================================================
------------------ -------------------------------------------------------------------
Option Value
------------------ -------------------------------------------------------------------
Service ID dinamic.repository.category
Class Dinamic\Bundle\SyliusBlogBundle\Repository\PostCategoryRepository
Tags -
Scope container
Public yes
Synthetic no
Lazy no
Synchronized no
Abstract no
Autowired no
Autowiring Types -
------------------ -------------------------------------------------------------------
Since here all it's ok.
When i try to access to Posts list this error appears:
An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Argument 4 passed to Sylius\Bundle\ResourceBundle\Controller\ResourceController::__construct() must implement interface Sylius\Component\Resource\Repository\RepositoryInterface, instance of Dinamic\Bundle\SyliusBlogBundle\Repository\PostCategoryRepository given, called in /Applications/XAMPP/xamppfiles/htdocs/rosasinbox-sylius/app/cache/dev/appDevDebugProjectContainer.php on line 2767 and defined")
The error of main post appears when the repository config wasn't set. Then my first post was wrong, on config.yml repository value wasn't set.
Now i set it another time and i got this error.
Sorry for the confusion.