CloudFoundry MySQL Java configuration - mysql

I have a Spring MVC app that is running fine on local tomcat etc. Its a Spring 3.1 MVC/Hibernate app.
I am using (where possible) pure Java #Configuration for the app - and I am now trying to deploy the app to CloudFoundry (via STS), but I am struggling to get the MySql db configured (from memory, with xml config you dont need to do anything and Spring/CloudFoundry auto-injects the required user/password etc, but its been a while since I deployed anything to CF).
I have tried both of the following configurations:
#Bean
public BasicDataSource dataSource() throws PropertyVetoException {
//CloudFoundry config
final CloudEnvironment cloudEnvironment = new CloudEnvironment();
final List<MysqlServiceInfo> mysqlServices = cloudEnvironment.getServiceInfos(MysqlServiceInfo.class);
final MysqlServiceInfo serviceInfo = mysqlServices.get(0);
BasicDataSource bean = new BasicDataSource();
bean.setDriverClassName("com.mysql.jdbc.Driver");
bean.setUrl(serviceInfo.getUrl());
bean.setUsername(serviceInfo.getUserName());
bean.setPassword(serviceInfo.getPassword());
return bean;
}
The above failed on out of bounds on the .get(0) line of the mysqlServices. This was based on the answer suggested here.
I also tried leaving the datasource as what it runs on as local to see if the properties just get injected, but no luck there either. (the below was tried with the values as per the Spring sample code here, and also using property placeholders from my db.connection props file)
#Bean
public BasicDataSource dataSource() throws PropertyVetoException {
BasicDataSource bean = new BasicDataSource();
bean.setDriverClassName("com.mysql.jdbc.Driver");
bean.setUrl("");
bean.setUsername("spring");
bean.setPassword("spring");
return bean;
}
Edit
I have also used the getServiceInfo(String, Class) method passing in the name of the MySql service that I have created and bound to the application, but that just NPEs similar to the getServiceInfos(..) approach

Ok, this was just a stupid mistake - when I deployed the app via STS I had selected Java Web app rather than the "Spring" type. Not sure why that would make the CloudEnvironment properties not be available (I was under the impression that approach was the common method to inject the details in non-Spring apps) - but re-deploying it to the server as a Spring app resolved the probs!

Related

Spring Boot 2 Upgrade Issue - Error Page Always returns HTML

I have recently upgraded our project to Spring Boot 2. The App is just a Rest API. And now all our 400 and 500 responses are being returned as html instead of json.
I am defining a custom ErrorAttributes, just like the docs say to do.
#Configuration
public class WebConfig implements WebMvcConfigurer {
...
#Bean
public ErrorAttributes errorAttributes() {
return new DefaultErrorAttributes() {
#Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest,
boolean includeStackTrace) {
Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, true);
return errorAttributes;
}
};
}
...
I would like to debug this issue locally, but I cannot find in the code where Spring Boot makes this decision to add a JSON Response for errors. The docs here: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-error-handling says:
For machine clients, it produces a JSON response with details of the error, the HTTP status, and the exception message.
I'm thinking that I must have a Bean defined locally that is causing this not to be configured correctly in the Spring Boot Auto configuration.
I finally figured this out. I think there were some changes in Spring Security 4 to Spring Security 5 that was causing a NPE early in the filter chain for our app. Also, compounding the difficulty of debugging the issue is that with the Spring Boot upgrade, the /error route was forced to be authenticated.
I ended up fixing the NPE, allowing for everyone to see the /error mapping and then making sure ErrorMvcAutoConfiguration was being initialized correctly. All is working now.

Injecting DbContext into FileProvider in ASP.NET Core

I am trying to load some of the views from the database as described in here. So I want to use EF Core in the File provider.
RazorViewEngineOptions has a FileProviders property that you can add your file provider to. The problem is that you have to give it an instace of the file provider. So you'll need to instantiate all of the file providers' dependencies right there in Startup's ConfigureServices method.
Currently I inject an instance of IServiceProvider into the Configure method of Startup. Then I store the instance in a field (called _serviceProvider):
IServiceProvider _serviceProvider;
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider provider)
{
_serviceProvider = provider;
...
}
Then in ConfigureServices I use that field to instanciate the UIDbContext.
services.Configure<RazorViewEngineOptions>(options =>
{
var fileProvider = new DbFileProvider(_serviceProvider.GetService<UIDbContext>());
options.FileProviders.Add(fileProvider);
});
Is there any better way to be able to inject the UIDbContext into the DbFileProvider constructor Or any way to instantiate a UIDbContext inside DbFileProvider without IServiceProvider?
You don't want to use DbContext as a file provider source the way you did.
DbContext isn't thread-safe, so it won't work when you have one single DbContext instance for the whole provider, because multiple requests could call the DbContext and it's operation more than once at the same time, resulting in exception when trying to execute 2 queries in parallel.
You'd have to instantiate a connection (like in the linked article) or DbContext per IFileInfo/IDirectoryContents instance.
DbContextOptions<UIDbContext> should be registered as singleton, so you can resolve it onceinside Configure` w/o any issues and pass it to your provider.
Alternatively you can also call DbContextOptionsBuilder and build/construct a DbContextOptions<T>, but then you have to repeat the configuration for you did inside AddDbContext (i.e. .UseSqlServer()).
However it can be useful, as it allows you to set different settings (i.e. changing the way how includes, errors etc. are logged).

ConnectionFactory exception Camel testing JMS

I'm doing my first steps with Camel and currently working on writing a simple junit test using jms as a transport.
Here is a code I wrote:
public class FirstMockTest extends CamelTestSupport {
#Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
from("jms:topic:quote")
.to("mock:quote");
}
};
}
#Test
public void testMessageCount() throws InterruptedException {
MockEndpoint mockEndpoint = getMockEndpoint("mock:quote");
mockEndpoint.setExpectedMessageCount(1);
template.sendBody("jms:topic:quote", "Camel rocks");
mockEndpoint.assertIsSatisfied();
}
}
Because of missing connectionFactory I got the following exception:
org.apache.camel.FailedToCreateRouteException: Failed to create route route1: Route(route1)[[From[jms:topic:quote]] -> [To[mock:quote]]] because of connectionFactory must be specified
I'm able to fix it adding the following lines to my route:
ConnectionFactory connectionFactory =
new ActiveMQConnectionFactory("vm://localhost?roker.persistent=false");
context.addComponent("jms", JmsComponent.jmsComponent(connectionFactory));
But I don't like I'm adding some components to my context inside the route. Also, If i want to have another route I will need to do it again.
Obviously, there should be another way to tell my test about connection factory.
Thank you in advance!
It's a good idea to define the JMS connection factory outside of your Camel context and, if possible, reuse it. How to do that depends on your component model / execution environment.
If you're using a Java SE version that supports CDI, that would be an obvious choice. You'd define your JMS connection factory as a named component once and inject it everywhere you need it. Have a look at http://camel.apache.org/cdi.html and for testing support at http://camel.apache.org/cdi-testing.html
If you're using Spring, define your connection factory as a spring bean and inject it wherever you need it.
If you're using Java EE on an application server, you'd usually define the JMS connection factory using the mechanisms of that app server. You'd then look up the JMS connection factory using JNDI.
If you're running in an OSGi container, you should define the JMS connection factory in its own bundle and export it as an OSGi service. In the bundle of your Camel context, import that OSGi servide and inject it into the Camel context.
In all above cases you should consider using a pooled JMS connection factory.
For CDI, Spring and OSGi, have a look at: http://activemq.apache.org/maven/5.14.5/apidocs/org/apache/activemq/jms/pool/PooledConnectionFactory.html
For Java EE the way how to set pooling parameters depends on your app server.
Note of caution: for Java SE CDI and Spring there should be only one Camel context per application (you can have many routes, though). So if the JMS connection factory is only used in that one Camel context, there is not much reuse. Despite that I still think it's preferable to define the JMS connection outside of the Camel context in a separate component. It's, well, cleaner.
Since you are writing a junit you can avoid creating a ConnectionFactory if you stub the jms endpoint. You can name the endpoint as stub:jms:topic:quote. Have a look at sample example at link https://github.com/camelinaction/camelinaction2/blob/master/chapter9/mock/src/test/java/camelinaction/FirstMockTest.java

MySql pooled datasource in standalone JAVA app (no J2EE container, no JNDI, no TOMCAT etc.)

I've been reading dozens of topics here with no real enlightment: I'm running a standalone java app, on a Synology NAS with Java 8. I also installed MariaDB on the same NAS. So everything is local.
I am able to setup a datasource and get a connection, but I would like to be able to access it in any instance of any of my classes / threads for connection pooling. Everything seem to show that I would need JNDI. But I don't have a J2EE container and this seems overkill for my need. Idem for developping my own implementation of JNDI.
I've seen replies to similar questions where people suggest C3PO. But this is just another datasource implementation. I don't think it solves the standalone app issue with no way to access datasource from anywhere in the code :
How to retrieve DB connection using DataSource without JNDI?
Is there another way to share a datasource across java threads ?
Can I pass the Datasource instance as a parameter to each thread, so
they can get a connection when they need ?
Should I assign a given connection to each thread - also passed as a
parameter ? and in this case, never really close it properly ?
Or should I really install something like tomcat, jboss, jetty ? are
they equivalent ? Is there a super light J2EE container that could
provide JNDI ?
Thanks
Vincent
You could use the singleton pattern, like this for example:
public class DataSourceFactory {
private static DataSource instance = null;
private DataSourceFactory() { }
public static synchronized DataSource getDataSource(){
if(instance == null){
instance = // initialize your datasource
}
return instance;
}
}
Then any from any thread you can call DataSourceFactory.getDataSource() to get a reference to your DataSource object.

webapi - db Migrations

I tried to run my code after adding two new classes to the ef using web api 2, and i got the following error :
The model backing the 'AuthContext' context has changed since the database was created.
When I tried to do "Enable-Migrations", i got the error :
No MigrationSqlGenerator found for provider 'MySql.Data.MySqlClient'.
I found a solution but it's a solution for MVC which is the following:
public Configuration()
{
AutomaticMigrationsEnabled = false;
// register mysql code generator
SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
}
The thing is I can't find where to put this piece of code in my web api project.
The solution to webapi is the same as a web MVC project.
First, you run command "enable-migrations" in the Package manage console. The the Migrations folder will be created in your project structure where you can find the Configuration.cs file.
Then inside the Configuration.cs file, add
// register mysql code generator
SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
into the constructor just below the line
AutomaticMigrationsEnabled = false;
That's all.