How do i disable elastic search and fall back to local filesystem storage in hibernate search 6 - hibernate-search

I am using Hibernate 6 with Amazons opensearch server in production. When i'm testing locally i don't want to use the opensearch server, instead i want to use local-filesystem to store the index files.
However i can't hibernate search to use local-filesystem even when i explicitly set it with jpaProperties.put("hibernate.search.backend.directory.type", "local-filesystem"); while at the same time not setting the property hibernate.search.backend.uris. Before all the hibernate search properties can be programmatically set i get the following error on startup:
default backend:
failures:
- HSEARCH400080: Unable to detect the Elasticsearch version running on the cluster: HSEARCH400007: Elasticsearch request failed: Connection refused: no further information
Request: GET with parameters {}
I have the following maven dependencies:
<dependency>
<groupId>org.hibernate.search</groupId>
<artifactId>hibernate-search-mapper-orm</artifactId>
<version>6.1.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.search</groupId>
<artifactId>hibernate-search-backend-elasticsearch-aws</artifactId>
<version>6.1.5.Final</version>
</dependency>
The following sets hibernate search and the lucene file destination path if using lucene only:
private Properties initializeJpaProperties() {
String luceneAbsoluteFilePath = useExternalElasticSearchServer ? null : setDefaultLuceneIndexBaseFilePath(); //Alleen relevant wanneer je geen elastic search gebruikt.
Properties jpaProperties = new Properties();
//---------------------------open search aws related-----------------------------------
if(useExternalElasticSearchServer) {
jpaProperties.put("hibernate.search.backend.aws.credentials.type", "static");
jpaProperties.put("hibernate.search.backend.aws.credentials.access_key_id", awsId);
jpaProperties.put("hibernate.search.backend.aws.credentials.secret_access_key", awsKey);
jpaProperties.put("hibernate.search.backend.aws.region", openSearchAwsInstanceRegion);
jpaProperties.put("hibernate.search.backend.aws.signing.enabled", true);
jpaProperties.put("hibernate.search.backend.uris", elasticSearchHostAddress);
}
//--------------------------------------------------------------------------------------------
jpaProperties.put("hibernate.search.automatic_indexing.synchronization.strategy", indexSynchronizationStrategy);
jpaProperties.put("hibernate.search.backend.request_timeout", requestTimeout);
jpaProperties.put("hibernate.search.backend.connection_timeout", elasticSearchConnectionTimeout);
jpaProperties.put("hibernate.search.backend.read_timeout", readTimeout);
jpaProperties.put("hibernate.search.backend.max_connections", maximumElasticSearchConnections);
jpaProperties.put("hibernate.search.backend.max_connections_per_route", maximumElasticSearchConnectionsPerRout);
// jpaProperties.put("hibernate.search.schema_management.strategy", schemaManagementStrategy);
jpaProperties.put("hibernate.search.backend.thread_pool.size", maxPoolSize);
jpaProperties.put("hibernate.search.backend.analysis.configurer", "class:config.EnhancedLuceneAnalysisConfig");
// jpaProperties.put("hibernate.search.backend.username", hibernateSearchUsername); //Alleen voor wanneer je elastic search lokaal draait
// jpaProperties.put("hibernate.search.backend.password", hibernateSearchPassword);
if(!useExternalElasticSearchServer) {
jpaProperties.put("hibernate.search.backend.directory.type", "local-filesystem");
jpaProperties.put("hibernate.search.backend.directory.root", luceneAbsoluteFilePath);
jpaProperties.put("hibernate.search.backend.lucene_version", "LUCENE_CURRENT");
jpaProperties.put("hibernate.search.backend.io.writer.infostream", true);
}
jpaProperties.put("hibernate.jdbc.batch_size", defaultBatchSize);
jpaProperties.put("spring.jpa.properties.hibernate.jdbc.batch_size", defaultBatchSize);
jpaProperties.put("hibernate.order_inserts", "true");
jpaProperties.put("hibernate.order_updates", "true");
jpaProperties.put("hibernate.batch_versioned_data", "true");
// log.info("The directory of the lucene index files is set to {}", luceneAbsoluteFilePath);
return jpaProperties;
}
private String setDefaultLuceneIndexBaseFilePath() {
String luceneRelativeFilePath = ServiceUtil.getOperatingSystemCompatiblePath("/data/lucene/indexes/default");
StringBuilder luceneAbsoluteFilePath = new StringBuilder(System.getProperty("user.dir"));
if(!StringUtils.isEmpty(luceneIndexBase)) {
luceneRelativeFilePath = ServiceUtil.getOperatingSystemCompatiblePath(luceneIndexBase);
String OSPathSeparator = ServiceUtil.getOperatingSystemFileSeparator();
if(luceneRelativeFilePath.toCharArray()[0] != OSPathSeparator.charAt(0))
luceneAbsoluteFilePath.append(OSPathSeparator);
luceneAbsoluteFilePath.append(luceneRelativeFilePath);
validateUserDefinedAbsolutePath(luceneRelativeFilePath);
}
else{
log.warn("No relative path value for property 'lucene-index-base' was found in application.properties, will use the default path '{}' instead.", luceneRelativeFilePath);
luceneAbsoluteFilePath.append(luceneRelativeFilePath);
}
return luceneAbsoluteFilePath.toString();
}
I know that i can disable hibernate search completely with hibernate.search.enabled set to false but i don't want that. I want to be able to switch to lucene only without having to remove all the ElasticSearch/OpenSearch dependencies from my POM.xml beforehand. How do i do this?
EDIT: I just found out that you can set the backend type with hibernate.search.backend.type. This setting is set to the value elasticsearch by default. I should also be able to set this value to lucene but when i do that i get the following error:
default backend:
failures:
- HSEARCH000501: Invalid value for configuration property 'hibernate.search.backend.type': 'lucene'. HSEARCH000579: Unable to resolve bean reference to type 'org.hibernate.search.engine.backend.spi.BackendFactory' and name 'lucene'. Failed to resolve bean from Hibernate Search's internal registry with exception: HSEARCH000578: No beans defined for type 'org.hibernate.search.engine.backend.spi.BackendFactory' and name 'lucene' in Hibernate Search's internal registry. Failed to resolve bean from bean manager with exception: HSEARCH000590: No configured bean manager. Failed to resolve bean from bean manager with exception: HSEARCH000591: Unable to resolve 'lucene' to a class extending 'org.hibernate.search.engine.backend.spi.BackendFactory': HSEARCH000530: Unable to load class 'lucene': Could not load requested class : lucene Failed to resolve bean using reflection with exception: HSEARCH000591: Unable to resolve 'lucene' to a class extending
'org.hibernate.search.engine.backend.spi.BackendFactory': HSEARCH000530: Unable to load class 'lucene': Could not load requested class : lucene
EDIT 2:
I tried the setting the following settings with no success as well.
jpaProperties.put("hibernate.search.default_backend", "lucene");
jpaProperties.put("hibernate.search.backends.lucene.type", "lucene");
jpaProperties.put("hibernate.search.backend.type", "lucene");

You need to set the backend type explicitly according to the environment:
jpaProperties.put("hibernate.search.backend.type", isProductionEnvironment() ? "elasticsearch" : "lucene");
And you also need to have the Lucene backend in your classpath:
<dependency>
<groupId>org.hibernate.search</groupId>
<artifactId>hibernate-search-backend-lucene</artifactId>
<version>${my-hibernate-search-version}</version>
</dependency>

Related

Can't install and use Jhipster Registry 7.4.0 because hazelcast and logs properties are left bound

I try to use Jhipster Registry 7.4.0 for my new application. At this time, I just want to start it in default configuration.
In my application and application-dev properties files, I have (in both files):
...
jhipster:
async:
core-pool-size: 2
max-pool-size: 50
queue-capacity: 10000
cache:
hazelcast:
time-to-live-seconds: 3600
backup-count: 1
management-center:
enabled: false
update-interval: 3
url: http://localhost:8180/mancenter
security:
authentication:
jwt:
base64-secret: <MY KEY>
metrics:
logs:
enabled: false
report-frequency: 60
...
When I start my registry, it's failed because logs and hazelcast are left bound :
2022-11-17T11:42:40.901+01:00 INFO 11900 --- [ main] t.jhipster.registry.JHipsterRegistryApp : The following 4 profiles are active: "composite", "dev", "api-docs", "swagger"
2022-11-17T11:42:44.401+01:00 WARN 11900 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webConfigurer' defined in URL [jar:file:/C:/Users/myuser/Desktop/JHIPSTER_REGISTRY-7.4.0/jhipster-registry-7.4.0.jar!/BOOT-INF/classes!/tech/jhipster/registry/config/WebConfigurer.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'jhipster-tech.jhipster.config.JHipsterProperties': Could not bind properties to 'JHipsterProperties' : prefix=jhipster, ignoreInvalidFields=false, ignoreUnknownFields=false; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'jhipster' to tech.jhipster.config.JHipsterProperties
2022-11-17T11:42:44.489+01:00 ERROR 11900 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : ____***************************__APPLICATION FAILED TO START__***************************____Description:____Binding to target [Bindable#9a2ec9b type = tech.jhipster.config.JHipsterProperties, value = 'provided', annotations = array<Annotation>[#org.springframework.boot.context.properties.ConfigurationProperties(ignoreInvalidFields=false, ignoreUnknownFields=false, prefix="jhipster", value="jhipster")]] failed:____ Property: jhipster.metrics.logs.enabled__ Value: "false"__ Origin: URL [file:config/application-dev.yml] - 88:22__ Reason: The elements [jhipster.metrics.logs.enabled,jhipster.metrics.logs.report-frequency] were left unbound.__ Property: jhipster.metrics.logs.report-frequency__ Value: "60"__ Origin: URL [file:config/application-dev.yml] - 89:31__ Reason: The elements [jhipster.metrics.logs.enabled,jhipster.metrics.logs.report-frequency] were left unbound.____Action:____Update your application's configuration__
Do you know why this properties ar not found ? I havec check sample on gitub registry depo ans configuration seems to be identical ...

Kafka testcontainer not running

I am trying to setup an integration test env for debezium integration (following the instructions in this example) but the test container (default image: confluentinc/cp-kafka:5.2.1) doesn't start but throws an exception.
I am using below mentioned code to create a KafkaContainer bean
#Bean
public KafkaContainer kafkaContainer() {
if (kafkaContainer == null) {
kafkaContainer = new KafkaContainer()
.withNetwork(network())
.withExternalZookeeper("172.17.0.2:2181");
kafkaContainer.start();
}
}
return kafkaContainer;
}
it throws following exception.
***************************
APPLICATION FAILED TO START
***************************
Description:
An attempt was made to call a method that does not exist. The attempt was made from the following location:
org.testcontainers.containers.KafkaContainer.getBootstrapServers(KafkaContainer.java:91)
The following method did not exist:
org/testcontainers/containers/KafkaContainer.getHost()Ljava/lang/String;
The method's class, org.testcontainers.containers.KafkaContainer, is available from the following locations:
jar:file:/home/shubham/.m2/repository/org/testcontainers/kafka/1.14.3/kafka-1.14.3.jar!/org/testcontainers/containers/KafkaContainer.class
The class hierarchy was loaded from the following locations:
org.testcontainers.containers.KafkaContainer: file:/home/shubham/.m2/repository/org/testcontainers/kafka/1.14.3/kafka-1.14.3.jar
org.testcontainers.containers.GenericContainer: file:/home/shubham/.m2/repository/org/testcontainers/testcontainers/1.12.5/testcontainers-1.12.5.jar
org.testcontainers.containers.FailureDetectingExternalResource: file:/home/shubham/.m2/repository/org/testcontainers/testcontainers/1.12.5/testcontainers-1.12.5.jar
Action:
Correct the classpath of your application so that it contains a single, compatible version of org.testcontainers.containers.KafkaContainer
2020-09-10 01:09:49.937 ERROR 72507 --- [ main] o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener
Used an older version of org.testcontainers in maven dependencies and it worked. Thanks!

Invalid mongo configuration, either uri or host/port/credentials must be specified

I'm getting this exception :
Caused by: java.lang.IllegalStateException: Invalid mongo configuration, either uri or host/port/credentials must be specified
at org.springframework.boot.autoconfigure.mongo.MongoProperties.createMongoClient(MongoProperties.java:207)
at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration.mongo(MongoAutoConfiguration.java:73)
at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration$$EnhancerBySpringCGLIB$$15f9b896.CGLIB$mongo$1(<generated>)
at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration$$EnhancerBySpringCGLIB$$15f9b896$$FastClassBySpringCGLIB$$c0338f6a.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration$$EnhancerBySpringCGLIB$$15f9b896.mongo(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 25 common frames omitted
Here is my application.yml content :
spring:
data:
mongodb:
uri: mongodb://develop:d3VeL0p$#<my_host>:27017/SHAM
Here is my configuration class :
package com.me.service.testservice.config;
import com.mongodb.MongoClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
#Configuration
#EnableMongoRepositories(basePackages = {"com.me.service.testservice.repository"}, considerNestedRepositories = true)
public class SpringMongoConfiguration {
#Bean
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(new MongoClient("<my_host>"), "SHAM");
}
}
Now I'm getting this stack trace when starting without failing, it looks like user develop doesn't have the right to connect:
Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server phelbwlabect003.karmalab.net:27017. The full response is { "ok" : 0.0, "errmsg" : "Authentication failed.", "code" : 18, "codeName" : "AuthenticationFailed" }
at com.mongodb.connection.CommandHelper.createCommandFailureException(CommandHelper.java:170)
at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:123)
at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
at com.mongodb.connection.SaslAuthenticator.sendSaslStart(SaslAuthenticator.java:117)
at com.mongodb.connection.SaslAuthenticator.access$000(SaslAuthenticator.java:37)
at com.mongodb.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:50)
... 9 common frames omitted
You are mixing the uri style connection settings with the individual properties style settings.
Either use
spring:
data:
mongodb:
host: localhost
port: 27017
database: SHAM_TEST
username: develop
password: pass
Or
spring:
data:
mongodb:
uri:mongodb://develop:pass#localhost:27017/SHAM_TEST
If your project has more then one application.properties/application.yml file, sometime they both conflicts if one has URI and other has Host/Port/Credential.
This result in the error "Invalid mongo configuration, either uri or host/port/credentials must be specified"
To Avoid the conflict, make sure you either use URI or Host/Port/Credential in all.
The issue was authentication-database was missing.
Here is now the working configuration :
spring:
data:
mongodb:
host: <my_host>
username: develop
password: d3VeL0p$
port: 27017
database: SHAM
repositories:
enabled: true
authentication-database: admin
If you are using application.properties file to store your configuration, Use the following structure.
spring.data.mongodb.host = localhost
spring.data.mongodb.port = 27017
spring.data.mongodb.database = SHAM_TEST
spring.data.mongodb.username = develop
spring.data.mongodb.password = pass
This issue appears with mongo version 4.x,
spring or spring boot supports version 2.x only so when we try to connect with mongo 4 this error appears:
Downgrade your mongo from 4.x to 3.x or lower.
If not, then change these placeholders.
Change from :
spring.data.mongodb.host= localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database= your db name
spring.data.mongodb.username= something
spring.data.mongodb.password= ***
-to-
mongo.replica.hosts=localhost:27017
mongo.dbname= your db name
mongo.username= something
mongo.password= ***

Getting error in installing mongeez plugin

I'm trying to install mongeez plugin and I get the following error,
I have included ,
plugins{
..
compile ':mongeez:0.2.3'
..
}
in the BuildConfig.groovy
Error creating bean with name 'grails.mongeez.MongeezController': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongeez': Cannot resolve reference to bean 'mongo' while setting bean property 'mongo'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongo' is defined
.....
.....
....
....
.....
.....
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongeez': Cannot resolve reference to bean 'mongo' while setting bean property 'mongo'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongo' is defined
I'm able to install the plugin by adding mongeez as a dependency instead of a plugin.
BuildConfig.groovy
dependencies {
......
.....
compile 'org.mongeez:mongeez:0.9.6'
.....
......
}
Contents of migrations folder(Change logs)
I have grails-app/migrations/test.js
grails-app/migrations/mongeez.xml
This is my mongeez.xml
<changeFiles>
<file path="test.js"/>
</changeFiles>
This is my test.js
db.movie.insert({
"name":"tutorials point"
});
I have written a groovy script as follows,
import com.mongodb.Mongo
import org.springframework.core.io.ClassPathResource
import org.mongeez.Mongeez
includeTargets << grailsScript("_GrailsInit")
target(updateMongo: "Update the mongo DB!") {
println "The script is about to run"
def host = 'localhost'
def port = 27017
def databaseName = 'reporting'
Mongeez mongeez = new Mongeez()
mongeez.setFile(new ClassPathResource("/migrations/mongeez.xml"))
mongeez.setMongo(new Mongo(host, port))
mongeez.setDbName(databaseName)
mongeez.process()
println "The script just ran"
}
setDefaultTarget(updateMongo)
When I run the above script both the print statements are getting executed.
A mongeez collection also got created in my reporting db but the contents of test.js(movie collection) is not reflected in my mongodb , i.e movie collection is not getting created.
Please suggest me if I'm missing something.
Got mongeez plugin working by replacing ClassPathResource with FileSystemResource.
Mongeez mongeez = new Mongeez()
mongeez.setFile(new FileSystemResource(path)) // Give the path to your mongeez.xml
mongeez.setMongo(new Mongo(properties.host, properties.port))
mongeez.setDbName(databaseName)
mongeez.process()

How to connect JBoss 7.1.1 remoting -jmx via java code?

I have a JBoss 7.1.1 server, for which I want to write jmx client. As far I understood, jboss 7.1.1 is not using typical rmi based jmx and they have given a layer of remoting-jmx over native management. I am using following code:
JMXServiceURL address = new JMXServiceURL("service:jmx:remoting-jmx://localhost:9999");
Map env = JMXConnectorConfig.getEnvironment(paramtbl);
JMXConnector connector = JMXConnectorFactory.connect(address, env);
But it is giving following exception:
java.net.MalformedURLException: Unsupported protocol: remoting-jmx
I googled it and the following thread seems relevant:
https://community.jboss.org/thread/204653?tstart=0
It asks to add jboss's libraries to my classpath. I tried that also but still getting same exception.
I got the same exception when trying to get a JmxServiceUrl.
Make sure that in your standalone.xml you have the following:
<subsystem xmlns="urn:jboss:domain:jmx:1.1">
<show-model value="true"/>
<remoting-connector use-management-endpoint="true" />
</subsystem>
And you should include in project classpath the jar named: jboss-client.jar, it can be found in JBOSS_DIRECTORY/bin/client. In fact, the JMX client must include that jar in its classpath.
This tip fixed the problem for me..Hope it will be helpful for you
Tried to do the same from Arquillian test on JBoss AS7 and finally had to use:
import org.jboss.remotingjmx.RemotingConnectorProvider;
RemotingConnectorProvider s = new RemotingConnectorProvider();
JMXConnector connector = s.newJMXConnector(url, credentials);
connector.connect();
Could not have "module name="org.jboss.remoting-jmx" services="import"" working
Also works with
environment.put("jmx.remote.protocol.provider.pkgs", "org.jboss.remotingjmx");
JMXConnector connector = JMXConnectorFactory.connect(url, environment);
connector.connect();
I used this code to connect to JBoss in a remote server
ModelControllerClient client = null;
try {
client = createClient(InetAddress.getByName("172.16.73.12"), 9999,
"admin", "pass", "ManagementRealm");
}
catch (UnknownHostException e) {
e.printStackTrace();
}
Where createClient is a method I wrote -
private ModelControllerClient createClient(final InetAddress host,
final int port, final String username, final String password,
final String securityRealmName) {
final CallbackHandler callbackHandler = new CallbackHandler() {
public void handle(Callback[] callbacks) throws IOException,
UnsupportedCallbackException {
for (Callback current : callbacks) {
if (current instanceof NameCallback) {
NameCallback ncb = (NameCallback) current;
ncb.setName(username);
} else if (current instanceof PasswordCallback) {
PasswordCallback pcb = (PasswordCallback) current;
pcb.setPassword(password.toCharArray());
} else if (current instanceof RealmCallback) {
RealmCallback rcb = (RealmCallback) current;
rcb.setText(rcb.getDefaultText());
} else {
throw new UnsupportedCallbackException(current);
}
}
}
};
return ModelControllerClient.Factory
.create(host, port, callbackHandler);
}
For more information on how to read the data obtained from Server or for the complete project using Java/Google visualizer API (to show the statistics in Graph after every 10 secs) , Please refer to this tutorial -
http://javacodingtutorial.blogspot.com/2014/05/reading-jboss-memory-usage-using-java.html
Add the following to your jboss-deployment-structure
<dependencies>
<module name="org.jboss.remoting3.remoting-jmx" services="import"/>
</dependencies>
Activate JMX remoting subsystem by adding following entry in standalone.xml
<subsystem xmlns="urn:jboss:domain:ee:1.1">
<!-- Activate JMX remoting -->
<global-modules>
<module name="org.jboss.remoting-jmx" slot="main"/>
</global-modules>
...
</subsystem>
It seems like "jboss-client.jar" is not available at run-time for JMX connection, So make sure that you have added "jboss-client.jar" in the class path.
And also you are using deprecated protocol "remoting-jmx" instead of "remote".
i.e, "service:jmx:remote://localhost:9999"
Hope it helps.