Hibernate add custom prefix to the catalogs - java

I'm using Hibernate 4.3.6 and I need to add custom prefix to my catalogs depending on the environment. I used to do this code in version 4.2.3
private static SessionFactory buildSessionFactory() {
try {
Configuration config = new Configuration();
config.configure("db.cfg.xml");
config.buildMappings();
ServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySettings(config.getProperties())
.build();
if (prefix != null && !prefix.isEmpty()) {
Iterator<Table> iterator = config.getTableMappings();
while (iterator.hasNext()) {
Table table = (Table) iterator.next();
table.setCatalog(prefix + table.getCatalog());
}
}
//return new AnnotationConfiguration().buildSessionFactory(registry);
SessionFactory factory = config.buildSessionFactory(registry);
return factory;
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println(ex);
throw new ExceptionInInitializerError(ex);
}
}
But now it errors out on
config.buildSessionFactory(registry);
java.lang.ExceptionInInitializerError
at db.DatabaseEngine.buildSessionFactory(DatabaseEngine.java:110)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.NullPointerException
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1456)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
at db.DatabaseEngine.buildSessionFactory(DatabaseEngine.java:104)
... 26 more
Is there such thing like ImprovedNamingStrategy but for catalogs?

After you create an orm.xml, you can load it using the following code:
Configuration config = new Configuration();
config.configure("db.cfg.xml");
config.addResource("orm.xml"); // Load these files in any order
config.buildMappings();
See Vlad's answer for how to create an orm.xml file.

According to Hibernate Annotation docs the orm.xml XML settings can override the annotation configs:
<entity-mappings
xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
version="2.0">
<persistence-unit-metadata>
<persistence-unit-defaults>
<schema>${db.schema}</schema>
<catalog>${db.catalog}</catalog>
</persistence-unit-defaults>
</persistence-unit-metadata>
<entity class="package.YourEntity1">
<table name="YOUR_TABLE_1" catalog="${specific_catalog1}"/>
</entity>
<entity class="package.YourEntity2">
<table name="YOUR_TABLE_2" catalog="${specific_catalog2}"/>
</entity>
The schema/catalog variables can be replaced by Maven based on a specific profile that you run prior to building. That works for both the default catalog and for specific entity catalog definitions.

Wouldn't be more simpler loading configuration file per environment, I mean (depends of the env)
config.configure("db.cfg-env1.xml");
or
config.configure("db.cfg-env2.xml");
and there set the proper catalog in the jdbc connection url ?
Example close to implementation (thx serge for letting me know :))
config.configure(String.format("db.cfg-%s.xml"), env);

Related

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger [duplicate]

I am receiving the following exception when trying to use java mail;
java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger
at javax.mail.Session.initLogger(Session.java:226)
at javax.mail.Session.<init>(Session.java:210)
at javax.mail.Session.getInstance(Session.java:247)
at com.secondstory.mailsender.MailSender.createSmtpSession(MailSender.java:67)
at com.secondstory.mailsender.MailSender.sendSimpleMessage(MailSender.java:38)
at com.secondstory.mailsender.MailSender.generateLostPasswordEmail(MailSender.java:79)
at com.secondstory.mailsender.MailSenderTest.shouldReturnTrueWithCredentialsSet(MailSenderTest.java:49)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.MailLogger
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 30 more
After searching stack overflow extensively (maybe not extensively enough - lets see!) I have found that we need two jars inside our maven pom for this too work. The two dependancies I have are as follows;
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
Something has changed but I am not entirely sure what it is - as this worked previously. The code i have written where this element fails is as follows;
private static Session createSmtpSession() {
final Properties props = new Properties();
props.setProperty("mail.host", "host");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty("mail.transport.protocol", "smtp");
//props.setProperty("mail.debug", "true");
return Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"username", "password");
}
});
}
Am I missing some config or should this work with the current setup that I have?
Thanks
Try adding this into Maven POM:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.2</version>
</dependency>
The problem is that you are trying to use javax.mail-api.jar. That is the wrong library. JavaMail is a Java EE specification, the interfaces of that specification are published in that javax.mail-api-1.6.1.jar, which only works when compiling. It doesn't provide an implementation of the specification, so it doesn't work at runtime.
You need to use an implementation of the JavaMail specification at runtime. You can find the reference implementation on https://javaee.github.io/javamail/ (but there are others, for example Java EE application servers usually include one).
For javax.mail-api.jar, https://javaee.github.io/javamail/ says:
The JavaMail API definitions only, suitable for compiling against; use
only with a Maven “provided” dependency scope
Specifically in your case you need either javax.mail.jar or mailapi.jar + the jars of the specific protocols you want to use. For example mailapi.jar + smtp.jar if you only need smtp(s) support.
With Maven, you can use
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.1</version>
</dependency>

org.dbunit.dataset.NoSuchTableException: localized_values

I am trying to using spring test dbunit.
https://springtestdbunit.github.io/spring-test-dbunit/
As I am using spring 4.1.x I decided to use version 1.2.1 for spring-test-dbunit and 2.5.2 for core dbunit.
Originally I used plain dbunit and it worked fine. Then I decided to try spring-test-dbunit and I got several problems.
Here is my test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(value = {
"classpath:path/to/test/context/sql-context.xml"})
#TransactionConfiguration(defaultRollback = true)
#Transactional
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class, DbUnitTestExecutionListener.class })
#DbUnitConfiguration(databaseConnection = "databaseConnection")
#DatabaseSetup("classpath:path/to/dataset/questionRepositoryTestDS.xml")
public class QuestionRepositoryDbUnitTest {
....
#Autowired
private QuestionRepository repository;
#Test
public void mustReturnQuestion() throws Exception {
....
assertEquals("Result is not the same as expected!", expected,
repository.findQuestion(QUESTION_ID_1, PRODUCT_CONFIGURATION_ID_1, LANGUAGE));
}
My dataset file looks like this
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<question question_id='q_mail' display_type='EMAIL' display_group='2' organization_uid='123' display_order='1'/>
<question question_id='q_copies' display_type='NUMBER' display_group='1' organization_uid='123' display_order='1'/>
<localized_question question_id='q_mail' language='EN' organization_uid='*' display_label='What is your email?'/>
<localized_question question_id='q_mail' language='EN' organization_uid='123' display_label='Enter the mailbox'/>
<localized_question question_id='q_copies' language='EN' organization_uid='*' display_label='How many copies you are planning to create?'/>
<localized_values question_select_value_id='a_mail1' language='EN' organization_uid='*' display_label='common#email.com'/>
<localized_values question_select_value_id='a_mail1' language='EN' organization_uid='123' display_label='custom#email.com'/>
<localized_values question_select_value_id='a_mail2' language='EN' organization_uid='*' display_label='null#email.com'/>
</dataset>
Database connection bean looks like this
<bean id="databaseConnection"
class="com.github.springtestdbunit.bean.DatabaseDataSourceConnectionFactoryBean">
<property name="schema" value="mySchema"/>
<property name="dataSource" ref="customDataSource"/>
</bean>
where dataSource bean is
<bean id="customDataSource"
class="com.custom.db.embedded.EmbeddedH2DatabaseFactory">
<property name="resourcesFromPaths">
<list value-type="java.lang.String">
<value>#{systemProperties['test-changelog']}</value>
</list>
</property>
<property name="url" value="jdbc:h2:mem:product.pricing;MVCC=TRUE"/>
<property name="createCommonTablesOnStartup" value="false"/>
</bean>
But when I try to run test I get this error
org.dbunit.dataset.NoSuchTableException: localized_values
at org.dbunit.database.DatabaseDataSet.getTableMetaData(DatabaseDataSet.java:305)
at org.dbunit.operation.DeleteAllOperation.execute(DeleteAllOperation.java:109)
at org.dbunit.operation.CompositeOperation.execute(CompositeOperation.java:79)
at com.github.springtestdbunit.DbUnitRunner.setupOrTeardown(DbUnitRunner.java:194)
at com.github.springtestdbunit.DbUnitRunner.beforeTestMethod(DbUnitRunner.java:66)
at com.github.springtestdbunit.DbUnitTestExecutionListener.beforeTestMethod(DbUnitTestExecutionListener.java:186)
at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:249)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:70)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:86)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:49)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:64)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:50)
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:497)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:106)
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:497)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:360)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
What is the problem?
Also when I used plain dbunit I had to set autoCommit in order to make it work
databaseConnection = new DatabaseConnection(h2databaseResource.getConnection(), DATABASE_SCHEMA);
databaseConnection.getConnection().setAutoCommit(true);
(though I thought that autoCommit supposed to be true by default)
I know that this is a late answer but I think your issue is that you haven't created your schema correctly. I see that you are using a custom data source factory and I would recommend you switch over to using a more standardized DB initialization, like putting this in your test XML configuration:
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="classpath:com/foo/sql/db-schema.sql"/>
</jdbc:initialize-database>
Or declaring a test #Configuration class:
#Configuration
public class TestDbConfig {
#Value("classpath:com/foo/sql/db-schema.sql")
private Resource schemaScript;
#Bean
public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) {
final DataSourceInitializer initializer = new DataSourceInitializer();
initializer.setDataSource(dataSource);
initializer.setDatabasePopulator(databasePopulator());
return initializer;
}
private DatabasePopulator databasePopulator() {
final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
populator.addScript(schemaScript);
return populator;
}
}

Test Method fails with Log Error

I've written a test Method. In this project I use Morphia for MongoDB. But when I start the Method I get the follow Error:
java.lang.NoSuchMethodError: org.apache.log4j.Logger.log(Ljava/lang/String;Lorg/apache/log4j/Level;Ljava/lang/Object;Ljava/lang/Throwable;)V
at org.slf4j.impl.Log4jLoggerAdapter.info(Log4jLoggerAdapter.java:166)
at com.mongodb.diagnostics.logging.SLF4JLogger.info(SLF4JLogger.java:71)
at com.mongodb.connection.SingleServerCluster.<init>(SingleServerCluster.java:45)
at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:85)
at com.mongodb.Mongo.createCluster(Mongo.java:670)
at com.mongodb.Mongo.createCluster(Mongo.java:656)
at com.mongodb.Mongo.<init>(Mongo.java:278)
at com.mongodb.Mongo.<init>(Mongo.java:274)
at com.mongodb.MongoClient.<init>(MongoClient.java:174)
at com.mongodb.MongoClient.<init>(MongoClient.java:151)
at com.mongodb.MongoClient.<init>(MongoClient.java:141)
at de.meinTellerchen.utils.mongoDB.connection.MongoDBCon.<init>(MongoDBCon.java:65)
at de.meinTellerchen.ingredient.service.IngredientRestService.dataBaseConnection(IngredientRestService.java:34)
at de.meinTellerchen.ingredient.service.IngredientRestService.<init>(IngredientRestService.java:22)
at de.meinTellerchen.ingredient.service.IngredientRestServiceTest.test001_WriteIngredient(IngredientRestServiceTest.java:21)
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:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
The Method in this Test creates an Object and saves it in a MongoDB with Morphia.
#Test
public void test001_WriteIngredient() {
Ingredient ingredient = generateIngredient();
IngredientRestService ingredientRestService = new IngredientRestService();
assertNotNull(ingredient);
Response response = ingredientRestService.writeIngredient(ingredient);
assertNotNull(response);
}
I don't know why it doesn't work. I don't use Logger.
The issue is with the version of log4j and slf4j.
Add below mentioned jars in your classpath :
log4j
slf4j-simple
jcl-over-slf4j
slf4j-api
slf4j-log4j12 with appropriate versions
or use maven to handle your dependencies.
Example of Compatible versions of jars:
1) log4j-1.2.15.jar
2) slf4j-api-1.7.7.jar
3) commons-logging-1.0.4.jar
4) logback-classic-1.0.0.jar
5) logback-core-1.0.0.jar
The dependent jar of slf4j is missing in your classpath.
Please open the mongodriver jar available in your system and see the meta-inf/MANIFEST.MF file and add the required jars mentioned in Import-Package:section.
Example:
Mongodb java driver 3.2.1 requires following dependent jars.
Import-Package: javax.xml.bind,javax.crypto,javax.crypto.spec,javax.ma
nagement,javax.net,javax.net.ssl,javax.security.sasl,javax.security.a
uth.callback,org.ietf.jgss,io.netty.bootstrap;resolution:=optional;ve
rsion="[4.0,5)",io.netty.buffer;resolution:=optional;version="[4.0,5)
",io.netty.channel;resolution:=optional;version="[4.0,5)",io.netty.ch
annel.nio;resolution:=optional;version="[4.0,5)",io.netty.channel.soc
ket;resolution:=optional;version="[4.0,5)",io.netty.channel.socket.ni
o;resolution:=optional;version="[4.0,5)",io.netty.handler.ssl;resolut
ion:=optional;version="[4.0,5)",io.netty.handler.timeout;resolution:=
optional;version="[4.0,5)",io.netty.util.concurrent;resolution:=optio
nal;version="[4.0,5)",org.slf4j;resolution:=optional;version="[1.7,2)
"

Spring MVC Java-based configuration can't see class-path properties file

I'm trying to migrate my web-app from XML-based configuration to Java-based one. I have properties files under "\src\main\resources\" directory. In XML configuration I had such bean:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:test.properties</value>
</list>
</property>
</bean>
And it worked just fine.
Now I switched to Java config so I have:
#Configuration
#ComponentScan(basePackages = {"blah.blah.blah.*"})
#Import({MVCConfig.class, PersistenceConfig.class, SecurityConfig.class})
#PropertySource("classpath:test.properties")
public class TestConfig {
}
But unfortunately I'm getting exception:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:155)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:100)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:319)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:212)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:264)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
Caused by: org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [classpath:WEB-INF/test.properties] cannot be opened because it does not exist
at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:89)
...
I've tried to use #PropertySource("classpath*:test.properties"), then exception changes to:
Caused by:
org.springframework.beans.factory.BeanDefinitionStoreException: Failed
to load bean class: blah.blah.blah.TestConfig; nested
exception is java.io.FileNotFoundException: class path resource
[classpath*:test.properties] cannot be opened because it does not
exist ...
Leading slash also doesn't help...
My test class starts as follows:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(classes = TestConfig.class, loader = AnnotationConfigContextLoader.class)
public class IntegrationTests {
What am I doing wrong?
My bad: I also had #Bean of type org.springframework.beans.factory.config.PropertyPlaceholderConfigurer and it conflicted somehow with #PropertySource annotation. Removing this been fixed things up.

SAXParseException: Element type "CountryNamecode" must be followed by either attribute specifications, ">" or "/>"

OK, this seems like a common error message, but I've looked at this from a few angles, and I'm stumped.
My XML (complete file is huge, so limiting to area that seems related unless somebody can tell me how/why I need more here):
<?xml version="1.0" encoding="utf-8"?>
<MyXML date="201112102200" type="daily">
<CountryList>
<CountryName code="AARCT" name="Antarctica" IsTerritory="True"/>
<CountryName code="ABKHAZ" name="Abkhazia" IsTerritory="True"/>
<!-- ... -->
<CountryName code="VCAN" name="Vatican City" IsTerritory="False" ProfileURL="vatican city.doc"/>
<CountryName code="VEN" name="Venezuela" IsTerritory="False" ProfileURL="venezuela.doc"/>
<CountryName code="VI" name="US Virgin Islands" IsTerritory="True"/>
<CountryName code="VIETN" name="Vietnam" IsTerritory="False" ProfileURL="vietnam.doc"/>
<CountryName code="WALLIS" name="Wallis and Futuna Islands" IsTerritory="True"/>
<CountryName code="WSOMOA" name="Samoa" IsTerritory="False" ProfileURL="samoa.doc"/>
<CountryName code="YEMAR" name="Yemen" IsTerritory="False" ProfileURL="yemen.doc"/>
<CountryName code="YUG" name="Serbia" IsTerritory="False" ProfileURL="serbia.doc"/>
<CountryName code="ZAIRE" name="Democratic Republic of the Congo" IsTerritory="False" ProfileURL="democratic republic of the congo.doc"/>
<CountryName code="ZAMBIA" name="Zambia" IsTerritory="False" ProfileURL="zambia.doc"/>
<CountryName code="ZIMBAB" name="Zimbabwe" IsTerritory="False" ProfileURL="zimbabwe.doc"/>
</CountryList>
<!-- ... -->
</MyXML>
So the error is:
org.xml.sax.SAXParseException: Element type "CountryNamecode" must be followed by either attribute specifications, ">" or "/>".
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1231)
at com.foo.bar.Baz.<init>(Baz.java:38)
at com.foo.bar.BazTest.testRecordCounts(BazTest.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
The logging I have indicated it's failing after country code "VI", and that there's something wrong with the "VIETN" entry.
So, there doesn't appear to be a malformed element called "CountryNamecode", I've checked for dodgy characters, but it's all pretty vanilla character-wise. The whole file validates when I've checked it, using STS, Oxygen, and xmllint.
Any help on this would be greatly appreciated.
Cheers folks!
EDIT:
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
xmlReader.setContentHandler(this);
xmlReader.setErrorHandler(this);
xmlReader.parse(new InputSource(new StringReader(retriever.getContent())));
The retriever object is returning the xml string, and other than that, I'm parsing an InputSource, passing it the StringReader. Unless there's something obvious I'm missing
I'd be prepared to bet the issue is in the underlying data stream code.
To support my theory, open the original data file, move the cursor to the space between CountryName and code and find a way of determining the exact offset of that space character in the file. It is likely to be an exact multiple of 1024 and probably 4096 or 8192.
Then look at the InputSource or Reader code you are using to feed the SAX parser. It will probably look something like:
sax = factory.newSAXParser();
try {
// Here I am using an InputSource wrapping a StringReader.
sax.parse(new InputSource(new StringReader(xml)), this);
} catch (SAXException ex) {
log.warning("XMLParser failed on: "+xml, ex);
}
I suspect whatever you are using instead of the new InputSource(new StringReader(xml)) I use above is what is corrupting the data.

Categories