I'm following AWS lambda's "create a jar using mvn":
http://docs.aws.amazon.com/lambda/latest/dg/java-create-jar-pkg-maven-no-ide.html
and some reason when I try to do either "mvn clean install" nor "mvn package" run properly. the project is using java 8.
Here's my pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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>lambda</groupId>
<artifactId>test</artifactId>
<packaging>jar</packaging>
<version>0.0.0.1-SNAPSHOT</version>
<name>lambda-test</name>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
and my code:
package lambda.test;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.google.gson.Gson;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.util.Objects;
import java.util.Properties;
import java.util.Vector;
public class Test {
private static final Gson gson = new Gson();
public static String myHandler(Tester tester, Context context) {
LambdaLogger logger = context.getLogger();
logger.log("received: " + tester);
try {
JSch jSch = new JSch();
Session session = jSch.getSession(username, sftpHost, sftpPort);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect(15000);
ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
channel.cd("Inbox");
Vector<ChannelSftp.LsEntry> list = channel.ls(".");
logger.log("the list ==> \n" + gson.toJson(list));
} catch (Exception e) {
e.printStackTrace();
logger.log("the exception: " + e.getMessage());
}
return String.valueOf(tester);
}
public static class Tester {
private final String name;
private final Integer id;
public Tester(String name, Integer id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public Integer getId() {
return id;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tester tester = (Tester) o;
return Objects.equals(name, tester.name) &&
Objects.equals(id, tester.id);
}
#Override
public int hashCode() {
return Objects.hash(name, id);
}
#Override
public String toString() {
return gson.toJson(this);
}
}
}
Maybe you must set the java -version of your project, and tell to the maven compiler the value of these setting like below :
<project>
[...]
<build>
[...]
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
[...]
</build>
[...]
</project>
I think it will working better right now!
You can look at https://maven.apache.org/plugins/maven-compiler-plugin/examples/compile-using-different-jdk.html and other sections.
Related
I am trying to upgrade the log4j version to 2.16.0 with the springboot version 2.6.2 .After upgrading My code is failing with the below error while connecting to MongoDB database .Which version of spring-data-mongodb is compatible with the springboot version 2.6.2 .Could anyone suggest which version of Mongodb is the proper version for the below Java code . Any help would be appreciated
Error:(51,27) java: package MongoClientOptions does not exist . My pom.xml as like below
<?xml version="1.0" encoding="UTF-8"?>
<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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
<relativePath/>
</parent>
<groupId>com.sample</groupId>
<artifactId>SampleService</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SampleService</name>
<description>Project for Service</description>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<surefire-plugin.version>2.22.0</surefire-plugin.version>
<log4j2.version>2.17.0</log4j2.version>
</properties>
<dependencyManagement>
<dependencies>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>3.2.3</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.2.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestone</id>
<name>Spring Maven MILESTONE Repository</name>
<url>https://repo.spring.io/libs-milestone</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<systemProperties>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
</systemProperties>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.2</version>
<configuration>
<arguments>
<source>1.8</source>
<target>1.8</target>
<uberJar>true</uberJar>
</arguments>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
My Application Java Code :
package com.sample;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;
#SpringBootApplication
public class Application implements CommandLineRunner {
private static final Logger LOG = LoggerFactory.getLogger(Application.class);
//private String uri;
private String database;
private String host;
private String username;
private String password;
private int port;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... args) throws Exception {
LOG.info("Application Running.......");
}
public #Bean
com.mongodb.MongoClient mongoClient() {
MongoClientOptions.Builder mongoClientOptions = MongoClientOptions.builder().sslInvalidHostNameAllowed(true)
.sslEnabled(true).applicationName("Sample-Service");
try {
KeyStore keystore = KeyStore.getInstance("JKS");
try (InputStream in = new FileInputStream("/mnt/secrets/keystore.jks")) {
keystore.load(in, "password".toCharArray());
} catch (IOException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, "password".toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
mongoClientOptions.sslContext(sslContext);
} catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
e.printStackTrace();
}
MongoClientOptions mops = mongoClientOptions.build();
MongoCredential mongoCredential = MongoCredential.createCredential(username, database, password.toCharArray());
MongoClient mongoClient = new MongoClient(new ServerAddress(host, port), mongoCredential, mops);
return mongoClient;
}
// #Value("${spring.data.mongodb.uri}")
// public void setUri(String uri) {
// this.uri = uri;
// }
public String getDatabase() {
return database;
}
#Value("${spring.data.mongodb.authentication-database}")
public void setDatabase(String database) {
this.database = database;
}
public String getHost() {
return host;
}
#Value("${spring.data.mongodb.host}")
public void setHost(String host) {
this.host = host;
}
public String getUsername() {
return username;
}
#Value("${spring.data.mongodb.username}")
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
#Value("${spring.data.mongodb.password}")
public void setPassword(String password) {
this.password = password;
}
public int getPort() {
return port;
}
#Value("${spring.data.mongodb.port}")
public void setPort(int port) {
this.port = port;
}
}
Your pom.xml is asking for mongodb-driver-sync 4.2.3. Some of the classes moved or were retired in the 4.x version; for example, com.mongodb.MongoClient is now com.mongodb.client.MongoClient. Your code appears to be 3.x API compatible. You will have to spend a few minutes to rework your options setup to be compatible with the new classes. See the API docs https://mongodb.github.io/mongo-java-driver/4.2/apidocs for more.
UPDATED
I took a look and the migration to the new classes is not trivial and I hadn't used non-connection string based material in a long time so I reworked the critical parts of the code above. Note that credential, sslsettings, and connectionstring objects are designed to be built in slightly different ways which can lead to some confusion at first.
import com.mongodb.client.MongoClient; // interface
import com.mongodb.client.MongoClients; // factory
import com.mongodb.MongoClientSettings; // yes, *not* in the .client hierarchy!
import com.mongodb.MongoCredential;
import com.mongodb.ConnectionString;
MongoCredential credentials = MongoCredential.createCredential(
"USER", "ADMIN_DB", "PASSWORD".toCharArray());
String conns = String.format("mongodb://%s:%d/?replicaSet=rs0", "localhost", 27017);
MongoClientSettings.Builder mcsb = MongoClientSettings.builder();
MongoClientSettings mcs = mcsb
.applicationName("Sample-Service")
.credential(credentials)
.applyToSslSettings(sslb ->
sslb.enabled(true)
.invalidHostNameAllowed(true))
.applyConnectionString(new ConnectionString(conns))
.build();
MongoClient client = MongoClients.create(mcs);
I think you should upgrade your dependencies. Please see the version and pom
Please try:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>3.3.0</version>
</dependency>
<!-- reactive: Do you really need it? -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.4.0</version>
</dependency>
Suggestion
If you use spring-boot, and you can try org.springframework.boot:spring-boot-starter-data-mongodb to auto config.
I am trying to use RestEasy in a Jetty application. I am using Jackson for serializing/deserializing my POJOs. I need my serialization to be polymorphic since I have endpoints that handle a POJO type that has sub-types. I thought I could use resteasy-jackson-provider to provide my MessageBodyWriter and MessageBodyReader implementations.
When I call an endpoint I get the following error:
java.lang.NoClassDefFoundError: org/jboss/resteasy/util/FindAnnotation
at org.jboss.resteasy.plugins.providers.jackson.ResteasyJacksonProvider.isWriteable(ResteasyJacksonProvider.java:42)
at org.jboss.resteasy.core.providerfactory.ResteasyProviderFactoryImpl.resolveMessageBodyWriter(ResteasyProviderFactoryImpl.java:1322)
at org.jboss.resteasy.core.providerfactory.ResteasyProviderFactoryImpl.getMessageBodyWriter(ResteasyProviderFactoryImpl.java:1293)
at org.jboss.resteasy.core.ServerResponseWriter.lambda$writeNomapResponse$2(ServerResponseWriter.java:112)
at org.jboss.resteasy.core.interception.jaxrs.ContainerResponseContextImpl.filter(ContainerResponseContextImpl.java:405)
at org.jboss.resteasy.core.ServerResponseWriter.executeFilters(ServerResponseWriter.java:232)
at org.jboss.resteasy.core.ServerResponseWriter.writeNomapResponse(ServerResponseWriter.java:97)
at org.jboss.resteasy.core.ServerResponseWriter.writeNomapResponse(ServerResponseWriter.java:70)
at org.jboss.resteasy.core.SynchronousDispatcher.writeResponse(SynchronousDispatcher.java:578)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:508)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:252)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:153)
at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:363)
at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:156)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:238)
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:249)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:60)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:841)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:535)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:188)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1253)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:168)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:473)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:166)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1155)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.Server.handle(Server.java:561)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:334)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:104)
at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:247)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.produce(EatWhatYouKill.java:140)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:679)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:597)
at java.base/java.lang.Thread.run(Thread.java:834)
Here's my POM file:
<?xml version="1.0" encoding="UTF-8"?>
<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.foster.app</groupId>
<artifactId>jettyRestEasyApiService</artifactId>
<version>3.0.0</version>
<packaging>jar</packaging>
<name>Jetty-RESTEasy Api Service</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<version.jetty>9.4.7.v20170914</version.jetty>
</properties>
<dependencies>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${version.jetty}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-core</artifactId>
<version>4.2.0.Final</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>3.9.0.Final</version>
</dependency>
</dependencies>
<build>
<finalName>JettyRestEasyApiService</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archive>
<manifest>
<mainClass>com.foster.app.resteasy.rest.App</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Here's my Main class:
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher;
public class App {
private static final Logger LOGGER = Logger.getLogger(App.class.getName());
private static final String APPLICATION_PATH = "/jetty/resteasy";
private static final String CONTEXT_ROOT = "/";
private static final Server JETTY_SERVER = new Server(8080);
public App() {}
public static void main(String[] args) throws Exception {
try {
new App().run();
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "Application Exception", ex);
throw ex;
} finally {
if (JETTY_SERVER != null) {
JETTY_SERVER.destroy();
}
}
}
public void run() throws Exception {
final ServletContextHandler context = new ServletContextHandler(JETTY_SERVER, CONTEXT_ROOT);
final ServletHolder restEasyServlet = new ServletHolder(new HttpServletDispatcher());
restEasyServlet.setInitParameter("resteasy.servlet.mapping.prefix", APPLICATION_PATH);
restEasyServlet.setInitParameter("javax.ws.rs.Application", JaxRsActivator.class.getCanonicalName());
context.addServlet(restEasyServlet, APPLICATION_PATH + "/*");
final ServletHolder defaultServlet = new ServletHolder(new DefaultServlet());
context.addServlet(defaultServlet, CONTEXT_ROOT);
JETTY_SERVER.start();
LOGGER.log(Level.INFO, "Started Server");
JETTY_SERVER.join();
LOGGER.log(Level.INFO, "Joined Server");
}
}
Here's my Application class:
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
public class JaxRsActivator extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new HashSet<>();
resources.add(MessageResource.class);
resources.add(TestResource.class);
return resources;
}
}
Here are my POJO classes:
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import java.io.Serializable;
import java.util.Date;
#JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "$type")
#JsonSubTypes({
#JsonSubTypes.Type(
value = PojoDog.class,
name = "PojoDog"),
#JsonSubTypes.Type(
value = PojoCat.class,
name = "PojoCat")
})
public abstract class Pojo implements Serializable {
public String property1;
public String property2;
public int property3;
public Date property4;
}
public class PojoCat extends Pojo {
public long sebastian;
}
public class PojoDog extends Pojo {
public String clifford;
}
Here's my endpoint:
#Path("/test")
public class TestResource {
#GET
#Path("pojo")
#Produces(MediaType.APPLICATION_JSON)
public Response getPojo() {
Pojo pojo = new PojoDog();
pojo.property1 = "Hello";
pojo.property2 = "World";
pojo.property3 = 5;
pojo.property4 = new Date();
((PojoDog)pojo).clifford = "I am a dog.";
return Response.ok(pojo).build();
}
}
The class org.jboss.resteasy.util.FindAnnotation is part of the resteasy-jaxrs artifact.
See search:
https://search.maven.org/search?q=fc:org.jboss.resteasy.util.FindAnnotation
That pointed me to see that you have mixed resteasy versions.
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-core</artifactId>
<version>4.2.0.Final</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>3.9.0.Final</version>
</dependency>
That's 100% not valid, you need to use the same resteasy version everywhere.
So from that, I took your code and made a few simple changes, and it worked.
I upgraded to Jetty 9.4.20.v20190813.
Upgraded to org.jboss.resteasy/resteasy-jackson2-provider/4.2.0.Final
Removed the two Jackson dependencies from the pom entirely, relied on them coming from transitive dependency on resteasy-jackson2-provider
<!-- REMOVED : no point having them here
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.9</version>
</dependency>
-->
I initialized the ServletContextHandler slightly differently (don't pass server into constructor, as that's the job of the handler tree).
final ServletContextHandler context = new ServletContextHandler();
final ServletHolder restEasyServlet = new ServletHolder(new HttpServletDispatcher());
context.setContextPath(CONTEXT_ROOT);
restEasyServlet.setInitParameter("resteasy.servlet.mapping.prefix", APPLICATION_PATH);
restEasyServlet.setInitParameter("javax.ws.rs.Application", JaxRsActivator.class.getCanonicalName());
context.addServlet(restEasyServlet, APPLICATION_PATH + "/*");
final ServletHolder defaultServlet = new ServletHolder("default", DefaultServlet.class); // the name "default" here is important
context.addServlet(defaultServlet, "/"); // this is not context-root, it's the default url-pattern
HandlerList handlers = new HandlerList();
handlers.addHandler(context);
handlers.addHandler(new DefaultHandler()); // to report errors that don't match the root context better
JETTY_SERVER.setHandler(handlers);
JETTY_SERVER.start();
I'm having some difficulties importing a utility jar file containing some custom aspects into another project. It should be noted, that I'm not using Spring for this project, as my client is somewhat averse to Spring.
I have created a proof of concept (full code example below). When I run a test runner in the utility jar, any method annotated with my AspectJ annotation gets their aspects executed just fine. When I use the self-same jar in another project, the aspects are ignore.
When I run the main class in the utility I get:
$> java -cp aspectjrt-1.8.2.jar;aop-util-1.0-SNAPSHOT.jar TestOne
AspectOne's aroundAdvice's body is now executed Before aspectTestMethod is called.
Executing TestOne.aspectTestMethod()
AspectOne's aroundAdvice's body is now executed After aspectTestMethod is called.
If I run the main class of the consumer class, I get:
$>java -cp aspectjrt-1.8.2.jar;aop-util-1.0-SNAPSHOT.jar;aop-consumer-1.0-SNAPSHOT.jar Test
Test.testAspectOne
AspectTwo's aroundAdvice's body is now executed Before aspectTestMethod is called.
Test.testAspectTwo
AspectTwo's aroundAdvice's body is now executed After aspectTestMethod is called.
As I'm fairly new to aspect oriented programming, I'd really appreciate a pointer as to what I'm missing :)
utility jar
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>sandbox.aop</groupId>
<artifactId>aop-util</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<configuration>
<complianceLevel>1.8</complianceLevel>
<source>1.8</source>
<target>1.8</target>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Annotation
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface AnnotationOne { }
Aspect
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.JoinPoint;
#Aspect
public class AspectOne {
#Pointcut("#annotation(AnnotationOne)")
public void annotationPointCutDefinition(){
}
#Pointcut("execution(* *(..))")
public void atExecution(){}
#Around("#annotation(AnnotationOne) && execution(* *(..))")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
Object returnObject = null;
try {
System.out.println("AspectOne's aroundAdvice's body is now executed Before aspectTestMethod is called.");
returnObject = joinPoint.proceed();
} catch (Throwable throwable) {
throw throwable;
}
finally {
System.out.println("AspectOne's aroundAdvice's body is now executed After aspectTestMethod is called.");
}
return returnObject;
}
#After("annotationPointCutDefinition() && atExecution()")
public void printNewLine(JoinPoint pointcut){
System.out.print("\n\r");
}
}
Main class
public class TestOne {
public static void main(String[] args) {
TestOne testOne = new TestOne();
testOne.aspectTestMethod();
}
#AnnotationOne
public void aspectTestMethod(){
System.out.println("Executing TestOne.aspectTestMethod()");
}
}
AOP consumer
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>sandbox.aop</groupId>
<artifactId>aop-consumer</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>sandbox.aop</groupId>
<artifactId>aop-util</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<configuration>
<complianceLevel>1.8</complianceLevel>
<source>1.8</source>
<target>1.8</target>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Annotation
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface AnnotationTwo {}
Aspect
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class AspectTwo {
#Pointcut("#annotation(AnnotationTwo)")
public void annotationPointCutDefinition(){
}
#Pointcut("execution(* *(..))")
public void atExecution(){}
#Around("#annotation(AnnotationTwo) && execution(* *(..))")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
Object returnObject = null;
try {
System.out.println("AspectTwo's aroundAdvice's body is now executed Before aspectTestMethod is called.");
returnObject = joinPoint.proceed();
} catch (Throwable throwable) {
throw throwable;
}
finally {
System.out.println("AspectTwo's aroundAdvice's body is now executed After aspectTestMethod is called.");
}
return returnObject;
}
#After("annotationPointCutDefinition() && atExecution()")
public void printNewLine(JoinPoint pointcut){
System.out.print("\n\r");
}
}
Main class
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.testAspectOne();
test.testAspectTwo();
}
#AnnotationOne
public void testAspectOne() {
System.out.println(Test.class.getName() + ".testAspectOne");
}
#AnnotationTwo
public void testAspectTwo() {
System.out.println(Test.class.getName() + ".testAspectTwo");
}
}
You need to tell the aspectj weaver to weave aspect defined in your library using aspectLibraries:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<configuration>
<complianceLevel>1.8</complianceLevel>
<source>1.8</source>
<target>1.8</target>
<aspectLibraries>
<aspectLibrary>
<groupId>sandbox.aop</groupId>
<artifactId>aop-util</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
Hi I am doing a small POC with AWS Lambda using Java,
I want to test a simple Lambda function call, which will accept a string
I am using Google's Gson to convert String to Json and use it in my demo program.
I referred this documentation for my demo -
http://docs.aws.amazon.com/lambda/latest/dg/get-started-step4-optional.html
and
http://docs.aws.amazon.com/lambda/latest/dg/java-create-jar-pkg-maven-and-eclipse.html
Here's my Project directory structure -
I am getting an error when I call the Lambda function with the following String -
"{'name':'Aniruddha','age':'25'}"
Here's the error -
{
"errorMessage": "com/google/gson/GsonBuilder",
"errorType": "java.lang.NoClassDefFoundError",
"stackTrace": [
"example.Hello.myHandler(Hello.java:11)",
"sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)",
"sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)",
"sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)",
"java.lang.reflect.Method.invoke(Method.java:498)"
]
}
Here's my Handler function -
package example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Hello {
public String myHandler(String request, Context context) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
QueryParams queryParams = gson.fromJson(request, QueryParams.class);
System.out.println("Name is: "+queryParams.getName()+" Age is: "+queryParams.getAge());
LambdaLogger logger = context.getLogger();
logger.log("received a Lambda request");
String message = "Hey there! " + queryParams.getName() + " you are " + queryParams.getAge() + " years old";
return message;
}
}
This is my PoJo -
package example;
public class QueryParams {
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
This is the pom.xml -
<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>doc-examples</groupId>
<artifactId>lambda-java-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>lambda-java-example</name>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-lambda-java-core -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Alright as #JBNizet advised (check question's comments),
It solved the issue.
Here's the pom.xml we need -
<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>doc-examples</groupId>
<artifactId>lambda-java-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>lambda-java-example</name>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-lambda-java-core -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
I have a very simple ejb 3.0 module with maven, it has only two session beans one stateless and the other is singleton...when I am trying to deploy the project on Glassfish 3.0 server, I got this exception:
Error occurred during deployment: Exception while deploying the app :
Invalid ejb jar : it contains zero ejb. Note: 1. A valid ejb jar
requires at least one session, entity (1.x/2.x style), or
message-driven bean. 2. EJB3+ entity beans (#Entity) are POJOs and
please package them as library jar. 3. If the jar file contains valid
EJBs which are annotated with EJB component level annotations
(#Stateless, #Stateful, #MessageDriven, #Singleton), please check
server.log to see whether the annotations were processed properly..
Please see server.log for more details.
I verify the project with the Glassfish Verifier Tool, I got this exception, but I don't know what should I do?
Verifier output unparsable
Verifier output (C:\Users\Mariam.Moustafa\Documents\NetBeansProjects\web\EmployeesTimer\target\EmployeesTimer-1.0-SNAPSHOT.jar.xml) not found.
Here is The pom.xml:
<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.unilever</groupId>
<artifactId>EmployeesTimer</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>ejb</packaging>
<name>EmployeesTimer</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.2</version>
</dependency>
<!-- slf4j Logger -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-ejb-plugin</artifactId>
<version>2.3</version>
<configuration>
<ejbVersion>3.1</ejbVersion>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>6.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>unknown-jars-temp-repo</id>
<name>A temporary repository created by NetBeans for libraries and jars it could not identify. Please replace the dependencies in this repository with correct ones and delete this repository.</name>
<url>file:${project.basedir}/lib</url>
</repository>
<repository>
<id>m2.dev.java.net</id>
<url>http://download.java.net/maven/2</url>
<layout>default</layout>
</repository>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
</project>
I confirm that I have 2 simple ejb
#Stateless public class EmployeesFacade {}
#Singleton public class TimerService {
#EJB EmployeesFacade emloyeesFacade;
}
Here is the code:
First #singleton ejb bean
package com.employeestimer.services;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.unilever.employeestimer.enums.ConnectionEnum;
import com.unilever.employeestimer.exceptions.BusinessException;
import java.io.IOException;
import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.naming.NamingException;
import javax.ws.rs.core.MediaType;
import org.codehaus.jackson.JsonProcessingException;
import org.slf4j.LoggerFactory;
#Singleton
public class TimerService {
static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(TimerService.class);
#EJB
EmployeesFacade emloyeesFacade;
private final static String U_ENGAGE_URL = "http://..../webresources/employees/update";
#Schedule(second="*", minute="*/1",hour="*", persistent=false)
public void doWork() throws JsonProcessingException, IOException, NamingException{
try{
String input = emloyeesFacade.getUsersData(ConnectionEnum.USERNAME.getCode(), ConnectionEnum.PASSWORD.getCode());
consumeRESTfulWebService(input);
}catch(BusinessException e){
LOGGER.error("",e);
}
}
private void consumeRESTfulWebService(String input){
try {
LOGGER.debug("input = " + input);
Client client = Client.create();
WebResource webResource = client.resource(U_ENGAGE_URL);
ClientResponse response = webResource.type(MediaType.TEXT_PLAIN).post(ClientResponse.class, input);
if (response.getStatus() != ClientResponse.Status.NO_CONTENT.getStatusCode()) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
LOGGER.debug("Output from Server .... \n");
} catch (Exception e) {
LOGGER.error("",e);
}
}
}
and here is the Facade bean:
package com.employeestimer.services;
import com.employeestimer.beans.EmployeeData;
import com.employeestimer.enums.ConfigurationsEnum;
import com.employeestimer.enums.ConnectionEnum;
import com.employeestimer.exceptions.BusinessException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import javax.ejb.Stateless;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.PagedResultsControl;
import javax.naming.ldap.PagedResultsResponseControl;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.slf4j.LoggerFactory;
#Stateless
public class EmployeesFacade {
static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(EmployeesFacade.class);
public String getLDAPConnectionType() {
return ConfigurationsEnum.LDAP_Connection_Type.getCode();
}
public String getDomain() {
return ConfigurationsEnum.DOMAIN.getCode();
}
public String getLDAPIP() {
return ConfigurationsEnum.LDAP_IP.getCode();
}
public String getLDAPPort() {
return ConfigurationsEnum.LDAP_PORT.getCode();
}
public String getLDAPBase() {
return ConfigurationsEnum.LDAP_BASE.getCode();
}
private LdapContext getContext(String username, String password) throws BusinessException, NamingException {
Hashtable env = new Hashtable();
if (getDomain() == null || getLDAPConnectionType() == null
|| getLDAPIP() == null || getLDAPPort() == null) {
throw new BusinessException("error_general");
}
String domain = getDomain();
String url = getLDAPConnectionType() + "://" + getLDAPIP() + ":" + getLDAPPort();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.REFERRAL, "follow");
if (!username.contains("#")) {
username = username + "#" + domain;
}
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, password);
return new InitialLdapContext(env, null);
}
public String getUsersData(String username, String password) throws BusinessException, JsonProcessingException, IOException, NamingException {
List<EmployeeData> employeelist = new ArrayList<EmployeeData>();
EmployeeData employee;
String json = "";
try {
LdapContext context = getContext(username, password);
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = {"mail"}; //, "sn", "cn", "c", "l"};
constraints.setReturningAttributes(attrIDs);
// Activate paged results
int pageSize = Integer.parseInt(ConnectionEnum.PAGESIZE.getCode());
byte[] cookie = null;
context.setRequestControls(new Control[]{new PagedResultsControl(pageSize,
Control.NONCRITICAL)});
int total;
NamingEnumeration<SearchResult> result = null;
do {
/* perform the search */
result = context.search(getLDAPBase(), "(&(objectClass=User)(c=EG))", constraints);
/* for each entry print out name + all attrs and values */
while (result != null && result.hasMore()) {
SearchResult entry = (SearchResult) result.next();
employee = new EmployeeData();
Attribute attribute;
if (entry.getAttributes() != null) {
if (entry.getAttributes().get("mail") != null) {
attribute = entry.getAttributes().get("mail");
employee.setEmail(attribute != null ? attribute.toString().replace("mail: ", "") : "");
employeelist.add(employee);
}
}
}
// Examine the paged results control response
Control[] controls = context.getResponseControls();
if (controls != null) {
for (int i = 0; i < controls.length; i++) {
if (controls[i] instanceof PagedResultsResponseControl) {
PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
total = prrc.getResultSize();
if (total != 0) {
LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total + ") *****************\n");
} else {
LOGGER.debug("***************** END-OF-PAGE " + "(Page no. " + i + ") ***************\n");
}
cookie = prrc.getCookie();
}
}
} else {
LOGGER.debug("No controls were sent from the server");
}
// Re-activate paged results
context.setRequestControls(new Control[]{new PagedResultsControl(
pageSize, cookie, Control.CRITICAL)});
} while (cookie != null);
//result.close();
context.close();
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
json = ow.writeValueAsString(employeelist);
LOGGER.debug("\n \n \n ************* \n ************* \n ************* \n \n THE SIZE = " + employeelist.size() + "\n \n ************* \n ************* \n ************* \n \n \n");
} catch (NamingException ex) {
String detailmessage = ex.getExplanation();
if (detailmessage.contains(" 32 ")) {
// User not Found
throw new BusinessException("error_invalidUser");
} else if (detailmessage.contains(" 49 ")) {
if (detailmessage.contains(" 775 ") || detailmessage.contains(" 701 ") || detailmessage.contains(" 533 ")) {
//Invalid Account
throw new BusinessException("error_invalidAccount");
} else {
//Invalid Username or password
throw new BusinessException("error_invalidUsernamePassword");
}
} else {
LOGGER.error("error_general", ex);
throw new BusinessException("error_general");
}
}
return json;
}
}
I don't see a problem with your setup. If you really have some class annotated with #Singleton or #Stateless inside this project, this should work.
But one important point is that if you have any dependencies which are not available in the libs of Glassfish, you have to package them with your application which is not possible with EJB/JAR packaging. You have to package it as a WAR or EAR file.
For a quick start, try the following:
Change
<packaging>ejb</packaging>
to
<packaging>war</packaging>
and change
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-ejb-plugin</artifactId>
<version>2.3</version>
<configuration>
<ejbVersion>3.1</ejbVersion>
</configuration>
</plugin>
to
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
If you want to package it as an EAR, you can use the maven-ear-plugin.
See also:
Packaging EJB in JavaEE 6 WAR vs EAR
Maven 2 & Packaging ejb vs jar
Maven EJB packaging with dependent libraries
Adam Bien - Is Java EE 6 War The New EAR?