Is there a way to copy a jar in the karaf lib/ext folder while starting the pax-exam
#Configuration
public static Option[] configuration() throws Exception {
return new Option[] {
karafDistributionConfiguration().frameworkUrl(maven().groupId("org.apache.karaf").artifactId("apache-karaf")
.type("zip").version("4.0.1"))
.unpackDirectory(new File("target/paxexam/unpack/"))
.useDeployFolder(false),
KarafDistributionOption.debugConfiguration("8898", true),
configureConsole().ignoreLocalConsole(),
logLevel(LogLevel.INFO),
keepRuntimeFolder(),
};
}
I have found the solution. The below code will fix the issue
#Configuration
public static Option[] configuration() throws Exception {
MavenUrlReference oracleLib = maven()
.groupId("com.oracle")
.artifactId("ojdbc6")
.version("11.2.0")
.type("jar");
return new Option[] {
karafDistributionConfiguration().frameworkUrl(maven().groupId("org.apache.karaf").artifactId("apache-karaf")
.type("zip").version("4.0.1"))
.unpackDirectory(new File("target/paxexam/unpack/"))
.useDeployFolder(false),
KarafDistributionOption.debugConfiguration("8898", true),
bootClasspathLibrary(oracleLib),
configureConsole().ignoreLocalConsole(),
logLevel(LogLevel.INFO),
keepRuntimeFolder(),
};
}
Related
I am starting to write an application in spring boot and below is how my package structure looks:
com.practice.spring.project.helloworld.HelloworldApplication.java
com.practice.spring.project.repository.EmployeeRepository.java
com.practice.spring.project.model.Employee.java
Below is how i had my application startup successfully,
#SpringBootApplication
#ComponentScan(basePackages = "com.practice.spring.project.DB", basePackageClasses = InitDatabase.class)
#EnableJpaRepositories(basePackages = "com.practice.spring.project.repository" , basePackageClasses = EmployeeRepository.class)
public class HelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloworldApplication.class, args);
}
#Bean
public CommandLineRunner run(EmployeeRepository employeeRepository) throws Exception {
return (args) -> {
System.out.println("Calling it after the application context is all loaded up");
employeeRepository.save(new Employee("Ashwin", "Architect"));
};
}
}
My question is should I have to specify the base-packages & baseClasses for every class I add ? It would be tough if have 10 packages having 10 different classes.
Am sure there should be an easier way to scan and instantiate classes in different package.
Figured out a way - set the basePackages to com.practice.spring.project.*
#ComponentScan(basePackages = "com.practice.spring.project.*")
I'm trying to use Tuckey as urlRewrite in my spring boot project but i get error below registering Tuckey filter:
org.tuckey.web.filters.urlrewrite.UrlRewriteFilter ERROR: unable to find urlrewrite conf file at `urlrewrite.xml` even i have `urlrewrite.xml` file under resources.
I register Tucky filter like below in my Configuration class:
#Bean
public FilterRegistrationBean urlRewriteFilterRegistration() throws IOException {
log.info("UrlRewriteFilter registered!");
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new UrlRewriteFilter());
registration.setName("UrlRewriteFilter");
List<String> urlPatterns = new ArrayList<>();
urlPatterns.add("/urlmap");
registration.setUrlPatterns(urlPatterns);
registration.getInitParameters().put("confPath","/urlrewrite.xml");
return registration;
}
Even i used to register Filter like below:
FilterRegistration.Dynamic urlRewriteFilter = servletContext.addFilter("urlRewriteFilter", new UrlRewriteFilter());
urlRewriteFilter.setInitParameter("confPath", "urlrewrite.xml");
urlRewriteFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, "/*");
it was working in none boot version!
what is wrong with my configuration.
Had the same issue recently.
Found this post with an answer:
Spring boot cannot find urlrewrite.xml inside jar file
TL;DR: Created a class extending UrlRewriteFilter and overwrote the loadUrlRewriterMethod to allow loading a the configuration as a org.springframework.core.io.Resource
Please adapt to your needs:
public class BootCompliantUrlRewriteFilter extends UrlRewriteFilter {
private Resource resource;
public BootCompliantUrlRewriteFilter(Resource config){
this.resource = config;
}
//Override the loadUrlRewriter method, and write your own implementation
#Override
protected void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {
try {
//Create a UrlRewrite Conf object with the injected resource
Conf conf = new Conf(filterConfig.getServletContext(), resource.getInputStream(), resource.getFilename(), "##yourOwnSystemId##");
checkConf(conf);
} catch (IOException ex) {
throw new ServletException("Unable to load URL rewrite configuration file from " + this.resource, ex);
}
}
}
and in the application class:
public static final String REWRITE_FILTER_NAME = "rewriteFilter";
public static final String REWRITE_FILTER_CONF_PATH = "urlrewrite.xml";
#Bean
public FilterRegistrationBean rewriteFilterConfig() {
FilterRegistrationBean reg = new FilterRegistrationBean();
reg.setName(REWRITE_FILTER_NAME);
reg.setFilter(new BootCompliantUrlRewriteFilter(new ClassPathResource(REWRITE_FILTER_CONF_PATH)));
//reg.addInitParameter("confPath", REWRITE_FILTER_CONF_PATH);
reg.addInitParameter("confReloadCheckInterval", "-1");
reg.addInitParameter("statusPath", "/redirect");
reg.addInitParameter("statusEnabledOnHosts", "*");
reg.addInitParameter("logLevel", "WARN");
return reg;
}
When running test-app in grails 3.0, or run-app, grails runs its own version of the embedded Tomcat server. I was able to conclude this from the following link: https://roshandawrani.wordpress.com/2011/03/13/grails-tip-configuring-embedded-tomcat-instance-used-in-developmenttest-env/
However, the context.xml and server.xml files are precompiled with the pulled down libraries. When creating a grails app from scratch, I cannot find either of there two files. Same is true for config.groovy, as it is located within an external library.
I am trying to inject JNDI resources, into the container, so that I can invoke them. Something like this:
<Resource name="myDatasourceName" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="password" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/my_db_name"/>
In the first link, the authors provide a way to do it in a scripts/_Events.groovy directory, but I do not have this either.
UPDATE 1: Non-working code
import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration
import org.apache.catalina.Context
import org.apache.catalina.startup.Tomcat
import org.apache.tomcat.util.descriptor.web.ContextResource
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory
import org.springframework.context.annotation.Bean
#SpringBootApplication
class Application extends GrailsAutoConfiguration {
static void main(String[] args) {
GrailsApp.run(Application, args)
}
#Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
return new TomcatEmbeddedServletContainerFactory() {
#Override
protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
Tomcat tomcat) {
tomcat.enableNaming();
return super.getTomcatEmbeddedServletContainer(tomcat);
}
#Override
protected void postProcessContext(Context context) {
context.getNamingResources().addResource(preconfigureDbResource("oneSource", "127.0.0.1"))
context.getNamingResources().addResource(preconfigureDbResource("nextSource", "127.0.0.1"))
}
}
}
private ContextResource preconfigureDbResource(String name, String ip) {
ContextResource resource = new ContextResource()
resource.setType("javax.sql.DataSource")
resource.setName("jdbc/" + name)
resource.setProperty("url", "jdbc:oracle:thin:#" + ip + ":1521:ucop")
resource.setProperty("driverClassName", "oracle.jdbc.driver.OracleDriver")
resource.setProperty("username", "coolio")
resource.setProperty("password", "password")
resource.setProperty("auth", "Container")
resource.setProperty("maxTotal", "100")
resource.setProperty("maxIdle", "30")
resource.setProperty("maxWaitMillis", "10000")
return resource;
}
}
I am calling this source like this in my service file:
public DataSource getOneSource() {
Context context = (Context) new InitialContext().lookup("java:/comp/env")
oneSource= (DataSource) context.lookup("jdbc/oneSource")
return oneSource
}
But I am getting an error stating:
javax.naming.NameNotFoundException: Name [comp/env] is not bound in this Context. Unable to find [comp].
Has anyone done this before? I would not be surprised if there is an extra thread that is overwriting the context.
In Grails 3, you do it like this: SampleTomcatJndiApplication
Typically, in Grails web applications, this is in /grails-app/init/Application.groovy
(In my case, I commented out the jndiDataSource() part and just used postProcessContext().)
Source: Graeme Rocher
The solution to this issue is addressed in two steps. First, I had to use the child approach to setting the right context, found in this question. Setting the right context in embedded Tomcat
As imagined, The only change I then had to make was to the getTomcatEmbeddedServletContainer method. I have edited the original to look like this:
#Override
protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) {
tomcat.enableNaming();
TomcatEmbeddedServletContainer container =
super.getTomcatEmbeddedServletContainer(tomcat);
for (Container child: container.getTomcat().getHost().findChildren()) {
if (child instanceof Context) {
ClassLoader contextClassLoader =((Context)child).getLoader().getClassLoader();
Thread.currentThread().setContextClassLoader(contextClassLoader);
break;
}
}
return container;
}
Next, I had to edit the gradle build file, to include the dbcp BasicDataSource Dependency. My gradle build file now contains:
dependencies {
// Embedded tomcat dependencies
compile "org.apache.tomcat:tomcat-dbcp:9.0.0.M1"
}
Below is the code for my camel exec component. This is one of my first times using Camel and I'm just trying to get camel exec to execute a batch file for me. Can anyone tell me how I misconfigured the workingDir parameter? As part of the error I am getting that 1 parameters couldn't be set. If it matters I'm working on windows.
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
/**
* A Camel Java DSL Router
*/
public class MyClass {
public static void main(String args[]) throws Exception {
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
public void configure() {
from("direct:exec").to("exec:mybat.bat?workingDir=C:/Users/userName/Desktop");
}
});
context.start();
Thread.sleep(10000);
context.stop();
}
}
EgoKilla, below is the working code
public class MyClass {
public static void main(String args[]) throws Exception {
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
public void configure() {
from("timer:foo?period=5000").to("exec:D:/jboss/test.bat?");
}
});
context.start();
Thread.sleep(10000);
context.stop();
}
}
Here for every 5000 msec, camel executes the batch file. I give the fully qualified path of the bat file.
Working directory means, the directory which the command should be executed. ex: if you trying to create a file using batch file, that file will be created in the working directory specified.
Hope it helps!!
I have a very simple Spring Boot application with classes detailed below.
My problem is with the application.properties file and how they get auto-configured. I'm trying to get Groovy Templates to update in dev by setting 'spring.groovy.template.cache: false', however this is not working. I added two more properties to see if the application.properties file was being read. The 'logging.level.org.springframework.web: ERROR' still results in INFO level messages printed to the console. However, some.prop is read correctly into the MyBean class on application start.
Is there a configuration declaration I'm missing for these properties?
src/main/resources/application.properties:
spring.groovy.template.cache: false
logging.level.org.springframework.web: ERROR
some.prop: bob
src/main/java/sample/MyBean.java:
#Component
public class MyBean {
#Value("${some.prop}")
private String prop;
public MyBean() {}
#PostConstruct
public void init() {
System.out.println("================== " + prop + "================== ");
}
}
and src/main/java/sample/Application.java:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
and src/main/java/sample/com/example/MainController.java
#Controller
public class MainController {
#RequestMapping(value="/login", method = RequestMethod.GET)
public ModelAndView risk(#RequestParam Optional<String> error) {
return new ModelAndView("views/login", "error", error);
}
}
It seems you missing scanned your package "sample". Please make sure that you have scanned it.
#ComponentScan({
"sample" })
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Also, your application.properties is right. No problem with it.
It appears the solution was much simpler than I thought:
gradle bootRun
should be used to hot reload templates
gradle run does not work (all compiled classes are just built in build/ )