how to set active profile for gradle build of spring boot application? - spring-mvc

Here is the DbConfig of my spring-boot application.
#Configuration
#EnableTransactionManagement
public class DBConfig
{
#Bean
public LocalSessionFactoryBean sessionFactory()
{
....
}
#Bean
public DataSource aaDataSource()
{
.....
}
public PlatformTransactionManager transactionManager()
{
....
}
private Properties hibernateProperties()
{
....
}
}
Here is my test class
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Application.class)
#WebAppConfiguration
public class ApplicationTests {
#Test
public void contextLoads() {
}
}
Its a gradle project.
when I run gradlew clean build locally, I get successful build since my connection settings in application.properties matches my sql connection.
But when I run from jenkins box in our qa environment (the database is qa one), the build fails with following exception.
java.lang.IllegalStateException: Failed to load ApplicationContext
....
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is com.zaxxer.hikari.pool.PoolInitializationException: Exception during pool initialization
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(Abstract
.....
Caused by: com.zaxxer.hikari.pool.PoolInitializationException: Exception during pool initialization
at com.zaxxer.hikari.pool.BaseHikariPool.initializeConnections(BaseHikariPool.java:544)
at com.zaxxer.hikari.pool.BaseHikariPool.<init>(BaseHikariPool.java:171)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:60)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:48)
.....
Caused by: java.sql.SQLException: Access denied for user 'admin1'#'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3835)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3771)
I tried running gradlew clean build -Dspring.profiles.active=qa with application-qa.properties in the src/main/resources/ that have qa db settings. The build still failed with same exception.
I have two options.
run the build skipping datasource bean creation. I still need my units tests to be run since they don't rely on datasource
or pass the right settings to gradle build so that application context is created.
I prefer second option to get it working

If your requirement is that you control this externally (i.e., via the command line when launching Gradle), you can then modify your Gradle test task configuration as follows.
test {
systemProperty("spring.profiles.active", project.properties.get("springProfiles"))
// ...
}
And then you can set a value for springProfiles like this: gradlew clean build -PspringProfiles=ci (where ci is the name of the profile you want active on the CI server).
The above will make spring.profiles.active available as a JVM system property for your tests; however, you'd still need to set the active profiles for the Spring TestContext Framework.
To do that, you need to annotate your test class with #ActiveProfiles, but instead of passing in static profiles you'd need to implement a custom ActiveProfilesResolver and register it via #ActiveProfiles(resolver = MyCustomResolver.class). Your customer resolver could then read then simply return the value of the spring.profiles.active system property.
Another option is to implement a custom ApplicationContextInitializer that programmatically sets the active profiles (similar to the custom ActiveProfilesResolver). You can configure one of those via #SpringApplicationConfiguration(initializers = MyCustomInitializer.class).
And yet another option would be to programmatically set the active profiles directly in your SpringApplication -- for example, based on a system property or environment variable.
So, you have several options.

Related

How to solve 'Cannot find contract attachments' exception in Corda 4 upgrade

I upgraded to Corda 4 and now I'm getting the following exception when running my flow tests:
net.corda.core.transactions.MissingContractAttachments: Cannot find contract attachments for my.package.Contractnull
This is part of the code that I have in the mock network setup:
fun setup() {
network = MockNetwork(MockNetworkParameters(cordappsForAllNodes = listOf(
cordappWithPackages("my.package"),
enclosedCordapp()
))) ... }
Any ideas on what I'm missing?
I had the same issue when running one of my flows and the problem was with the contract ID.
It was with a different name from the class.
class YourAwesomeContract : Contract {
companion object {
// Used to identify our contract when building a transaction.
const val ID = "markets.imperium.contracts.NotSoAwesomeId"
}
...
}
Have you got multiple JARs with the my.package root namespace? The MockNetwork searches for a single jar with that namespace - it could be that there are multiples and it is picking up the wrong one. You need to specify a package namespace that identifies the JAR you want to include uniquely.

Definine a synthetic service in Symfony 4.1 doesn't work from within a bundle

I am creating a Symfony Bundle that defines a synthetic service:
my_alias:
public: true
synthetic: true
After installing the bundle, the application's console command cache:clear always fails with the error:
[Symfony\Component\DependencyInjection\Exception\RuntimeException]
Invalid service "my_alias": class "" does not exist.
If I create the same alias inside the actual framework, this error does not turn up.
Is this a bug, or am I doing something wrong?
When you clear the cache the kernel is recompiled and the container will not figure out your service that is not injected to the container, that's why you need to inject it under your Kernel class:
if (!$container->hasDefinition('my_alias')) {
$container->set('my_alias', new SyntheticService());
}

Unit testing a symfony service class with phpunit

I have a basic class GenericHelper.php in directory Foo/BarBundle/Helper
I registered it as a service in Foo/BarBundle/Resources/config/services.yml:
parameters:
generic_helper.class: Foo\BarBundle\Helper\GenericHelper
services:
generic_helper:
class: %generic_helper.class%
and I'm able to access it in a command by doing the following:
$helper = $this->getContainer()->get('generic_helper');
Now, I'd like to unit test that class with PHPUnit; I have the following code (similar to http://symfony.com/doc/2.0/book/testing.html#unit-tests):
namespace Foo\BarBundle\Tests\Helper;
use Foo\BarBundle\Helper\GenericHelper;
class GenericHelperTest extends \PHPUnit_Framework_TestCase {
public function testSomeMethod() {
$helper = new GenericHelper(); //line 10
$this->assertEquals($helper->someMethod(), SOME_RESULT);
}
}
Running PHPUnit results in the following error:
PHP Fatal error: Class 'Foo\BarBundle\Helper\GenericHelper' not found in /DIR/src/Foo/BarBundle/Tests/Helper/GenericHelperTest.php on line 10
Grepping for 'GenericHelper' only yields a few results:
the Class itself and the Test class
the services.yml file
appDevDebugProjectContainer files in app/cache/dev/, which have all the service getters
Question(s):
Does Symfony prevent PHPUnit from directly constructing a service class?
Is there a way to do this without creating a Symfony Container then accessing the service (as done here: Access Symfony 2 container via Unit test?)? I mean, it's still just a basic class...
Running phpunit with the -c flag pointing to the directory containing the phpunit.xml.dist file solved the issue. Doing this includes bootstrap.php.cache and therefore the autoloading stuff necessary.

Ant: Not finding my #ContextConfiguration

We have a Spring 3 MVC application and JUnit test cases for spring controllers. The Junit version is 4.8.1 which supports ContextConfiguration annotation.
Here is how I am adding context configuration in my test stub
#ContextConfiguration(locations = "file:WebContent/WEB-INF/myappconfig.xml")
I am able to run the junits locally, but when I am trying to run this with my ant build script, it throws an error java.lang.IllegalStateException: Failed to load ApplicationContext
I tried to set classpath element to the WebContent, then upto web-inf, nothing works out.
i'm using
#ContextConfiguration({ "classpath*:application-test.xml" })
and my application-test.xml resides under main/resources

seam solder (former weld-extensions project) is not initialized

I want to use logger in my java web application.
I'm using JBossAS 6.0.0.final, cdi (weld), jsf ... etc. Seam solder proposes to use an abstract logger is not tying to a concrete implementation (slf4j, log4j, etc) using jboss-logging api.
In order to get this logger in your code will need to write
# Inject
org.jboss.logging.Logger log
seam-solder.jar has the producer for this logger.
package org.jboss.seam.solder.log;
...
class LoggerProducers
{
# Produces
org.jboss.logging.Logger produceLog (InjectionPoint injectionPoint) {}
}
When I deploying my application, I get an error
15:51:18,300 ERROR [org.jboss.kernel.plugins.dependency.AbstractKernelController] Error installing to Start: name=vfs:///C:/Java/jboss-6.0.0.Final/server/default/deploy/kamis-web-client.5.0.0-SNAPSHOT.ear_WeldBootstrapBean state=Create: org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [Logger] with qualifiers [#Default] at injection point [[field] #Inject private ru.kamis.suite.webclient.web.breadcrumbs.BreadcrumbsManager.log]
This is due to the seam-solder.jar has not META-INF/beans.xml file, and it is necessary for cdi container.
If to add beans.xml file in seam-solder.jar manually, then the application works WELL.
How to do without hacks?
To build my application I use maven, so my solution is not comfortable and NOT fine.
PS: Former weld-extensions project contained META-INF/beans.xml file in jar.
with seam-solder-3.0.0.Beta1 there should be no need to modify the jar

Resources