Quarkus Reactive WebClient Gives Unsatisfied dependency - reactive-programming

I am trying to boot up a simple quarkus app where I can filter the incoming request and check the token in the header. But getting unsatisfied dependency. So any request comes to resource should first get through the requestFilter.java
I want application to build successfully.
Quarkus version 2.16.1.Final, Java 17 and gradle 7.5.1
build.gradle
plugins {
id 'java'
id 'io.quarkus'
}
repositories {
mavenCentral()
mavenLocal()
}
dependencies {
implementation enforcedPlatform("${quarkusPlatformGroupId}:${quarkusPlatformArtifactId}:${quarkusPlatformVersion}")
implementation('io.quarkus:quarkus-arc')
testImplementation('io.quarkus:quarkus-junit5')
testImplementation('io.rest-assured:rest-assured')
implementation('io.quarkus:quarkus-resteasy-reactive')
implementation("io.quarkus:quarkus-rest-client-reactive-jackson")
implementation("io.quarkus:quarkus-kubernetes")
implementation("io.quarkus:quarkus-vertx")
implementation("io.smallrye.reactive:smallrye-mutiny-vertx-web-client")
}
version '1.0-SNAPSHOT'
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
test {
systemProperty "java.util.logging.manager", "org.jboss.logmanager.LogManager"
}
compileJava {
options.encoding = 'UTF-8'
options.compilerArgs << '-parameters'
}
compileTestJava {
options.encoding = 'UTF-8'
}
RequestFilter.java
import io.quarkus.runtime.util.StringUtil;
import io.vertx.mutiny.core.Vertx;
import io.vertx.mutiny.ext.web.client.WebClient;
import org.jboss.logging.Logger;
import org.jboss.resteasy.reactive.server.ServerRequestFilter;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
#Provider
#ApplicationScoped
public class RequestFilters {
#Inject
UriInfo uriInfo;
#Inject
Logger logger;
private final Vertx vertx;
private final WebClient client;
#Inject
public RequestFilters(Vertx vertx, WebClient client) {
this.vertx = vertx;
this.client = WebClient.create(vertx);
}
private static final String USER_TOKEN_JWT = "usertoken";
#ServerRequestFilter
public void requestFilter(ContainerRequestContext requestContext) throws Exception {
if (StringUtil.isNullOrEmpty(requestContext.getHeaders().getFirst(USER_TOKEN_JWT))) {
logger.error("User token is missing.");
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
}
var requestUri = uriInfo.getRequestUri().getPath();
client.getAbs(requestUri)
//.host("")
//.port(8080)
.send();
}
}
Exception
java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
[error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type io.vertx.mutiny.ext.web.client.WebClient and qualifiers [#Default]
- java member: *.*.*.gateway.RequestFilters():client
- declared on CLASS bean [types=[*.*.*.gateway.RequestFilters, java.lang.Object], qualifiers=[#Default, #Any], target=*.*.*.gateway.RequestFilters]
at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:1223)

Simply changed the order of annotation on requestFilter class and it worked.
#ApplicationScoped
#Provider
#RegisterRestClient
#RegisterClientHeaders
public class RequestFilters {
..
..
}

Related

Quarkus: ContextNotActiveException when i call db from verticle

When I try to call the DB from a vertex, I get a ContextNotActiveException.
When called via Rest router everything works.
deploy Verticle:
#Inject
Vertx vertx;
void onStart(#Observes StartupEvent startupEvent) {
DeploymentOptions deploymentOptions = new DeploymentOptions();
deploymentOptions.setWorker(true);
deploymentOptions.setWorkerPoolSize(DEFAULT_WORKER_POOL_SIZE);
vertx.deployVerticle(new FileFinderForSaveWorker(), deploymentOptions);
}
my Verticle:
public class FileFinderForSaveWorker extends AbstractVerticle {
#Override
public void start(Promise<Void> startPromise) throws Exception {
try {
List<Media> mediaList = new MediaRepository().listAll();
} catch (Exception e) {
e.printStackTrace();
}
}
}
An exception occurs on this line:
List<Media> mediaList = new MediaRepository().listAll();
javax.enterprise.context.ContextNotActiveException: interface javax.enterprise.context.RequestScoped
at io.quarkus.hibernate.orm.runtime.RequestScopedEntityManagerHolder_ClientProxy.arc$delegate(RequestScopedEntityManagerHolder_ClientProxy.zig:83)
at io.quarkus.hibernate.orm.runtime.RequestScopedEntityManagerHolder_ClientProxy.getOrCreateEntityManager(RequestScopedEntityManagerHolder_ClientProxy.zig:191)
at io.quarkus.hibernate.orm.runtime.entitymanager.TransactionScopedEntityManager.getEntityManager(TransactionScopedEntityManager.java:78)
at io.quarkus.hibernate.orm.runtime.entitymanager.TransactionScopedEntityManager.createQuery(TransactionScopedEntityManager.java:317)
at io.quarkus.hibernate.orm.runtime.entitymanager.ForwardingEntityManager.createQuery(ForwardingEntityManager.java:142)
at io.quarkus.hibernate.orm.panache.runtime.JpaOperations.findAll(JpaOperations.java:328)
at io.quarkus.hibernate.orm.panache.runtime.JpaOperations.listAll(JpaOperations.java:340)
at ru.npc.sapsan.domain.repository.MediaRepository.listAll(MediaRepository.java)
at ru.npc.sapsan.core.worker.FileFinderForSaveWorker.start(FileFinderForSaveWorker.java:18)
at io.vertx.core.impl.DeploymentManager.lambda$doDeploy$9(DeploymentManager.java:556)
at io.vertx.core.impl.ContextImpl.executeTask(ContextImpl.java:369)
at io.vertx.core.impl.WorkerContext.lambda$wrapTask$0(WorkerContext.java:35)
at io.vertx.core.impl.TaskQueue.run(TaskQueue.java:76)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)
I thought that context-propagation should help me, but it doesn't work.
My dependencies in build.gradle:
dependencies {
annotationProcessor 'org.projectlombok:lombok:1.18.10'
compileOnly 'org.projectlombok:lombok:1.18.10'
implementation 'io.quarkus:quarkus-smallrye-reactive-streams-operators'
implementation 'io.quarkus:quarkus-smallrye-context-propagation-parent:1.2.1.Final'
implementation 'io.quarkus:quarkus-jdbc-postgresql'
implementation 'io.quarkus:quarkus-hibernate-orm-panache'
implementation 'io.quarkus:quarkus-tika'
implementation 'io.quarkus:quarkus-vertx-web'
implementation 'io.quarkus:quarkus-smallrye-openapi'
implementation 'io.quarkus:quarkus-vertx'
implementation 'io.quarkus:quarkus-flyway'
implementation 'io.quarkus:quarkus-hibernate-orm'
implementation 'org.projectlombok:lombok:1.18.10'
implementation enforcedPlatform("${quarkusPlatformGroupId}:${quarkusPlatformArtifactId}:${quarkusPlatformVersion}")
implementation 'io.quarkus:quarkus-resteasy'
implementation 'org.xerial.snappy:snappy-java:1.1.7.3'
implementation 'org.reflections:reflections:0.9.11'
testImplementation 'io.quarkus:quarkus-junit5'
testImplementation 'io.rest-assured:rest-assured'
}
I use hibernate-orm-panache
Repository:
#ApplicationScoped
public class MediaRepository implements PanacheRepository<Media> {
}
Entity:
#Data
#Entity
#EqualsAndHashCode(callSuper = false)
#Table(name = "media")
public class Media extends PanacheEntity {
#SerializedName("uuid")
#Column(name = "uuid", unique = true, nullable = false, columnDefinition = "varchar(36)", length = 36, updatable = false)
private String uuid = "";
}
Regards.
You are using Panache which is behind the scene is a managed JPA/Hibernate which needs CDI Context to function probably. That's why it works fine with you when you call it through rest because CDI is already initiated. If you want to use vert.x routes with Quarkus, I suggest you to use Quarkus reactive-routes with context-propagation - which you are already configured - to achieve your goal.

Why do I get "Duplicate XML entry" when I try to run my jHipster app as a stand-alone war (built by gradlew bootRepackage)?

I am stumped by this one so I'm looking for some help here.
I am developing a jHipster app with multiple database connections, built with gradle. The app runs fine with "./gradlew bootRun" but when I try to package a stand-alone war with "./gradlew -Pprod bootRepackage" and run it, I get this exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/babycenter/belle/config/DatabaseConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Duplicate XML entry for com.babycenter.belle.readonly.domain.InvoiceLineItem
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
at com.babycenter.belle.BelleApp.main(BelleApp.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
at org.springframework.boot.loader.WarLauncher.main(WarLauncher.java:59)
Caused by: java.lang.IllegalStateException: Duplicate XML entry for com.babycenter.belle.readonly.domain.InvoiceLineItem
at org.hibernate.cfg.annotations.reflection.XMLContext.addClass(XMLContext.java:140)
at org.hibernate.cfg.annotations.reflection.XMLContext.addDocument(XMLContext.java:105)
at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.<init>(AnnotationMetadataSourceProcessorImpl.java:94)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess$1.<init>(MetadataBuildingProcess.java:147)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:141)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:858)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
... 22 common frames omitted
I am puzzled because the file it says the error is in, DatabaseConfiguration.java, should only read entities from the package com.babycenter.belle.domain, which the class/XML it says is duplicated, InvoiceLineItem, is not in.
Here are files that may be involved. Tell me if you would like to see another.
DatabaseConfiguration.java
package com.babycenter.belle.config;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.liquibase.AsyncSpringLiquibase;
import liquibase.integration.spring.SpringLiquibase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
#Configuration
#EnableJpaRepositories(basePackages = "com.babycenter.belle.repository")
#EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
#EnableTransactionManagement
public class DatabaseConfiguration {
private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);
private final Environment env;
public DatabaseConfiguration(Environment env) {
this.env = env;
}
#Bean
public SpringLiquibase liquibase(#Qualifier("taskExecutor") TaskExecutor taskExecutor, #Qualifier("dataSource") DataSource dataSource,
LiquibaseProperties liquibaseProperties) {
// Start Liquibase asynchronously
SpringLiquibase liquibase = new AsyncSpringLiquibase(taskExecutor, env);
// Start Liquibase synchronously
//SpringLiquibase liquibase = new SpringLiquibase();
liquibase.setDataSource(dataSource);
liquibase.setChangeLog("classpath:config/liquibase/master.xml");
liquibase.setContexts(liquibaseProperties.getContexts());
liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
liquibase.setDropFirst(liquibaseProperties.isDropFirst());
if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE)) {
liquibase.setShouldRun(false);
} else {
liquibase.setShouldRun(liquibaseProperties.isEnabled());
log.debug("Configuring Liquibase");
}
return liquibase;
}
#Primary
#Bean(name = "dataSource")
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, #Qualifier("dataSource") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("com.babycenter.belle.domain")
.persistenceUnit("readwrite")
.build();
}
#Primary
#Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(#Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
ReadOnlyDatabaseConfiguration.java
package com.babycenter.belle.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
#Configuration
#EnableJpaRepositories(
entityManagerFactoryRef = "roEntityManagerFactory",
transactionManagerRef = "roTransactionManager",
basePackages = "com.babycenter.belle.readonly.repository")
#EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
#EnableTransactionManagement
public class ReadOnlyDatabaseConfiguration {
private final Logger log = LoggerFactory.getLogger(ReadOnlyDatabaseConfiguration.class);
#Bean(name = "roDataSource")
#ConfigurationProperties(prefix = "spring.datasource-ro")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name = "roEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean roEntityManagerFactory(EntityManagerFactoryBuilder builder, #Qualifier("roDataSource") DataSource dataSource) {
return
builder
.dataSource(dataSource)
.packages("com.babycenter.belle.readonly.domain")
.persistenceUnit("readonly")
.build();
}
#Bean(name = "roTransactionManager")
public PlatformTransactionManager roTransactionManager(#Qualifier("roEntityManagerFactory") EntityManagerFactory roEntityManagerFactory) {
return new JpaTransactionManager(roEntityManagerFactory);
}
}
InvoiceLineItem.java
package com.babycenter.belle.readonly.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import java.io.Serializable;
/**
* An object representation of a row from the opr_invoice_line_item table in Redshift
*/
#Entity
#Table(name = "opr_invoice_line_item", schema = "advertising")
#Cacheable
#Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class InvoiceLineItem implements Serializable {
#Id
#Column(name = "invoice_line_item_id", insertable = false, updatable = false)
private Long invoiceLineItemId;
#Column(name = "sales_order_line_item_id", insertable = false, updatable = false)
private Long salesOrderLineItemId;
#Column(name = "primary_performance", insertable = false, updatable = false)
private Long primaryPerformance;
#Column(name = "third_party_performance", insertable = false, updatable = false)
private Long thirdPartyPerformance;
#Column(name = "invoice_units", insertable = false, updatable = false)
private String invoiceUnits;
#Column(name = "invoice_amount", insertable = false, updatable = false)
private Float invoiceAmount;
/**
* Assigned when possible - not a column in opr_invoice_line_item table
*/
private String billingPeriodName;
public Long getInvoiceLineItemId() {
return invoiceLineItemId;
}
public void setInvoiceLineItemId(Long invoiceLineItemId) {
this.invoiceLineItemId = invoiceLineItemId;
}
public Long getSalesOrderLineItemId() {
return salesOrderLineItemId;
}
public void setSalesOrderLineItemId(Long salesOrderLineItemId) {
this.salesOrderLineItemId = salesOrderLineItemId;
}
public Long getPrimaryPerformance() {
return primaryPerformance;
}
public void setPrimaryPerformance(Long primaryPerformance) {
this.primaryPerformance = primaryPerformance;
}
public Long getThirdPartyPerformance() {
return thirdPartyPerformance;
}
public void setThirdPartyPerformance(Long thirdPartyPerformance) {
this.thirdPartyPerformance = thirdPartyPerformance;
}
public String getInvoiceUnits() {
return invoiceUnits;
}
public void setInvoiceUnits(String invoiceUnits) {
this.invoiceUnits = invoiceUnits;
}
public Float getInvoiceAmount() {
return invoiceAmount;
}
public void setInvoiceAmount(Float invoiceAmount) {
this.invoiceAmount = invoiceAmount;
}
public String getBillingPeriodName() {
return billingPeriodName;
}
public void setBillingPeriodName(String billingPeriodName) {
this.billingPeriodName = billingPeriodName;
}
}
build.gradle
import org.gradle.internal.os.OperatingSystem
buildscript {
repositories {
mavenLocal()
jcenter()
maven { url "http://repo.spring.io/plugins-release" }
maven { url "https://plugins.gradle.org/m2/" }
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:${spring_boot_version}"
classpath "org.springframework.build.gradle:propdeps-plugin:0.0.7"
//jhipster-needle-gradle-buildscript-dependency - JHipster will add additional gradle build script plugins here
}
}
plugins {
id "org.sonarqube" version "2.5"
id "net.ltgt.apt" version "0.11"
id "io.spring.dependency-management" version "1.0.3.RELEASE"
id "com.moowork.node" version "1.2.0"
//jhipster-needle-gradle-plugins - JHipster will add additional gradle plugins here
}
apply plugin: 'java'
sourceCompatibility=1.8
targetCompatibility=1.8
apply plugin: 'maven'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'
apply plugin: 'propdeps'
apply plugin: 'com.moowork.node'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'idea'
defaultTasks 'bootRun'
group = 'com.babycenter.belle'
version = '0.0.1-SNAPSHOT'
description = ''
bootRepackage {
mainClass = 'com.babycenter.belle.BelleApp'
}
war {
}
springBoot {
mainClass = 'com.babycenter.belle.BelleApp'
executable = true
buildInfo()
}
if (OperatingSystem.current().isWindows()) {
task pathingJar(type: Jar) {
dependsOn configurations.runtime
appendix = 'pathing'
doFirst {
manifest {
attributes 'Class-Path': configurations.runtime.files.collect {
it.toURL().toString().replaceFirst(/file:\/+/, '/').replaceAll(' ', '%20')
}.join(' ')
}
}
}
bootRun {
addResources = false
dependsOn pathingJar
doFirst {
classpath = files("$buildDir/classes/java/main", "$buildDir/resources/main", pathingJar.archivePath)
}
}
} else {
bootRun {
addResources = false
systemProperties System.properties
}
}
//use jrebel to hot-deploy class changes during development
if (project.hasProperty('rebelAgent')) {
bootRun.jvmArgs += rebelAgent
}
test {
include '**/*UnitTest*'
include '**/*IntTest*'
// uncomment if the tests reports are not generated
// see https://github.com/jhipster/generator-jhipster/pull/2771 and https://github.com/jhipster/generator-jhipster/pull/4484
// ignoreFailures true
reports.html.enabled = false
}
task cucumberTest(type: Test) {
include '**/CucumberTest*'
// uncomment if the tests reports are not generated
// see https://github.com/jhipster/generator-jhipster/pull/2771 and https://github.com/jhipster/generator-jhipster/pull/4484
// ignoreFailures true
reports.html.enabled = false
}
test.finalizedBy(cucumberTest)
task testReport(type: TestReport) {
destinationDir = file("$buildDir/reports/tests")
reportOn test
reportOn cucumberTest
}
cucumberTest.finalizedBy(testReport)
apply from: 'gradle/docker.gradle'
apply from: 'gradle/sonar.gradle'
apply from: 'gradle/liquibase.gradle'
apply from: 'gradle/mapstruct.gradle'
//jhipster-needle-gradle-apply-from - JHipster will add additional gradle scripts to be applied here
if (project.hasProperty('prod')) {
apply from: 'gradle/profile_prod.gradle'
} else if (project.hasProperty('stag')) {
apply from: 'gradle/profile_stag.gradle'
} else {
apply from: 'gradle/profile_dev.gradle'
}
if (project.hasProperty('graphite')) {
apply from: 'gradle/graphite.gradle'
}
if (project.hasProperty('prometheus')) {
apply from: 'gradle/prometheus.gradle'
}
configurations {
providedRuntime
compile.exclude module: "spring-boot-starter-tomcat"
}
repositories {
mavenLocal()
jcenter()
maven { url 'http://nexus.babycenter.com:8081/nexus/content/repositories/thirdparty/'}
}
dependencies {
compile "io.github.jhipster:jhipster:${jhipster_server_version}"
compile "io.dropwizard.metrics:metrics-core:${dropwizard_metrics_version}"
compile "io.dropwizard.metrics:metrics-jcache:${dropwizard_metrics_version}"
compile "io.dropwizard.metrics:metrics-jvm:${dropwizard_metrics_version}"
compile "io.dropwizard.metrics:metrics-servlet:${dropwizard_metrics_version}"
compile "io.dropwizard.metrics:metrics-json:${dropwizard_metrics_version}"
compile "io.dropwizard.metrics:metrics-servlets:${dropwizard_metrics_version}"
compile "net.logstash.logback:logstash-logback-encoder:${logstash_logback_encoder_version}"
compile "com.fasterxml.jackson.dataformat:jackson-dataformat-csv:${jackson_dataformat_csv_version}"
compile "com.fasterxml.jackson.datatype:jackson-datatype-json-org"
compile "com.fasterxml.jackson.datatype:jackson-datatype-hppc"
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"
compile "com.fasterxml.jackson.datatype:jackson-datatype-hibernate5"
compile "com.fasterxml.jackson.core:jackson-annotations"
compile "com.fasterxml.jackson.core:jackson-databind"
compile "com.fasterxml.jackson.module:jackson-module-afterburner"
compile ("com.ryantenney.metrics:metrics-spring:${metrics_spring_version}")
compile "javax.cache:cache-api"
compile "org.hibernate:hibernate-core:${hibernate_version}"
compile ("com.zaxxer:HikariCP:${hikaricp_version}")
compile "org.apache.commons:commons-lang3:${commons_lang_version}"
compile "commons-io:commons-io:${commons_io_version}"
compile "javax.transaction:javax.transaction-api"
compile "org.ehcache:ehcache"
compile "org.hibernate:hibernate-jcache:${hibernate_version}"
compile "org.hibernate:hibernate-envers:${hibernate_version}"
compile "org.hibernate:hibernate-validator"
compile "org.hibernate:hibernate-entitymanager:${hibernate_version}"
compile ("org.liquibase:liquibase-core")
compile "com.mattbertolini:liquibase-slf4j:${liquibase_slf4j_version}"
compile "org.springframework.boot:spring-boot-actuator"
compile "org.springframework.boot:spring-boot-autoconfigure"
compile "org.springframework.boot:spring-boot-loader-tools"
compile "org.springframework.boot:spring-boot-starter-mail"
compile "org.springframework.boot:spring-boot-starter-logging"
compile "org.springframework.boot:spring-boot-starter-aop"
compile "org.springframework.boot:spring-boot-starter-data-jpa"
compile "org.springframework.boot:spring-boot-starter-security"
compile ("org.springframework.boot:spring-boot-starter-web") {
exclude module: 'spring-boot-starter-tomcat'
}
compile "org.springframework.boot:spring-boot-starter-undertow"
compile "org.springframework.boot:spring-boot-starter-thymeleaf"
compile "org.zalando:problem-spring-web:${problem_spring_web_version}"
compile "org.springframework.boot:spring-boot-starter-cloud-connectors"
compile ("org.springframework:spring-context-support")
compile "org.springframework.security:spring-security-config"
compile "org.springframework.security:spring-security-data"
compile "org.springframework.security:spring-security-web"
compile ("io.springfox:springfox-swagger2:${springfox_version}") {
exclude module: 'mapstruct'
}
compile "io.springfox:springfox-bean-validators:${springfox_version}"
//The Data Warehouse (i.e. our read-only data source) is AWS Redshift
compile "com.amazon.redshift:RedShiftJDBC42:${redshift_jdbc_version}" //needs the RedShiftJDBC42 driver to work
compile "com.amazonaws:aws-java-sdk-redshift:${redshift_sdk_version}"
//our writable database is mysql
compile "mysql:mysql-connector-java"
compile "org.mapstruct:mapstruct-jdk8:${mapstruct_version}"
testCompile "org.awaitility:awaitility:${awaitility_version}"
testCompile "com.jayway.jsonpath:json-path"
testCompile "info.cukes:cucumber-junit:${cucumber_version}"
testCompile "info.cukes:cucumber-spring:${cucumber_version}"
testCompile ("org.springframework.boot:spring-boot-starter-test") {
exclude group: 'com.vaadin.external.google', module: 'android-json'
}
testCompile "org.springframework.security:spring-security-test"
testCompile "org.springframework.boot:spring-boot-test"
testCompile "org.assertj:assertj-core:${assertj_version}"
testCompile "junit:junit"
testCompile "org.mockito:mockito-core"
testCompile "com.mattbertolini:liquibase-slf4j:${liquibase_slf4j_version}"
testCompile "org.hamcrest:hamcrest-library"
testCompile "com.h2database:h2"
optional ("org.springframework.boot:spring-boot-configuration-processor:${spring_boot_version}") {
exclude group: 'com.vaadin.external.google', module: 'android-json'
}
//jhipster-needle-gradle-dependency - JHipster will add additional dependencies here
}
clean {
delete "target"
}
task cleanResources(type: Delete) {
delete 'build/resources'
}
task wrapper(type: Wrapper) {
gradleVersion = '4.1'
}
task stage(dependsOn: 'bootRepackage') {
}
if (project.hasProperty('nodeInstall')) {
node {
version = "${node_version}"
npmVersion = "${npm_version}"
yarnVersion = "${yarn_version}"
download = true
}
}
compileJava.dependsOn processResources
processResources.dependsOn cleanResources,bootBuildInfo
bootBuildInfo.mustRunAfter cleanResources
Here are my versions of things:
jHipster 4.9.0
Spring Boot 1.5.8.RELEASE
Gradle 4.2
Groovy 2.4.11
I was eventually able to solve this myself.
I was using annotations in code to define my JPA entities PLUS an orm.xml file for named queries that had to have my result class entities defined. I had no persistence.xml file.
This ran fine with “./gradlew bootRun” but when I bundled a war it threw the exception listed above.
I learned when I package up a Spring Boot war with Hibernate JPA it will attempt to add annotated entities to orm.xml - and may even load orm.xml multiple times:
Duplicate XML entry | Hibernate orm.xml
Since I already had an entity definition there, it said there was a duplicate.
Basically I learned I can either use annotations in code, including named queries, OR define everything in orm.xml but I can’t mix the two.

Cybersource org.apache.cxf.binding.soap.SoapFault: Security processing failed USING CXF

package com.cybersource.schemas.transaction_data.transactionprocessor;
import java.io.IOException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
imp ort java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Map;
import org.apache.cxf.version.Version;
import com.cybersource.schemas.transaction_data_1.BillTo;
import com.cybersource.schemas.transaction_data_1.CCAuthService;
import com.cybersource.schemas.transaction_data_1.Card;
import com.cybersource.schemas.transaction_data_1.Item;
import com.cybersource.schemas.transaction_data_1.PurchaseTotals;
import com.cybersource.schemas.transaction_data_1.ReplyMessage;
import com.cybersource.schemas.transaction_data_1.RequestMessage;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor;
import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.WSPasswordCallback;
//import org.apache.wss4j.common.ext.WSPasswordCallback;
import org.apache.ws.security.handler.WSHandlerConstants;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
public class CybersourceClientExample {
// Replace the MERCHANT_ID and MERCHANT_KEY with the appropriate --donevalues.
private static final String MERCHANT_ID = "MERCHANT_ID ";
private static final String MERCHANT_KEY = "MERCHANT_KEY ";
private static final String SERVER_URL = "https://ics2wstesta.ic3.com/commerce/1.x/transactionProcessor/CyberSourceTransaction_1.142.wsdl";
private static final String CLIENT_LIB_VERSION = Version.getCompleteVersionString() + "/1.5.10"; // CXF Version / WSS4J Version
private static final String CLIENT_LIBRARY = "Java CXF WSS4J";
private static final String CLIENT_ENV = System.getProperty("os.name") + "/" +
System.getProperty("os.version") + "/" +
System.getProperty("java.vendor") + "/" +
System.getProperty("java.version");
public static void main(String[] args) throws RemoteException, MalformedURLException {
RequestMessage request = new RequestMessage();
// To help Cybersource troubleshoot any problems that you may encounter,
// include the following information about the client.
addClientLibraryInfo(request);
request.setMerchantID(MERCHANT_ID);
// Internal Transaction Reference Code for the Merchant
request.setMerchantReferenceCode("222222");
// Here we are telling the client that we are going to run an AUTH.
request.setCcAuthService(new CCAuthService());
request.getCcAuthService().setRun("true");
request.setBillTo(buildBillTo());
request.setCard(buildCard());
request.setPurchaseTotals(buildPurchaseTotals());
request.getItem().add(buildItem("0", "12.34", "2"));
request.getItem().add(buildItem("1", "56.78", "1"));
ITransactionProcessor processor = new TransactionProcessor(new URL(SERVER_URL)).getPortXML();
// Add WS-Security Headers to the Request
addSecurityValues(processor);
ReplyMessage reply = processor.runTransaction(request);
System.out.println("decision = " + reply.getDecision());
System.out.println("reasonCode = " + reply.getReasonCode());
System.out.println("requestID = " + reply.getRequestID());
System.out.println("requestToken = " + reply.getRequestToken());
System.out.println("ccAuthReply.reasonCode = " + reply.getCcAuthReply().getReasonCode());
}
private static void addClientLibraryInfo(RequestMessage request) {
request.setClientLibrary(CLIENT_LIBRARY);
request.setClientLibraryVersion(CLIENT_LIB_VERSION);
request.setClientEnvironment(CLIENT_ENV);
}
private static Item buildItem(String id, String unitPrice, String quantity) {
Item item = new Item();
item.setId(new BigInteger(id));
item.setUnitPrice(unitPrice);
item.setQuantity(quantity);
return item;
}
private static PurchaseTotals buildPurchaseTotals() {
PurchaseTotals purchaseTotals = new PurchaseTotals();
purchaseTotals.setCurrency("USD");
purchaseTotals.setGrandTotalAmount("100");
return purchaseTotals;
}
private static Card buildCard() {
Card card = new Card();
card.setAccountNumber("4111111111111111");
card.setExpirationMonth(new BigInteger("12"));
card.setExpirationYear(new BigInteger("2020"));
return card;
}
private static BillTo buildBillTo() {
BillTo billTo = new BillTo();
billTo.setFirstName("John");
billTo.setLastName("Doe");
billTo.setStreet1("1295 Charleston Road");
billTo.setCity("Mountain View");
billTo.setState("CA");
billTo.setPostalCode("94043");
billTo.setCountry("US");
billTo.setEmail("null#cybersource.com");
billTo.setIpAddress("10.7.111.111");
return billTo;
}
private static void addSecurityValues(ITransactionProcessor processor) {
Client client = ClientProxy.getClient(processor);
Endpoint endpoint = client.getEndpoint();
// We'll have to add the Username and Password properties to an OutInterceptor
HashMap<String, Object> outHeaders = new HashMap<String, Object>();
outHeaders.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
outHeaders.put(WSHandlerConstants.USER, MERCHANT_ID);
outHeaders.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
outHeaders.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientPasswordHandler.class.getName());
WSS4JOutInterceptor interceptor = new WSS4JOutInterceptor(outHeaders);
endpoint.getOutInterceptors().add(interceptor);
}
public static class ClientPasswordHandler implements CallbackHandler {
#Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback callback : callbacks) {
if ((WSPasswordCallback)callback instanceof WSPasswordCallback) {
WSPasswordCallback passwordCallback = (WSPasswordCallback) callback;
passwordCallback.setPassword(MERCHANT_KEY);
}
}
}
}
}
I am facing the following error. Please help.
Dec 04, 2017 8:15:00 AM org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean buildServiceFromWSDL
INFO: Creating Service {urn:schemas-cybersource-com:transaction-data:TransactionProcessor}TransactionProcessor from WSDL: https://ics2wstesta.ic3.com/commerce/1.x/transactionProcessor/CyberSourceTransaction_1.142.wsdl
Dec 04, 2017 8:15:03 AM org.apache.cxf.phase.PhaseInterceptorChain doDefaultLogging
WARNING: Interceptor for {urn:schemas-cybersource-com:transaction-data:TransactionProcessor}TransactionProcessor#{urn:schemas-cybersource-com:transaction-data:TransactionProcessor}runTransaction has thrown exception, unwinding now
org.apache.cxf.binding.soap.SoapFault: Security processing failed.
at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessageInternal(WSS4JOutInterceptor.java:269)
at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessage(WSS4JOutInterceptor.java:135)
at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessage(WSS4JOutInterceptor.java:122)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:518)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:427)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:328)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:281)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:139)
at com.sun.proxy.$Proxy36.runTransaction(Unknown Source)
at com.cybersource.schemas.transaction_data.transactionprocessor.CybersourceClientExample.main(CybersourceClientExample.java:77)
Caused by: org.apache.wss4j.common.ext.WSSecurityException: WSHandler: password callback failed
Original Exception was java.lang.ClassCastException: org.apache.wss4j.common.ext.WSPasswordCallback cannot be cast to org.apache.ws.security.WSPasswordCallback
at org.apache.wss4j.dom.handler.WSHandler.performPasswordCallback(WSHandler.java:1172)
at org.apache.wss4j.dom.handler.WSHandler.getPasswordCB(WSHandler.java:1130)
at org.apache.wss4j.dom.action.UsernameTokenAction.execute(UsernameTokenAction.java:43)
at org.apache.wss4j.dom.handler.WSHandler.doSenderAction(WSHandler.java:234)
at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor.access$100(WSS4JOutInterceptor.java:54)
at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessageInternal(WSS4JOutInterceptor.java:261)
... 11 more
Caused by: java.lang.ClassCastException: org.apache.wss4j.common.ext.WSPasswordCallback cannot be cast to org.apache.ws.security.WSPasswordCallback
at com.cybersource.schemas.transaction_data.transactionprocessor.CybersourceClientExample$ClientPasswordHandler.handle(CybersourceClientExample.java:152)
at org.apache.wss4j.dom.handler.WSHandler.performPasswordCallback(WSHandler.java:1170)
... 16 more
Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Security processing failed.
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:161)
at com.sun.proxy.$Proxy36.runTransaction(Unknown Source)
at com.cybersource.schemas.transaction_data.transactionprocessor.CybersourceClientExample.main(CybersourceClientExample.java:77)
Caused by: org.apache.wss4j.common.ext.WSSecurityException: WSHandler: password callback failed
Original Exception was java.lang.ClassCastException: org.apache.wss4j.common.ext.WSPasswordCallback cannot be cast to org.apache.ws.security.WSPasswordCallback
at org.apache.wss4j.dom.handler.WSHandler.performPasswordCallback(WSHandler.java:1172)
at org.apache.wss4j.dom.handler.WSHandler.getPasswordCB(WSHandler.java:1130)
at org.apache.wss4j.dom.action.UsernameTokenAction.execute(UsernameTokenAction.java:43)
at org.apache.wss4j.dom.handler.WSHandler.doSenderAction(WSHandler.java:234)
at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor.access$100(WSS4JOutInterceptor.java:54)
at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessageInternal(WSS4JOutInterceptor.java:261)
at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessage(WSS4JOutInterceptor.java:135)
at org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor$WSS4JOutInterceptorInternal.handleMessage(WSS4JOutInterceptor.java:122)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:518)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:427)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:328)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:281)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:139)
... 2 more
Caused by: java.lang.ClassCastException: org.apache.wss4j.common.ext.WSPasswordCallback cannot be cast to org.apache.ws.security.WSPasswordCallback
at com.cybersource.schemas.transaction_data.transactionprocessor.CybersourceClientExample$ClientPasswordHandler.handle(CybersourceClientExample.java:152)
at org.apache.wss4j.dom.handler.WSHandler.performPasswordCallback(WSHandler.java:1170)
... 16 more
"Caused by: java.lang.ClassCastException: org.apache.wss4j.common.ext.WSPasswordCallback cannot be cast to org.apache.ws.security.WSPasswordCallback at " - looks like you are mixing WSS4J versions incorrectly. Have you verified that all of the WSS4J jars on the classpath have the same version? Also have you checked that the WSS4J version is the correct one that should be used with the version of CXF you are using?

SRVE0777E: Exception thrown by application class

I have a JEE rest app for consume and build web service. When I use url of app in ibm bluemix I have an error in local server webSphere and also in Bluemix:
SRVE0777E: Exception thrown by application class
'tn.hunterViews.services.OfferService.afficherOffer:31'
java.lang.NullPointerException:
at tn.hunterViews.services.OfferService.afficherOffer(OfferService.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(NativeMethodAccessorImpl.java:-2)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.ibm.ws.jaxrs20.server.LibertyJaxRsServerFactoryBean.performInvocation(LibertyJaxRsServerFactoryBean.java:674)
at [internal classes]
OffersService.java
package tn.hunterViews.services;
import java.util.List;
import javax.ejb.EJB;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import tn.hunterViews.business.OfferBusiness;
import tn.hunterViews.business.OfferBusinessRemote;
import tn.hunterViews.domain.Offer;
#Path("/Offers")
public class OfferService {
#EJB
OfferBusinessRemote ofR;
#GET
#Path("")
#Produces(MediaType.APPLICATION_JSON)
public Response afficherOffer(){
return Response.status(Status.OK).entity(ofR.getOffer()).build();
}
}
offersBuissness.java
package tn.hunterViews.business;
import java.util.List;
import javax.ejb.Stateless;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import tn.hunterViews.domain.Offer;
/**
* Session Bean implementation class OfferBusiness
*/
#Stateless
public class OfferBusiness implements OfferBusinessRemote {
#Override
public List<Offer> getOffer() {
Client cl = ClientBuilder.newClient();
WebTarget target = cl.target("https://pihunterviewsdotnet.mybluemix.net/api");
WebTarget off = target.path("offerApi");
List<Offer> offers = off.request(MediaType.APPLICATION_JSON).get(new GenericType<List<Offer>>(){}) ;
cl.close();
return offers;
}
#Override
public boolean createOffer(Offer offer) {
Client cl = ClientBuilder.newClient();
WebTarget target = cl.target("https://pihunterviewsdotnet.mybluemix.net/api");
WebTarget off = target.path("offerApi");
Response resp=target.request().post(Entity.entity(offer, MediaType.APPLICATION_JSON));
if(resp.getStatus()!=201)
return false;
return true;
}
#Override
public boolean updateOffer(int id, Offer offer) {
if (id+""!=null && id!=0 && offer.getId()!=0)
{
Client cl = ClientBuilder.newClient();
WebTarget target = cl.target("https://pihunterviewsdotnet.mybluemix.net/api/offerApi"+ id);
target.request().build("PUT", Entity.entity(offer, MediaType.APPLICATION_JSON))
.invoke();
return true;
}
return false;
}
#Override
public boolean deleteOffer(int id) {
if (id+""!=null && id!=0)
{
Client cl = ClientBuilder.newClient();
WebTarget target = cl.target("https://pihunterviewsdotnet.mybluemix.net/api/offerApi"+ id);
target.request().delete();
return true;}
return false;
}
#Override
public Offer findOfferById(int id) {
Client cl = ClientBuilder.newClient();
WebTarget baseUrl = cl.target("https://pihunterviewsdotnet.mybluemix.net/api/offerApi");
WebTarget getPostURL=baseUrl.path(""+id);
Response response = getPostURL.request(MediaType.APPLICATION_JSON).get();
Offer offer=response.readEntity(Offer.class);
response.close();
cl.close();
return offer;
}
}
Please help me with this problem. Thanks.
If the #EJB annotation cannot be resolved to an EJB, then you would
have received a failure when the server created an instance of the
class containing the #EJB annotation. Since that does not appear to be
happening for you, and instead the instance is created fine, just
without that field being set, then the server is not scanning your
class for annotations or you have the javax.ejb.EJB annotation class
packaged as part of your application.
I would recommend checking the following:
Make sure the javax.ejb.EJB class is not being packaged as part of your annotation
Check that the web.xml for your WAR module has a version > 2.4. WAR modules with a version of 2.4 (or earlier) will not be scanned for annotations.
Check that the web.xml does not contain the setting metadata-complete="true". This setting turns off annotation scanning.
Source: http://www.developersite.org/102-95523-websphere-liberty

gradle application plugin got shutdown

I am using gradle application plugin to run my application. Below is my build.gradle:
group 'demo.jersey'
version '1.0-SNAPSHOT'
apply plugin: 'groovy'
apply plugin: 'java'
apply plugin: 'application'
sourceCompatibility = 1.5
mainClassName = "com.example.Main"
repositories {
mavenCentral()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.3.11'
compile 'org.glassfish.jersey.containers:jersey-container-grizzly2-http:2.22.1'
testCompile group: 'junit', name: 'junit', version: '4.11'
}
When I run gradle run, I can see my application is launched but it got shutdown immediately. Below is my Main class. Do you know how to block the application without shutting down?
package com.example;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import java.io.IOException;
import java.net.URI;
public class Main {
public static final String BASE_URI = "http://localhost:8080/myapp/";
public static HttpServer startServer() {
final ResourceConfig rc = new ResourceConfig().packages("com.example");
return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
}
public static void main(String[] args) throws IOException {
final HttpServer server = startServer();
System.out.println(String.format("Jersey app started with WADL available at "
+ "%sapplication.wadl\nHit enter to stop it...", BASE_URI));
System.in.read();
server.stop();
}
}
It stops because you invoke server.stop(); explicitly so the program finishes. Comment out this line and it will keep on running and listening for incoming requests.