I am trying to build a simple JSF web application using embedded Undertow server.
Gradle dependencies for the project:
dependencies {
compile group: 'io.undertow', name: 'undertow-core', version: '1.4.0.CR3'
compile group: 'io.undertow', name: 'undertow-servlet', version: '1.4.0.CR3'
compile group: 'javax', name: 'javaee-api', version: '7.0'
compile group: 'org.glassfish', name: 'javax.faces', version: '2.2.11'
}
Sample Undertow Server Code:
public class HelloWorldServer {
public static void main(final String[] args) throws ServletException {
DeploymentInfo servletContainer=Servlets.deployment()
.setClassLoader(HelloWorldServer.class.getClassLoader())
.setDeploymentName("helloWorld.war")
.setContextPath("")
.addServlet(Servlets.servlet("javax.faces.webapp.FacesServlet",FacesServlet.class)
.addMappings("/faces/*","/javax.faces.resource/*")
.setLoadOnStartup(1));
DeploymentManager manager=Servlets.defaultContainer().addDeployment(servletContainer);
manager.deploy();
HttpHandler servletHandler=manager.start();
PathHandler path = Handlers.path(Handlers.redirect(""))
.addPrefixPath("/", servletHandler);
Undertow server = Undertow.builder()
.addHttpListener(8080, "localhost")
.setHandler(path)
.build();
server.start();
}
}
When i start the server,following error comes:
Mar 07, 2017 6:04:49 PM javax.faces.FactoryFinder$FactoryManager copyInjectionProviderFromFacesContext
SEVERE: Unable to obtain InjectionProvider from init time FacesContext. Does this container implement the Mojarra Injection SPI?
Mar 07, 2017 6:04:49 PM javax.faces.FactoryFinder$FactoryManager getFactory
SEVERE: Application was not properly initialized at startup, could not find Factory: javax.faces.context.FacesContextFactory. Attempting to find backup.
Exception in thread "main" java.lang.IllegalStateException: Could not find backup for factory javax.faces.context.FacesContextFactory.
at javax.faces.FactoryFinder$FactoryManager.getFactory(FactoryFinder.java:1135)
at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:379)
at javax.faces.webapp.FacesServlet.init(FacesServlet.java:350)
at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:117)
at io.undertow.servlet.core.ManagedServlet$DefaultInstanceStrategy.start(ManagedServlet.java:239)
at io.undertow.servlet.core.ManagedServlet.createServlet(ManagedServlet.java:133)
at io.undertow.servlet.core.DeploymentManagerImpl.start(DeploymentManagerImpl.java:541)
at HelloWorldServer.main(HelloWorldServer.java:24)
Finally i found a solution.
For JSF bootstrap process we must add Two additional init parameter to Undertow DeploymentInfo class.
com.sun.faces.forceLoadConfiguration = TRUE
com.sun.faces.expressionFactory = com.sun.el.ExpressionFactoryImpl
Also we must add two more extra dependency other than JSF.
el-api
el-impl
Related
Just trying out micronaut with Spring capability, and can't get access to my /actuator endpoints Spring Boot v2.3.0 release and micronaut 2.0.0.M3
I created a basic micronaut project using the mn create-app xxx --lang groovy.
I have then added the spring dependencies and micronaut-spring and associated annotation processors.
My build.gradle now looks as follows
plugins {
id "groovy"
id "com.github.johnrengelman.shadow" version "5.2.0"
id "application"
id "net.ltgt.apt" version "0.21" //enables annotation preproccessing support
id "net.ltgt.apt-idea" version "0.21"
id "org.springframework.boot" version "2.3.0.RELEASE"
id "io.spring.dependency-management" version "1.0.9.RELEASE"
}
ext['groovy.version'] = '3.0.4'
version "0.1"
group "com.softwood"
repositories {
mavenCentral()
maven { url "https://jcenter.bintray.com" }
}
configurations {
// for dependencies that are needed for development only
developmentOnly
}
dependencies {
//annotation processors
annotationProcessor platform("io.micronaut:micronaut-bom:$micronautVersion")
annotationProcessor "io.micronaut.spring:micronaut-spring-boot-annotation"
annotationProcessor "io.micronaut.spring:micronaut-spring-web-annotation"
testAnnotationProcessor "io.micronaut.spring:micronaut-spring-web-annotation:2.0.1"
//latest groovy v3
implementation group: 'org.codehaus.groovy', name: 'groovy-all', version: '3.0.4' //, ext: 'pom'
//spring
compileOnly "io.micronaut.spring:micronaut-spring-annotation:2.0.1"
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-actuator")
implementation group: 'io.micronaut.spring', name: 'micronaut-spring-web', version: '2.0.1'
runtime ("io.micronaut.spring:micronaut-spring-boot:2.0.1")
compileOnly platform("io.micronaut:micronaut-bom:$micronautVersion")
compileOnly "io.micronaut:micronaut-inject-groovy"
implementation platform("io.micronaut:micronaut-bom:$micronautVersion")
implementation "io.micronaut:micronaut-runtime-groovy"
implementation "io.micronaut:micronaut-validation"
implementation "javax.annotation:javax.annotation-api"
implementation "io.micronaut:micronaut-http-server-netty"
implementation "io.micronaut:micronaut-http-client"
runtimeOnly "ch.qos.logback:logback-classic:1.2.3"
testCompileOnly platform("io.micronaut:micronaut-bom:$micronautVersion")
testImplementation platform("io.micronaut:micronaut-bom:$micronautVersion")
testImplementation("org.spockframework:spock-core:2.0-M2-groovy-3.0") {
exclude group: "org.codehaus.groovy", module: "groovy-all"
}
testImplementation "io.micronaut:micronaut-inject-groovy"
testImplementation "io.micronaut.test:micronaut-test-spock"
testImplementation "io.micronaut.test:micronaut-test-junit5"
}
test.classpath += configurations.developmentOnly
mainClassName = "com.softwood.Application"
//added - enable incremetal compile feature - can't enable with annotation processors !
/*tasks.withType(GroovyCompile).configureEach {
options.incremental = true
}*/
tasks.withType(GroovyCompile) {
groovyOptions.forkOptions.jvmArgs.add('-Dgroovy.parameters=true')
}
shadowJar {
mergeServiceFiles()
}
tasks.withType(JavaExec) {
classpath += configurations.developmentOnly
jvmArgs('-noverify', '-XX:TieredStopAtLevel=1', '-Dcom.sun.management.jmxremote')
}
I have adjusted a HelloController as follows
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.HttpStatus
import org.springframework.boot.actuate.endpoint.annotation.Endpoint
#Controller("/hello")
#Endpoint
class HelloController {
#Get("/")
String index() {
return 'hello william'
}
}
and marked the Application class as being a SpringbootApplication - but call the Micronaut.run() to build the MN context etc
import io.micronaut.runtime.Micronaut
import groovy.transform.CompileStatic
import org.springframework.boot.autoconfigure.SpringBootApplication
#CompileStatic
#SpringBootApplication
class Application {
static void main(String[] args) {
Micronaut.run(Application)
}
}
I tried to adjust application.yml to expose all the endpoints as follows
micronaut:
application:
name: micronaut-std-app
management:
endpoints:
web:
exposure:
include=*:
This all compiles ok, and runs ok. if you invoke the localhost:8080/hello you get the expected string
if you try and access the actuator endpoints - nothing is being generated, and the browser displays
{"message":"Page Not Found","_links":{"self":{"href":"/actuator/health","templated":false}}}
if your trying to do a mixed micronaut and spring project, then how do you get any actuator endpoints enabled for your MN pre processed controllers etc ?
If you just want a health check endpoint, Micronaut have build in health check endpoint available.
Add in the build.gradle the fallowing dependence to add the endpoints like health:
implementation("io.micronaut:micronaut-management")
You can add in the application.yml
endpoints:
health:
enabled: true
Then change the health check url to "/health"
I'm getting an error running my JHipster application with Prometheus configuration for metrics.
I use the configuration from the official website :
https://www.jhipster.tech/monitoring/
In my application-dev.yml I have :
metrics:
prometheus:
enabled: true
And my class for auth is :
#Configuration
#Order(1)
#ConditionalOnProperty(prefix = "jhipster", name = "metrics.prometheus.enabled")
public class BasicAuthConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/management/prometheus/**")
.authorizeRequests()
.anyRequest().hasAuthority(AuthoritiesConstants.ADMIN)
.and()
.httpBasic().realmName("jhipster")
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().csrf().disable();
}
}
2019-06-25 12:22:52.693 INFO 13260 --- [ restartedMain] com.ex.App : The following profiles are active: dev,swagger
2019-06-25 12:22:55.170 WARN 13260 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webConfigurer' defined in file [/home/eclipse-workspace/back_docker/target/classes/com/ex/config/WebConfigurer.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'io.github.jhipster.config.JHipsterProperties': Could not bind properties to 'JHipsterProperties' : prefix=jhipster, ignoreInvalidFields=false, ignoreUnknownFields=false; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'jhipster' to io.github.jhipster.config.JHipsterProperties
2019-06-25 12:22:55.188 ERROR 13260 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target [Bindable#7585af55 type = io.github.jhipster.config.JHipsterProperties, value = 'provided', annotations = array<Annotation>[#org.springframework.boot.context.properties.ConfigurationProperties(ignoreInvalidFields=false, ignoreUnknownFields=false, value=jhipster, prefix=jhipster)]] failed:
Property: jhipster.metrics.prometheus.enabled
Value: true
Origin: class path resource [config/application-dev.yml]:128:22
Reason: The elements [jhipster.metrics.prometheus.enabled] were left unbound.
Action:
Update your application's configuration
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 11.679 s
[INFO] Finished at: 2019-06-25T12:22:55+02:00
[INFO] ------------------------------------------------------------------------
I changed my JHipster project from microservice application to microservice gateway and it solved this issue.
I am trying to run this simple kinesis message consumer with the following code. This is the only class in application
I am facing this error since, I have updated to latest snapshot version of kinesis binder
#SpringBootApplication
#RestController
#EnableBinding(Sink.class)
#EnableAutoConfiguration
public class ProducerApplication {
public static void main(String[] args) {
SpringApplication.run(ProducerApplication.class, args);
}
#StreamListener(Sink.INPUT)
public void listen(String message) {
System.out.println("Message has been received"+message);
}
}
Application yml
server.port: 8081
spring:
cloud:
stream:
bindings:
input:
destination: my.sink
content-type: application/json
cloud:
aws:
region:
static: us-east-1
credentials:
accessKey: <accessKey>
secretKey: <secretKey>
build.gradle
buildscript {
ext {
springBootVersion = '2.0.3.RELEASE'
}
repositories {
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.kinesis.demo'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
dependencies {
compile('org.springframework.boot:spring-boot-starter')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.cloud:spring-cloud-stream-binder-kinesis:1.0.0.BUILD-SNAPSHOT')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
I am getting the bean initialzation exception and there seems to be a problem in creating bean DynamoDbMetadataStore.
2018-07-10 10:53:22.629 INFO 18332 --- [esis-consumer-1] a.i.k.KinesisMessageDrivenChannelAdapter : Got an exception java.lang.IllegalStateException: The component has not been initialized: DynamoDbMetadataStore{table={SpringIntegrationMetadataStore: {AttributeDefinitions: [{AttributeName: KEY,AttributeType: S}],TableName: SpringIntegrationMetadataStore,KeySchema: [{AttributeName: KEY,KeyType: HASH}],TableStatus: ACTIVE,CreationDateTime: Wed Jun 27 10:51:53 IST 2018,ProvisionedThroughput: {NumberOfDecreasesToday: 0,ReadCapacityUnits: 1,WriteCapacityUnits: 1},TableSizeBytes: 0,ItemCount: 0,TableArn: arn:aws:dynamodb:us-east-1:1234567:table/SpringIntegrationMetadataStore,TableId: d0cf588b-e122-406b-ad82-06255dfea6d4,}}, createTableRetries=25, createTableDelay=1, readCapacity=1, writeCapacity=1, timeToLive=null}.
Is it declared as a bean? during [ShardConsumer{shardOffset=KinesisShardOffset{iteratorType=LATEST, sequenceNumber='null', timestamp=null, stream='my.sink', shard='shardId-000000000000', reset=false}, state=NEW}] task invocation.
Process will be retried on the next iteration.
This error started after updating to latest snapshot version of kinesis binder.
Can you please check if some thing is wrong.
I have just fixed the issue: https://github.com/spring-projects/spring-integration-aws/commit/fc34f814e557936d1bcb815d0879bd4f6e035675
The problem was that when we have already a table in the DynamoDB, we just return from the afterPropertiesSet() leaving the initialized as false.
The latest BUILD-SNAPSHOT should work now.
I've created new Groffin module using IntelliJ. I was prompted for create-app command.
Creating a module was fine, and as you know, by default, when you ran an app, it shows applet with default content "Content goes here".
Next, I've added a second login MVC group in Application.groovy:
application {
title = 'Soms'
startupGroups = ['login']
// Should Griffon exit when no Griffon created frames are showing?
autoShutdown = true
// If you want some non-standard application class, apply it here
//frameClass = 'javax.swing.JFrame'
}
mvcGroups {
// MVC Group for "soms"
'soms' {
model = 'soms.SomsModel'
view = 'soms.SomsView'
controller = 'soms.SomsController'
}
// MVC Group for "login"
'login' {
model = 'soms.LoginModel'
view = 'soms.LoginView'
controller = 'soms.LoginController'
}
}
I've also created:
LoginModel.groovy (groovy class)
LoginController.groovy (groovy class)
LoginView.groovy (groovy script)
in the corresponding folders.
When I run project, it's giving errors:
Base Directory: D:\work\griffon\soms Running script
C:\Griffon-1.2.0\scripts\RunApp.groovy Resolving dependencies...
Dependencies resolved in 633ms. Environment set to development
Resolving framework plugin dependencies ... Framework plugin
dependencies resolved in 1114 ms. Resolving plugin dependencies ...
Plugin dependencies resolved in 741 ms. [griffonc] Compiling 1 source
file to d:\Users\akarasaev.griffon\1.2.0\projects\soms\classes\main
Launching application ... 2013-04-15 10:26:44,788 [main] INFO
griffon.swing.SwingApplication - Initializing all startup groups:
[login] 2013-04-15 10:26:46,311 [AWT-EventQueue-0] ERROR
org.codehaus.griffon.runtime.builder.UberBuilder - An error occurred
while building soms.LoginView#34a083f2
groovy.lang.MissingPropertyException: No such property: CENTER for
class: org.codehaus.griffon.runtime.builder.UberBuilder at
org.codehaus.griffon.runtime.builder.UberBuilder.getProperty(UberBuilder.groovy:187)
at
org.codehaus.griffon.runtime.builder.UberInterceptorMetaClass.getProperty(UberInterceptorMetaClass.groovy:210)
at soms.LoginView.run(LoginView.groovy:18) at
org.codehaus.griffon.runtime.builder.UberInterceptorMetaClass.invokeMethod(UberInterceptorMetaClass.groovy:152)
at
org.codehaus.griffon.runtime.builder.UberBuilder.build(UberBuilder.groovy:160)
at
org.codehaus.griffon.runtime.core.AbstractMVCGroup$1.run(AbstractMVCGroup.java:129)
2013-04-15 10:26:46,324 [main] ERROR
griffon.util.GriffonExceptionHandler - Uncaught Exception
groovy.lang.MissingPropertyException: No such property: CENTER for
class: org.codehaus.griffon.runtime.builder.UberBuilder at
org.codehaus.griffon.runtime.builder.UberBuilder.getProperty(UberBuilder.groovy:187)
at
org.codehaus.griffon.runtime.builder.UberInterceptorMetaClass.getProperty(UberInterceptorMetaClass.groovy:210)
at soms.LoginView.run(LoginView.groovy:18) at
org.codehaus.griffon.runtime.builder.UberInterceptorMetaClass.invokeMethod(UberInterceptorMetaClass.groovy:152)
at
org.codehaus.griffon.runtime.builder.UberBuilder.build(UberBuilder.groovy:160)
at
org.codehaus.griffon.runtime.core.AbstractMVCGroup$1.run(AbstractMVCGroup.java:129)
The same error happens when I try to run from command prompt.
Environment:
Win 7 Pro, 64-bit
IntelliJ IDEA ver 12.1
Griffon-1.2.0 JDK 1.6
LoginModel.groovy:
package soms
import groovy.beans.Bindable
import griffon.transform.PropertyListener
import static griffon.util.GriffonNameUtils.isBlank
#Bindable
#PropertyListener(enabler)
class LoginModel {
String login
String password
boolean submitEnabled
boolean resetEnabled
private enabler = { e ->
submitEnabled = !isBlank(login) && !isBlank(password)
resetEnabled = !isBlank(login) || !isBlank(password)
}
}
LoginView.groovy:
package soms
application(title: 'Login',
preferredSize: [320, 240],
pack: true,
locationByPlatform: true
)
borderLayout()
panel(constraints: CENTER, border: emptyBorder(6)) {
gridLayout(rows:3, columns:2, hgap:6, vgap:6)
label: 'login:'
textField columns: 20, text: bind(target: model, 'login', mutual: true)
label: 'password:'
textField columns: 20, text: bind(target: model, 'password', mutual: true)
}
panel(constraints: SOUTH){
gridLayout(rows:1, cols:2, hgap:6, vgap:6 )
button('reset', actionPerformed: controller.reset, enabled: bind{model.resetEnabled})
button('submit', actionPerformed: controller.reset, enabled: bind{model.submitEnabled})
}
LoginController.groovy:
package soms
class LoginController {
def model
def view
}
I found out that my LoginController.groovy was incomplete.
Now it's working and the correct LoginController.groovy as follows:
package soms
import griffon.transform.Threading
class LoginController {
def model
def view
#Threading(Threading.Policy.SKIP)
def reset = {
model.login = ''
model.password = ''
}
def submit = {
println "Login: ${model.login}"
println "Password: ${model.password}"
}
}
I want to run Jetty 7+ with gradle build, but unlucky looks like there is no way to do this with jettyRun. So probably simplest idea to achieve what I want would be to use custom target:
task runJetty << {
def server = new Server()
// more code here
server.start()
server.join()
}
Unlucky I just started with gradle and I don't know groovy either, so it's hard for me to create proper target. I was looking over the internet but I wasn't able to find any solution.
Can anyone hit me with some sample groovy code which can run existing jar with jetty?
Ok, I found out how to run it using jetty directly from repository:
jettyVersion = "8.1.0.RC0"
configurations {
jetty8
}
dependencies {
jetty8 "org.mortbay.jetty:jetty-runner:$jettyVersion"
}
task runJetty8(type: JavaExec) {
main = "org.mortbay.jetty.runner.Runner"
args = [war.archivePath]
classpath configurations.jetty8
}
Here's a working version, using the jetty ant tasks. This finally enabled me the proper control with deamon=true.
configurations { jetty }
dependencies { jetty 'org.eclipse.jetty:jetty-ant:9.0.4.v20130625' }
task jetty(dependsOn: build) << {
ant.taskdef(name: 'jettyRun', classname: 'org.eclipse.jetty.ant.JettyRunTask', classpath: configurations.jetty.asPath, loaderref: "jetty.loader")
ant.typedef(name: "connector", classname: "org.eclipse.jetty.ant.types.Connector", classpath: configurations.jetty.asPath, loaderref: "jetty.loader")
ant.jettyRun(daemon:true, stopPort: 8999, stopKey: "STOP") {
webApp(war: THE_WAR_PRODUCING_TASK.archivePath, contextPath: '/context')
connectors { connector(port: 9000) }
systemProperties {
systemProperty(name: 'environment.type', value: 'development')
}
}
}
task jettyStop << {
ant.taskdef(name: 'jettyStop', classname: 'org.eclipse.jetty.ant.JettyStopTask', classpath: configurations.jetty.asPath)
ant.jettyStop(stopPort: 8999, stopKey: "STOP")
}
There is a jetty-eclipse-plugin that allows you to run newer versions of jetty
https://github.com/Khoulaiz/gradle-jetty-eclipse-plugin
jetty plugin supports jetty 6.1.25 at present
You can use something like this:
jettyRoot = '/path/to/your/jetty/root'
task runJetty7 << {
description = "Runs jetty 7"
ant.java(dir: jettyRoot, jar: jettyRoot + '/start.jar', failOnError: 'true', fork: 'true') {
classpath {
...
}
}
}