War proguard does not contain jar file of the project - proguard

I am trying to obfuscate a war project. I know that when you obfuscate a war project, you can find a jar file of the project in WEB-INF/lib and I could find this jar when I obfuscated my project a few months back. But when I obfuscate it now, I cannot find the jar file, so the project does not deploy on tomcat.
Any ideas?
Here is my proguard config file:
-injars /target/project-1.0.0-BUILD-SNAPSHOT
-outjars /target/project.war
-dontwarn
-optimizations !class/marking/final
-adaptresourcefilecontents **.properties,META-INF/MANIFEST.MF,META-INF/spring.*,spring/*
-keepattributes Exceptions,InnerClasses,Signature,Deprecated,SourceFile,LineNumberTable,*Annotation*,EnclosingMethod
-allowaccessmodification
-dontshrink
-dontoptimize
-dontnote
-dontusemixedcaseclassnames
-keepdirectories
-keep class org.springframework.** { *; }
-keep #javax.annotation.Resource class *
-keep #org.springframework.cache.annotation.EnableCaching class *
-keep public class * implements javax.servlet.Servlet
-keep class com.zaxxer.hikari.** {*;}
-keep class javax.el.Expression {*;}
-keep class javax.** { *; }
-keep class javax.validation.** {*;}
-keep class java.** { *; }
-keep class org.primefaces.** {*;}
-keep class org.** { *; }
-keep class javassist.** { *; }
-keep class cglib.** {*;}
-keep class io.jsonwebtoken.** {*;}
-keep class io.swagger.** {*;}
-keep class com.fasterxml.** {*;}
-keep class com.sun.** {*;}
-keep class dom4j.** {*;}
-keep class antlr.** {*;}
-keep class mysql.mysql-connector-java.** {*;}
-keep class com.mysql.jdbc.** {*;}
-keep class com.mysql.cj.core.** {*;}
-keep class com.mysql.cj.api.** {*;}
-keep class com.mysql.cj.jdbc.** {*;}
-keep class com.mysql.cj.mysqla.** {*;}
-keep class com.mysql.cj.mysqlx.protobuf.MysqlxDatatypes$Any {*;}
-keep public class com.mysql.cj.mysqlx.** {*;}
-keep class * implements java.sql.Driver
-keep class com.ctc.wstx.stax.WstxEventFactory {*;}
-keep class com.google.protobuf.CodedInputStream {*;}
-keep class com.google.protobuf.ExtensionRegistryLite {*;}
-keep class com.google.protobuf.DynamicMessage {*;}
-keep class com.google.protobuf.MysqlxDatatypes$Object$Builder {*;}
-keep class com.google.protobuf.MysqlxDatatypes$Array$Builder {*;}
-keep class edu.vt.middleware.vt-password.** {*;}
-keep class junit.junit.** {*;}
-keep class io.netty.netty-all.** {*;}
-keep class commons-dbcp.commons-dbcp.** {*;}
-keep class org.apache.poi.poi.** {*;}
-keep class com.google.code.gson.gson.** {*;}
-keep class com.fasterxml.jackson.core.** {*;}
-keep class com.sun.faces.** {*;}
-keep class org.glassfish.web.el-impl.** {*;}
-keep class postgresql.postgresql.** {*;}
-keep class net.sf.jt400.jt400-full.** {*;}
-keep class c3p0.c3p0.** {*;}
-keep class com.lowagie.itext.** {*;}
-keep class org.apache.xmlbeans.xmlbeans.** {*;}
-keep class ojdbc.ojdbc.** {*;}
-keep class oracle.jdbc.driver.** {*;}
-keep class oracle.** {*;}
-keep class edu.vt.middleware.** {*;}
-keep class javax.faces.view.** {*;}
-keep class org.omnifaces.omnifaces.** {*;}
-keepclassmembers class * {
#org.springframework.beans.factory.annotation.* *;
#org.springframework.beans.factory.annotation.Qualifier *;
#org.springframework.beans.factory.annotation.Value *;
#org.springframework.beans.factory.annotation.Required *;
#org.springframework.context.annotation.Bean *;
#javax.annotation.PostConstruct *;
#javax.annotation.PreDestroy *;
#org.aspectj.lang.annotation.AfterReturning *;
#org.aspectj.lang.annotation.Pointcut *;
#org.aspectj.lang.annotation.AfterThrowing *;
#org.aspectj.lang.annotation.Around *;
#org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor *;
}
# Preserve the special static methods that are required in all enumeration
# classes.
-keepclassmembers class * extends java.lang.Enum {
public static **[] values();
public static ** valueOf(java.lang.String);
}
# Explicitly preserve all serialization members. The Serializable interface
# is only a marker interface, so it wouldn't save them.
# You can comment this out if your library doesn't use serialization.
# If your code contains serializable classes that have to be backward
# compatible, please refer to the manual.
-keepnames class * implements java.io.Serializable
-keepclassmembers class * implements java.io.Serializable {
static final long serialVersionUID;
private static final java.io.ObjectStreamField[] serialPersistentFields;
!static !transient <fields>;
private void writeObject(java.io.ObjectOutputStream);
private void readObject(java.io.ObjectInputStream);
java.lang.Object writeReplace();
java.lang.Object readResolve();
}
-keepclassmembers class * {
#javax.annotation.Resource *;
}
-keepclassmembers class * {
#javax.persistence.Id <fields>;
}
-keepattributes RuntimeVisibleAnnotations
-keep #javax.persistence.* class * {
*;
}
-keep #org.springframework.stereotype.Service class *
-keep #org.springframework.stereotype.Component class *
-keep #org.springframework.stereotype.Controller class *
-keep #com.scsoft.afc.utility.scope.SpringViewScoped class *
-keep,allowobfuscation class com.test.** {*;}
-keep class com.test.service.** {
*;
}
And here is my <build> section from pom.xml:
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<configuration>
<encoding>utf-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<attachClasses>true</attachClasses>
<webResources>
<resource>
<directory>${project.build.directory}</directory>
<targetPath>WEB-INF/lib</targetPath>
<includes>
<include>*.jar</include>
</includes>
</resource>
<resource>
<directory>${project.build.directory}/classes</directory>
<targetPath>WEB-INF/classes</targetPath>
<includes>
<include>log4j.properties</include>
</includes>
</resource>
</webResources>
</configuration>
<executions>
<execution>
<id>war-exploded</id>
<phase>prepare-package</phase>
<goals>
<goal>exploded</goal>
</goals>
</execution>
<execution>
<id>default-war</id>
<phase>none</phase>
</execution>
<execution>
<id>war</id>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.4</version>
<configuration>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>default-install</id>
<phase>none</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.github.wvengen</groupId>
<artifactId>proguard-maven-plugin</artifactId>
<version>2.0.10</version>
<executions>
<execution>
<id>proguard</id>
<phase>prepare-package</phase>
<goals>
<goal>proguard</goal>
</goals>
</execution>
</executions>
<configuration>
<libs>
<lib>${java.bootstrap.classes}</lib>
<lib>${java.cryptographic.extension.classes}</lib>
<lib>${java.secure.socket.extension.classes}</lib>
<lib>${java.home}/lib/ext/jfxrt.jar</lib>
</libs>
<proguardInclude>${basedir}/proguard.conf</proguardInclude>
</configuration>
<dependencies>
<dependency>
<groupId>net.sf.proguard</groupId>
<artifactId>proguard-base</artifactId>
<version>5.2.1</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.4</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>

The problem was I was using attachClasses while I needed to use archiveClasses. Now everything works like a charm.

Related

Spring Cloud Contract EXPLICIT and WEBTESTCLIENT testMode

I want to use Spring Cloud Contract to produce my contracts and verify them. I want to use Spring WebFlux and Junit5. This is my Controller:
#RestController
#Slf4j
public class HelloWorldPortRESTAdapter implements HelloWorldPort {
#GetMapping(value = "/hello-world", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
#Override
public Mono<String> helloWorld() {
return Mono.just("Hello World!");
}
}
This is cloud contract maven plugin configuration:
<plugin>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<basePackageForTests>com.example.feedproviderapi.contract</basePackageForTests>
<testFramework>JUNIT5</testFramework>
<testMode>EXPLICIT</testMode>
</configuration>
</plugin>
But i don't know how base test class should look like. I tried this:
#ExtendWith(SpringExtension.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BaseTestClass {
#LocalServerPort
private int port;
#BeforeEach
void setup(){
RestAssured.baseURI = "http://localhost:" + this.port;
}
}
When I run mvn clean install, it returns java.net.ConnectException: Connection refused (Connection refused)
Then I changed testMode property in maven plugin to WEBTESTCLIENT and updated BaseTestClass like this:
#ExtendWith(SpringExtension.class)
#SpringBootTest
public class BaseTestClass {
#Autowired
WebApplicationContext context;
#BeforeEach
void setup(){
RestAssuredWebTestClient.standaloneSetup(context);
}
}
And again when I run mvn clean install now it returns:
You haven't configured a WebTestClient instance. You can do this statically
RestAssuredWebTestClient.mockMvc(..)
RestAssuredWebTestClient.standaloneSetup(..);
RestAssuredWebTestClient.webAppContextSetup(..);
or using the DSL:
given().
mockMvc(..). ..
Btw I tried RestAssuredWebTestClient.standaloneSetup(new HelloWorldPortRESTAdapter()); as well in my BaseTestClass but the result is same.
So how should I implement BaseTestClass regarding EXPLICIT and WEBTESTCLIENT testModes?
I have struggled for 3 days, to makes RestAssuredWebTestClient works.
Thanks a llooottt for : https://www.baeldung.com/spring-5-webclient
That's how i could do that:
#WebFluxTest
public class AnimeControllerIntegrTest{
WebTestClient testClient;
#Test
public void get_RA() {
testClient = WebTestClient.bindToServer().baseUrl("http://localhost:8080/animes").build();
RestAssuredWebTestClient
.given()
.webTestClient(testClient)
.when()
.get()
.then()
.statusCode(OK.value())
.body("name" ,hasItem("paulo"))
;
}
}
Please check the spring cloud contract samples https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/master/producer_webflux_webtestclient
And junit5
https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/master/producer_with_junit5
The
plugin
<plugin>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
<version>${spring-cloud-contract.version}</version>
<extensions>true</extensions>
<configuration>
<packageWithBaseClasses>com.example</packageWithBaseClasses>
<testMode>WEBTESTCLIENT</testMode>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<failIfNoTests>true</failIfNoTests>
</configuration>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit-platform-surefire-provider.version}</version>
</dependency>
</dependencies>
</plugin>
And The base class for junit5
public abstract class BeerRestBase {
#BeforeEach
public void setup() {
// remove::start[]
RestAssuredWebTestClient.standaloneSetup(new ProducerController(personToCheck -> personToCheck.age >= 20));
// remove::end[]
}
}
Try passing an ApplicationContext instance instead of WebApplicationContext.

Error generating signed APK due to proguard rules

Generating signed APK giving error after I updated Android Studio to 3.3-rc01 and enabled R8 code shrinking.
It is giving following proguard error :
Error: ~/app/proguard-rules.pro, offset: 2613, line: 74, column: 7, Expected char '-' at ~/app/proguard-rules.pro:74:7
-dump class_files.txt
before android studio 3.3-rc01 and without R8 code shrinking it was working perfectly fine.
Any workarounds for this or I have to disable the proguard rules now.
Following is my proguard-rules.pro file
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
# Retrofit does reflection on generic parameters and InnerClass is required to use Signature.
-keepattributes Signature, InnerClasses
# Retain service method parameters when optimizing.
-keepclassmembers,allowshrinking,allowobfuscation interface * {
#retrofit2.http.* <methods>;
}
# Ignore annotation used for build tooling.
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
# Ignore JSR 305 annotations for embedding nullability information.
-dontwarn javax.annotation.**
# Guarded by a NoClassDefFoundError try/catch and only used when on the classpath.
-dontwarn kotlin.Unit
# Top-level functions that can only be used by Kotlin.
-dontwarn retrofit2.-KotlinExtensions
# A resource is loaded with a relative path so the package of this class must be preserved.
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
# Animal Sniffer compileOnly dependency to ensure APIs are compatible with older versions of Java.
-dontwarn org.codehaus.mojo.animal_sniffer.*
# OkHttp platform used only on JVM and when Conscrypt dependency is available.
-dontwarn okhttp3.internal.platform.ConscryptPlatform
-dontwarn javax.xml.stream.**
-dontwarn rx.internal.util.unsafe.**
#Glide proguard rules
-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public class * extends com.bumptech.glide.module.AppGlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
**[] $VALUES;
public *;
}
-keep class android.support.v7.widget.LinearLayoutManager { *; }
-keep public class * extends android.support.v7.widget.RecyclerView$LayoutManager {
public <init>(...);
}
##---------------Begin: proguard configuration common for all Android apps ----------
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontskipnonpubliclibraryclassmembers
-dontpreverify
-verbose
-dump class_files.txt
-printseeds seeds.txt
-printusage unused.txt
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
-allowaccessmodification
-keepattributes *Annotation*
-renamesourcefileattribute SourceFile
-repackageclasses ''
-keep class com.qikcircle.qiketask.models.** { *; }
-keep class android.support.v4.** {*;}
-keep public class * extends android.app.Activity
-keep public class * extends android.support.v4.app.Fragment
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class com.android.vending.licensing.ILicensingService
-dontnote com.android.vending.licensing.ILicensingService
# Explicitly preserve all serialization members. The Serializable interface
# is only a marker interface, so it wouldn't save them.
-keepclassmembers class * implements java.io.Serializable {
static final long serialVersionUID;
private static final java.io.ObjectStreamField[] serialPersistentFields;
private void writeObject(java.io.ObjectOutputStream);
private void readObject(java.io.ObjectInputStream);
java.lang.Object writeReplace();
java.lang.Object readResolve();
}
# Preserve all native method names and the names of their classes.
-keepclasseswithmembernames class * {
native <methods>;
}
-keepclasseswithmembernames class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keepclasseswithmembernames class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}
# Preserve static fields of inner classes of R classes that might be accessed
# through introspection.
-keepclassmembers class **.R$* {
public static <fields>;
}
# Preserve the special static methods that are required in all enumeration classes.
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keep public class * {
public protected *;
}
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}
##---------------End: proguard configuration common for all Android apps ----------
##---------------Begin: proguard configuration for Gson ----------
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
# For using GSON #Expose annotation
# Gson specific classes
-keep class sun.misc.Unsafe { *; }
#-keep class com.google.gson.stream.** { *; }
# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { *; }
##---------------End: proguard configuration for Gson ----------
#removing logs
-assumenosideeffects class android.util.Log {
public static boolean isLoggable(java.lang.String, int);
public static int v(...);
public static int i(...);
public static int w(...);
public static int d(...);
public static int e(...);
}
#for getting crash reports
-assumenosideeffects class android.util.Log {
public static int v(...);
public static int d(...);
}
#Crashlytics proguard rules
-keepattributes SourceFile,LineNumberTable
-keep public class * extends java.lang.Exception
-ignorewarnings
-keep class * {
public private *;
}
I've tried the dump directive with Proguard (I didn't use it before) and all works fine.
[...]
## Strip Log.d
-assumenosideeffects class android.util.Log {
public static *** d(...);
}
-dump foo.txt
[...]
And I find my foo.txt under ./app/foo.txt
Printing classes to [./app/foo.txt]...
Then I enable R8 in legacy mode:
# For the bravests
android.enableR8=true
# For the crazyest. Must be enable also the previous setting
#android.enableR8.fullMode=true
And I got your error.
Without this line I can compile my APK even in full mode without any (apparent) issue.
So I confirm that this directive is not supported. Remember that R8 is still in beta. If you want you can submit an issue on the link I posted in comment.
Opened the issue here.
for me i had to remove the first line " public private *; " in my prograuard.pro file

force glassfish 4 to use jackson 2.3

I wrote an maven application which should run on Glassfish 4.
The Standard ApplicationConfig looks like this:
#javax.ws.rs.ApplicationPath("resources")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<Class<?>>();
// following code can be used to customize Jersey 2.0 JSON provider:
try {
Class jsonProvider = Class.forName("org.glassfish.jersey.jackson.JacksonFeature");
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
addRestResourceClasses(resources);
return resources;
}
The problem now is, that my resources which generate Json should use jackson 2.3 annotations.
But my glassfish uses some codehaus. ... packages to provide json. codehaus is the old version of jackson. I want to use the new one from fasterxml which provides the #JsonIdentityInfo annotation.
I thought that i could solve my problem by writing:
#javax.ws.rs.ApplicationPath("resources")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<Class<?>>();
resources.add(JacksonFeatures.class); //from the com.fasterxml.jackson.jaxrs.annotation Package
resources.add(JacksonJaxbJsonProvider.class);
resources.add(JacksonJsonProvider.class);
addRestResourceClasses(resources);
return resources;
}
But no effect. Now Glassfish uses the standard JsonProvider Moxy... which i dont want to use. Do you have any tips how i can force glassfish to use my library instead of the buildin-libraries? Or can i change the buildin library to the newer one?
And if you know how to solve this. could you please provide a little code-snippet?
EDIT 1:
After trying the first approach to solve it:
new ApplicationConfig:
#javax.ws.rs.ApplicationPath("resources")
public class ApplicationConfig extends ResourceConfig {
public ApplicationConfig() {
//register( new GZipEncoder() );
register( JacksonFeature.class );
}
private void addMyResources() {
//a lot of resources.
}
}
JacksonFeature:
public class JacksonFeature implements Feature {
public boolean configure( final FeatureContext context ) {
String postfix = '.' + context.getConfiguration().getRuntimeType().name().toLowerCase();
context.property( CommonProperties.MOXY_JSON_FEATURE_DISABLE + postfix, true );
context.register( JsonParseExceptionMapper.class );
context.register( JsonMappingExceptionMapper.class );
context.register( JacksonJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class );
return true;
}
}
pom:
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-base</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>2.4</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.4</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
</dependency>
</dependencies>
Dependencies:
http://i.stack.imgur.com/uA4V2.png
Error:
SEVERE: Exception while loading the app : CDI deployment failure:WELD-001408 Unsatisfied dependencies for type [Ref<ContainerRequest>] with qualifiers [#Default] at injection point [[BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] #Inject org.glassfish.jersey.server.internal.routing.UriRoutingContext(Ref<ContainerRequest>, ProcessingProviders)]
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [Ref<ContainerRequest>] with qualifiers [#Default] at injection point [[BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] #Inject org.glassfish.jersey.server.internal.routing.UriRoutingContext(Ref<ContainerRequest>, ProcessingProviders)]
at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:403)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:325)
at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:177)
...
or
SEVERE: Exception while loading the app
SEVERE: Undeployment failed for context /blueserver
INFO: file:/C:/bluetrail/blueserver/target/blueserver-0.0.0.1/WEB-INF/classes/_de.bluetrail_blueserver_war_0.0.0.1PU logout successful
SEVERE: Exception while loading the app : CDI deployment failure:WELD-001408 Unsatisfied dependencies for type [IterableProvider<InjectionResolver<Object>>] with qualifiers [#Default] at injection point [[BackedAnnotatedParameter] Parameter 2 of [BackedAnnotatedConstructor] #Inject org.glassfish.jersey.internal.inject.JerseyClassAnalyzer(#Named ClassAnalyzer, IterableProvider<InjectionResolver<Object>>)]
EDIT 2:
i will now post some classes of my project. In that classes i included all Annotations that i use.
i have like 16 entities like that:
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
#Entity
#JsonIdentityInfo(generator = ObjectIdGenerators.None.class, property = "id", scope=Address.class)
//the JsonIdentityInfo is the reason i need Jackson 2
public class Address implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String postalCode;
private String city;
private String country;
private String street;
private String houseNumber;
#Embedded
private Coordinate coordinate;
//getters, setters , etc.
}
then i have a lot of DAO's like that:
import de.ibs.trail.entity.Address;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
#Stateless
public class AddressDao extends GenericDao {
public Address getAddress(long id){
return em.find(Address.class, id);
}
public List<Address> getAddresses(){
List<Address> address = em.createQuery("SELECT a FROM Address a", Address.class).getResultList();
return address;
}
}
and finally i have a lot of REssources like that:
import de.bluetrail.blueserver.dao.AddressDao;
import de.ibs.trail.entity.Address;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
#Path("dummy")
#Stateless
public class DummyResource {
#Context
private UriInfo context;
#Inject userAuth user;
#Inject addressDao AddressDao;
public DummyResource() {
}
#GET
#Produces("application/json")
public List<Address> getAddress() {
return AddressDao.getAddresses();
}
}
Thats the first part. As a second part i have a class for some Google Services. Because i want to try to use some Google GeoLocation and Routing. I put the Google-Code into a pasteBin file, because its so huge:
http://pastebin.com/u3e0dms6
there i use libraries like:
import com.fasterxml.jackson.databind.ObjectMapper;
import de.ibs.trail.entity.Address;
//some other entities
//...
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Set;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
I hope that helps. All the other classes use the same annotations.
First make sure you have the following in your pom.xml:
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson.version}</version>
</dependency>
Then make sure you DO NOT have this in any pom.xml:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.5</version>
</dependency>
Then you need to disable moxy. The easiest way to do this is to ditch your Application class and replace is with a ResourceConfig class. First lets create YOUR JacksonFeature class:
public class JacksonFeature implements Feature {
public boolean configure( final FeatureContext context ) {
String postfix = '.' + context.getConfiguration().getRuntimeType().name().toLowerCase();
context.property( CommonProperties.MOXY_JSON_FEATURE_DISABLE + postfix, true );
context.register( JsonParseExceptionMapper.class );
context.register( JsonMappingExceptionMapper.class );
context.register( JacksonJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class );
return true;
}
}
Two interesting things here, first I disabled moxy and second I made sure to add the JacksonException mappers. This way you will get better errors than internal server error if there is a parsing or generation exception. Okay, last step it so rewrite your Application as a ResourceConfig class:
#javax.ws.rs.ApplicationPath("resources")
public class RestApplication extends ResourceConfig {
public RestApplication() {
register( new GZipEncoder() );
register( JacksonFeature.class );
}
private void addMyResources() {
register( MyResource1.class );
register( MyResource2.class );
}
}
That should do it. Also, instead of registering the resources one by one like this, if you know their path you can just remove all that code and add this to the constructor of RestApplication:
package( "com.me.myrestresourcespackage" );
Hope this helps.

How to pass parameters to guicified TestNG test from Surefire Maven plugin?

I'm using Maven + Surefire + TestNG + Guice (latest stable ones)
I have "large" test that requires Guice to run.
Basically I'm doing it this way:
#Test(groups = "large")
#Guice(modules = FooLargeTest.Module.class)
public class FooLargeTest {
public static class Module extends AbstractModule {
public void configure() {
bindConstant().annotatedWith(FooPort.class).to(5000);
// ... some other test bindings
}
}
#Inject Provider<Foo> fooProvider;
#Test
public void testFoo() {
Foo foo = fooProvider.get() // here injection of port is done
// it could not be passed to constructor
// ... actual test of foo
}
}
The problem is that FooPort is hardcoded to 5000. It is a Maven property, so the first try was to use next Surefire configuration:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
<systemPropertyVariables>
<fooPort>${foo.port}</fooPort>
</systemPropertyVariables>
</configuration>
</plugin>
And after that request it like System.getProperty("fooPort"). Unfortunately, documentation says, that this is only for JUnit test. At least I could not see this system variable during debugging of a test. I tried forkMode both default one and never, it does not change anything. For TestNG tests it's recommended to make it this way:
<properties>
<property>
<name>fooPort</name>
<value>${foo.port}</value>
</property>
</properties>
But now I should use this property from Guice, so it should be given somehow to GuiceModule, I've tried it next way:
#Test(groups = "large")
#Guice(moduleFactory = FooLargeTest.ModuleFactory.class)
public class FooLargeTest {
public static class ModuleFactory extends AbstractModule {
private final String fooPort = fooPort;
#Parameters("fooPort")
public ModuleFactory(String fooPort) {
this.fooPort = fooPort;
}
public Module createModule(final ITestContext context, Class<?> testClass) {
return new AbstractModule {
public void configure() {
bindConstant().annotatedWith(FooPort.class).to(fooPort);
// ... some other test bindings
}
}
}
}
#Inject Provider<Foo> fooProvider;
#Test
public void testFoo() {
Foo foo = fooProvider.get() // here injection of port is done
// actual test of foo
}
}
But this way was also a failure as creator for modulefactories does not take #Parameters into account and thus could not create instance of a factory.
Looks like I should try to get some data from ITestContext context, but I do not know how and if the data is there or if there is some simpler way to do what I want.
Thanks for a response.
I just ran a quick test and properties seem to be passed correctly to TestNG:
<configuration>
<suiteXmlFiles>
<suiteXmlFile>src/test/resources/testng-single.yaml</suiteXmlFile>
</suiteXmlFiles>
<systemPropertyVariables>
<foo>bar</foo>
</systemPropertyVariables>
My suite file calls the test class B, which contains:
#Test
public void f() {
System.out.println(" property:" + System.getProperty("foo"));
}
and running it with Maven shows:
property:bar
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.358 sec
I'm not using Guice in this simple example but that's the only difference between your code and mine.
Feel free to create a small Maven project reproducing your problem, make sure that I can compile it and then email it to me.
I tried below test and works fine
My Pom file
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
<configuration>
<!--<groups>Regression</groups> -->
<systemPropertyVariables>
<environment>UAT</environment>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
My TestNG test
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class TestAuthentication {
#Test (groups = { "Sniff", "Regression" })
public void validAuthenticationTest(){
System.out.println(" property:" + System.getProperty("environment"));
}
#Test (groups = { "Regression" },parameters = {"environment"})
public void failedAuthenticationTest(String environment){
System.out.println("Regression-"+environment);
}
#Parameters("environment")
#Test (groups = { "Sniff"})
public void newUserAuthenticationTest(String environment){
System.out.println("Sniff-"+environment);
}
}

How to make m2eclipse (Maven) point to the "persistence.xml" path?

I working with Eclipse Helios, m2eclipse Maven plugin and Glassfish plugin.
I edited the "pom.xml" file so that I can get the DerbyClient and the JPA Persistence classes.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.apress.javaee6</groupId>
<artifactId>chapter02</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>chapter02</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.6.1.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4.3</version>
<type>maven-plugin</type>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>EclipseLink Repo</id>
<url>http://www.eclipse.org/downloads/download.php?r=1&nf=1&file=/rt/eclipselink/maven.repo</url>
</repository>
</repositories>
</project>
Then, I created the "src/main/resrouce" directory and put a "persistence.xml" file that contains:
<xml version="1.0" encoding="UTF-8">
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="chapter02PU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.apress.javaee6.chapter02.Book</class>
<properties>
<property name="eclipselink.target-datababase" value="DERBY"/>
<property name="eclipselink.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="eclipselink.jdbc.url" value="jdbc:derby://localhost:1527/chapter02DB;create=true"/>
<property name="eclipselink.jdbc.user" value="APP"/>
<property name="eclipselink.jdbc.password" value="APP"/>
<property name="eclipselink.jdbc.ddl-generation" value="create-tables"/>
<property name="eclipselink.jdbc.logging-level" value="INFO"/>
</properties>
</persistence-unit>
</persistence>
</xml>
Of course, the derby server runs perfectly.
And I have create the following Book Class:
package com.apress.javaee6.chapter02;
import javax.persistence.*;
#Entity
#NamedQuery(name="findAllBooks", query="SELECT b from Book b")
public class Book {
#Id #GeneratedValue
private Long id;
#Column(nullable = false)
private String title;
private float price;
#Column(length = 1000)
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
public Book() {
super();
}
public Book(Long id, String title, float price, String description,
String isbn, Integer nbOfPage, Boolean illustrations) {
super();
this.id = id;
this.title = title;
this.price = price;
this.description = description;
this.isbn = isbn;
this.nbOfPage = nbOfPage;
this.illustrations = illustrations;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Integer getNbOfPage() {
return nbOfPage;
}
public void setNbOfPage(Integer nbOfPage) {
this.nbOfPage = nbOfPage;
}
public Boolean getIllustrations() {
return illustrations;
}
public void setIllustrations(Boolean illustrations) {
this.illustrations = illustrations;
}
}
The main function is here:
package com.apress.javaee6.chapter02;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
// Create an instance of book
Book book = new Book();
book.setTitle("The Hitchhiker's guide to the Galaxy");
book.setPrice(12.5F);
book.setDescription("Science fiction comedy book");
book.setIsbn("1-84023-742-2");
book.setIllustrations(false);
// Gets an entity manager and a transaction
EntityManagerFactory emf = Persistence.createEntityManagerFactory("chapter02PU");
EntityManager em = emf.createEntityManager();
// Persists the book to the database
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
em.persist(book);
tx.commit();
em.close();
emf.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The problem is that the "persistence.xml" is not recognized.
How can I make Maven point to the "persistence.xml" file?
When I active the Maven console and "Update Dependencies", I got the following (bad) info:
28/06/10 15:20:36 CEST: [INFO] Using 'UTF-8' encoding to copy filtered resources.
28/06/10 15:20:36 CEST: [INFO] skip non existing resourceDirectory /home/zakaria/workspace/chapter02/src/main/resources
28/06/10 15:20:36 CEST: [INFO] Using 'UTF-8' encoding to copy filtered resources.
28/06/10 15:20:36 CEST: [INFO] skip non existing resourceDirectory /home/zakaria/workspace/chapter02/src/test/resources
So i think he tried somewhere to create the "resources" directories and cannot get them after the build.
Thank you so much ;)
Regards
You don't tell maven to "point" on a file, you put files in a directory that end up on the class path. For resources, you're supposed to use src/main/resources.
In other words, just put the persistence.xml in src/main/resources/META-INF.
I'm using m2eclipse 0.10.0 and I don't use any special workaround, it just works for at least 3 projects in my workspace of type jar, ejb and war.
If you're using m2eclipse 0.10.0, not having the resources recognized is a known problem (see m2eclipse user list). There is a workaround described here:
https://docs.sonatype.org/pages/viewpage.action?pageId=2949459
Using maven-resources-plugin version 2.4.2 or 2.4.3 may also work better than 2.4.
According to JPA standard persistence.xml should reside in the root of META-INF folder. So putting in into src/main/resources/META-INF should work