How to run external war file with embedded tomcat of spring boot with gradle? - spring-boot-gradle-plugin

I am trying to deploy external war file into embedded tomcat of spring boot.I added gradle dependencies in the format of .war file and i want run this war with by spring boot app , but not running please anyone can help me out.

Just try with this approach. add this code block in your spring boot application.
your war file must be placed in a src/main/resources directory.
#Bean
public EmbeddedServletContainerFactory servletContainerFactory() {
return new TomcatEmbeddedServletContainerFactory() {
#Override
protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) {
new File(tomcat.getServer().getCatalinaBase(), "webapps").mkdirs();
try {
tomcat.addWebapp("/cms", new ClassPathResource("cms.war").getFile().toString());
} catch (Exception ex) {
throw new IllegalStateException("Failed to add webapp",ex);
}
return super.getTomcatEmbeddedServletContainer(tomcat);
}
};
}
-> change the base directory in the application.properties as
server.tomcat.basedir=temp-server

A few classes have changed in Spring Boot 2 and hence you'll have to do:
#Bean
public ServletWebServerFactory servletContainer() {
return new TomcatServletWebServerFactory() {
protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
new File(tomcat.getServer().getCatalinaBase(), "webapps").mkdirs();
try {
tomcat.addWebapp("/cms", new ClassPathResource("cms.war").getFile().toString());
} catch (Exception ex) {
throw new IllegalStateException("Failed to add webapp", ex);
}
return super.getTomcatWebServer(tomcat);
}
};
}

Related

Bind authentication with Oracle in CAS

I'm setting up CAS 5.3 to do Bind authentication agains an Oracle database. But I don't know how to setup a OracleDataSource while using WAR Overlay method. Any guidance would be appreciated, thanks.
Just setting up Driver and URL doesn't appear to work. It seems the HikariDataSource is used by default, and it doesn't implement the required getConnection(String username, String password).
#SneakyThrows
public static DataSource newDataSource(final AbstractJpaProperties jpaProperties) {
final String dataSourceName = jpaProperties.getDataSourceName();
final boolean proxyDataSource = jpaProperties.isDataSourceProxy();
if (StringUtils.isNotBlank(dataSourceName)) {
try {
final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
dsLookup.setResourceRef(false);
final DataSource containerDataSource = dsLookup.getDataSource(dataSourceName);
if (!proxyDataSource) {
return containerDataSource;
}
return new DataSourceProxy(containerDataSource);
} catch (final DataSourceLookupFailureException e) {
LOGGER.warn("Lookup of datasource [{}] failed due to {} falling back to configuration via JPA properties.", dataSourceName, e.getMessage());
}
}
final HikariDataSource bean = new HikariDataSource();
if (StringUtils.isNotBlank(jpaProperties.getDriverClass())) {
bean.setDriverClassName(jpaProperties.getDriverClass());
}
bean.setJdbcUrl(jpaProperties.getUrl());
bean.setUsername(jpaProperties.getUser());
bean.setPassword(jpaProperties.getPassword());
bean.setLoginTimeout((int) Beans.newDuration(jpaProperties.getPool().getMaxWait()).getSeconds());
bean.setMaximumPoolSize(jpaProperties.getPool().getMaxSize());
bean.setMinimumIdle(jpaProperties.getPool().getMinSize());
bean.setIdleTimeout((int) Beans.newDuration(jpaProperties.getIdleTimeout()).toMillis());
bean.setLeakDetectionThreshold(jpaProperties.getLeakThreshold());
bean.setInitializationFailTimeout(jpaProperties.getFailFastTimeout());
bean.setIsolateInternalQueries(jpaProperties.isIsolateInternalQueries());
bean.setConnectionTestQuery(jpaProperties.getHealthQuery());
bean.setAllowPoolSuspension(jpaProperties.getPool().isSuspension());
bean.setAutoCommit(jpaProperties.isAutocommit());
bean.setValidationTimeout(jpaProperties.getPool().getTimeoutMillis());
return bean;
}
I would require that the bean created above, would be a OracleDataSource instance.

How to correctly load Firebase ServiceAccount json resource with Spring MVC?

I'm trying to connect my Spring MVC (not Spring Boot) application to Firebase. My application's folder structure looks like this:
folder structure
The problem is that I don't know where to place the api key json file, how to load the resource, and the correct order of the method calls.
I tried loading the resource the way shown below. Before that I also tried using ClassLoader to load it from the WEB-INF folder and it worked, but changed the code and kept receiving NullPointer Exception (why not FileNotFound Exception?) for the InputStream and couldn't restore the previous state.
With the current state I keep receiving FileNotFound Exception as I'm am not able to load the resource no matter how much I googled "Spring MVC load resource" and as I checked the debugger the service account's "init" method with #PostConstruct isn't running at starting the server.
I understand that I should be able to load the resource and call the "init" method in order to make it work. (I suppose it's enough to call it once after creating the bean and before using firebase methods) But I just couldn't come up with a working implementation.
I used examples from here:
https://github.com/savicprvoslav/Spring-Boot-starter
(Bottom of the Page)
My Controller Class:
#Controller
#RequestMapping("/firebase")
public class FirebaseController {
#Autowired
private FirebaseService firebaseService;
#GetMapping(value="/upload/maincategories")
public void uploadMainRecordCategories() {
firebaseService.uploadMainRecordCategories();
}
My Service Class:
#Service
public class FirebaseServiceBean implements FirebaseService {
#Value("/api.json")
Resource apiKey;
#Override
public void uploadMainRecordCategories() {
// do something
}
#PostConstruct
public void init() {
try (InputStream serviceAccount = apiKey.getInputStream()) {
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl(FirebaseStringValue.DB_URL).build();
FirebaseApp.initializeApp(options);
} catch (IOException e) {
e.printStackTrace();
}
}
}
how about saving value in a spring property and using #Value("${firebase.apiKey}")?
Alternatively, save path to file in property and reference that in #Value()
#Value("${service.account.path}")
private String serviceAccountPath;
In application.properties:
service.account.path = /path/to/service-account.json
then config code:
private String getAccessToken() throws IOException {
GoogleCredential googleCredential = GoogleCredential
.fromStream(getServiceAccountInputStream())
.createScoped(Collections.singletonList("https://www.googleapis.com/auth/firebase.messaging"));
googleCredential.refreshToken();
return googleCredential.getAccessToken();
}
private InputStream getServiceAccountInputStream() {
File file = new File(serviceAccountPath);
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) {
throw new RuntimeException("Couldn't find service-account.json");
}
}

How to set up JDBC Connection Poll to mySql on Jetty server in IntelliJ Vaadin Project

Pls explain me this like i am a retard kid. I am stuck at this point for three days. There so so much documentation for multiple use of JDBC, but when i do it one it won't work for me.
So I build project whit maven vaadin build:
.
Now I need to connect to my MySQL database. I will need to push data once per day. Just for store. I need one simple solution which will be good for my use.
This code work for me all ready but now i am trying whit Pool:
public class Povezavapool {
private static final BasicDataSource dataSource = new BasicDataSource();
static {
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/patrioti");
dataSource.setUsername("root");
dataSource.setPassword("1234567890");
}
private Povezavapool() {
//
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
But now i trying to do smt like this because I read it it is faster and better. I have no idea how to set up it.
public static JDBCConnectionPool getConnectionPool() {
SimpleJDBCConnectionPool pool = null;
try {
pool = new SimpleJDBCConnectionPool("com.mysql.jdbc.Driver",
"jdbc:mysql://localhost:3306/patrioti", "rooot",
"1234567890");
} catch (SQLException e) {
e.printStackTrace();
}
return pool;
}

How to setExceptionListener in Jruby

I'm new to Jruby and currently working on an app needs to convert Java code to Jruby for JMS client, here is the code in java:
connection.setExceptionListener(ExceptionListener.new() {
public void onException (JMSException ex) {
connection = null;
}
})
Can anyone give me some idea how to convert this to Jruby? Thanks.
first of all that is not valid Java code maybe this is :
connection.setExceptionListener(new ExceptionListener() {
public void onException(JMSException ex) {
connection = null;
}
})
... depends on the ExceptionListener lets assume its a functional-interface with a single onException method in which case you can use the (magical) block-to-interface conversion :
connection.setExceptionListener { |ex| connection = nil }

File Not Found Exception Visual Studio 2015

I am getting file not found error though I have the needed file inside the project directory.There are no compilation errors.
Here is my startup.cs class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
namespace OdeToFood
{
public class Startup
{
public Startup()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("config.json");
Configuration = builder.Build();
}
public IConfiguration Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
var message = Configuration["greeting"];
await context.Response.WriteAsync(message);
});
}
}
}
And this is the error message I get when I build it.
System.IO.FileNotFoundException: The configuration file 'config.json' was not found and is not optional.
at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)
at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
at OdeToFood.Startup..ctor()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.AspNetCore.Hosting.Internal.StartupLoader.LoadMethods(IServiceProvider services, Type startupType, String environmentName)
at Microsoft.AspNetCore.Hosting.WebHostBuilderExtensions.<>c__DisplayClass1_0.b__1(IServiceProvider sp)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureStartup()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
Screenshot showing the file present
How should I rectify this?
Thanks
I think you forget to use Server.MapPath function.
You can edit your Constructor with following code :
public Startup()
{
var builder = new ConfigurationBuilder()
.AddJsonFile(HttpContext.Current.Server.MapPath("~/config.json"));
Configuration = builder.Build();
}
Hope it helps you :)