Exceptions with EJB3 - java

I am Using a method in a session bean that is surrounded by a try and catch bloc with an IOException and it looks like it is making a problem as when i try to call a method from a java project client so here is my bean code
package com.et;
import com.gestionfichier.gestion.*;
import java.io.IOException;
import javax.ejb.ApplicationException;
import javax.ejb.Stateless;
#Stateless
public class PremierEJB3Bean implements PremierEJB3 {
public String envoicode(String Code) {
String s = null;
try {
s = GestionFichier.CopierCode(Code);
} catch (IOException e) {
e.printStackTrace();
}
CompilerFichierC.CompilerFichier(s,s);
return "Compilation réussie !";
}
}
and here is my client bean code:
package com.et;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class PremierEJB3Client {
public static void main(String[] args) {
try {
Context context = new InitialContext();
PremierEJB3 beanRemote = (PremierEJB3)
context.lookup("PremierEJB3Bean/remote");
System.out.println(beanRemote.envoicode("somthing"));
} catch (NamingException e) {
e.printStackTrace();
}
}
}
and here is what i get in the console
Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
at $Proxy0.envoicode(Unknown Source)
at com.et.PremierEJB3Client.main(PremierEJB3Client.java:15)
Caused by: java.lang.ClassNotFoundException: [Ljava.lang.StackTraceElement;
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
And more....
so i am quiet sure that exceptions in my bean are causing me this problem but i have no idea how to fix that

In order to do JNDI lookup for the EJB from a standalone client, context properties needs to be added.
Something similar to below.
Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
Context ct=new InitialContext(ht);

This doesn't necessarily indicate that the EJB bean is not found - a possible case would be that the bean is found, and its initializer is called in the EJB container, and an exception is caused there.
Thus you might see ClassNotFound - java.lang.StackTraceElement because somehow a serialized StackTraceElement is returned back to the client which cannot be de-serialized (e.g. because of an incompatibility between the Java version used to compile the code in the server and the code in the client?)
This was happening in my own scenario, where the EJB was found, but later when I called some method on it, a similar stack trace was appearing - because of an exception happening on the EJB container/server side. I fixed the error in the EJB and stopped looking for the reason its stack trace cannot be passed safely to the client.

Related

Problems with LDAP authentication: java.lang.IncompatibleClassChangeError

I've got a class that allows me to authenticate with LDAP. When i run this code in a project with just one class (for testing reasons) i don't have problems and it returns a boolean value, as is expected, but when i run it in the project i'm working in, i got the following error:
java.lang.IncompatibleClassChangeError: Class org.apache.mina.filter.codec.ProtocolCodecFilter does not implement the requested interface org.apache.mina.core.filterchain.IoFilter
This is the method the allows me to authenticate:
public static void autenticarUsuario(String usuar, String password) throws LdapException, CursorException{
Dn user = Dn.EMPTY_DN;
try{
BasicConfigurator.configure();
LdapConnectionConfig config = new LdapConnectionConfig();
config.setLdapHost(SERVER_IP);
config.setLdapPort(PORT);
config.setName("uid=ldapsearch,ou=System,ou=Users,dc=fiec,dc=espol,dc=edu,dc=ec");
config.setCredentials(CREDENTIALS);
conn = new LdapNetworkConnection(config);
}catch(Exception e){
}
String s1 = usuar;
String s2 = password;
//System.out.println("Nombre: "+s1+" Contra: "+s2);
try {
conn.bind();
System.out.println(conn.isAuthenticated());
// Create the SearchRequest object
SearchRequest req = new SearchRequestImpl();
req.setScope( SearchScope.SUBTREE );
req.addAttributes( "*" );
req.setTimeLimit( 0 );
req.setBase( new Dn( "ou=Users,dc=fiec,dc=espol,dc=edu,dc=ec" ) );
req.setFilter( "(uid="+ s1 +")" );
// Process the request
SearchCursor searchCursor = conn.search( req );
while ( searchCursor.next() )
{
Response r = searchCursor.get();
if(r instanceof SearchResultEntry){
Entry re = ((SearchResultEntry) r).getEntry();
user = re.getDn();
}
}
conn.bind(user, s2);
//return(conn.isAuthenticated());
inLDAP = conn.isAuthenticated();
} catch (InvalidConnectionException ex) {
//System.out.println(ex);
}
catch (LdapException e) {
e.printStackTrace();
} catch (CursorException e) {
e.printStackTrace();
}
inLDAP = false;
}
The project i'm working in is a JAVAFX application, but this method is called in a class that doesn't extend from application (just java code to verify user credentials).
This is the stacktrace:
Exception in thread "pool-1-thread-1" java.lang.IncompatibleClassChangeError: Class org.apache.mina.filter.codec.ProtocolCodecFilter does not implement the requested interface org.apache.mina.core.filterchain.IoFilter
at org.apache.mina.core.filterchain.DefaultIoFilterChain.register(DefaultIoFilterChain.java:267)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.addLast(DefaultIoFilterChain.java:174)
at org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder.buildFilterChain(DefaultIoFilterChainBuilder.java:436)
at org.apache.mina.core.polling.AbstractPollingIoProcessor.addNow(AbstractPollingIoProcessor.java:528)
at org.apache.mina.core.polling.AbstractPollingIoProcessor.handleNewSessions(AbstractPollingIoProcessor.java:501)
at org.apache.mina.core.polling.AbstractPollingIoProcessor.access$400(AbstractPollingIoProcessor.java:67)
at org.apache.mina.core.polling.AbstractPollingIoProcessor$Processor.run(AbstractPollingIoProcessor.java:1116)
at org.apache.mina.util.NamePreservingRunnable.run(NamePreservingRunnable.java:51)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
These are the libraries i'm working:
import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.cursor.SearchCursor;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.message.Response;
import org.apache.directory.api.ldap.model.message.SearchRequest;
import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
import org.apache.directory.api.ldap.model.message.SearchResultEntry;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
import org.apache.mina.*;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.apache.directory.ldap.client.api.exception.InvalidConnectionException;
import org.apache.log4j.BasicConfigurator;
I don't know why this is happening, i'll appreciate any help in advance
It is a version problem. Between Mina 1.0 and Mina 2.0, they moved the IoFilter interface (among other things) from org.apache.mina.filterchain to org.apache.mina.core.filterchain. I think you are trying to use code compiled for Mina 2.0 with the Mina 1.0 implementation.
Solution: examine your build and runtime classpaths and dependencies to figure out how this happened ... and fix the inconsistency.

Use Solr to index my database

I don't know why my code java is not compiled.
I need to index my database with solr.
I launch my server with line commande .
>cd C:\Solr\solr-4.10.0\solr-4.10.0\example\solr
>java -jar start.jar
After that i create a new project that contain my class to index database with solr.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
//import org.apache.lucene.index.IndexWriter;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;// CommonsHttpSolrServer;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest.ACTION;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
public class IndexFiles {
public static void main(String[] args) {
HttpSolrServer server = new HttpSolrServer("http://localhost:8983/solr/");
// i use SolrServer but it generate same error like this from httpSolrServer
//SolrServer solr = new HttpSolrServer("http://localhost:8983/solr");
/*
// TODO Auto-generated method stub
String urlString = "http://localhost:8989/solr";
if (args != null & args.length > 1) {
urlString = args[1];
}
SolrServer solr = new HttpSolrServer("http://localhost:8983/solr"); //CommonsHttpSolrServer(urlString);
try {
indexDocs(solr, new File(args[0]));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
}
}
I get this error :
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/NoHttpResponseException
at IndexFiles.main(IndexFiles.java:23)
Caused by: java.lang.ClassNotFoundException: org.apache.http.NoHttpResponseException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
How to resolve this problem?
Sounds like you haven't added the httpclient jar (from dist/solrj-lib) to your classpath.
See the Solrj wiki page topic about: Setting the Classpath

Unable to create JAXBContext java Web service

I am beginning to learn Web Services and I wanted to create a Simple custom one that connects to the database:
import java.sql.*;
import javax.jws.WebMethod;
import javax.jws.WebService;
#WebService
public class DatabaseService{
Connection conn;
#WebMethod
public Connection getDBConnection(){
try{
Class.forName("oracle.jdbc.driver.Oracledriver");
String url = "jdbc:oracle:thin:#localhost:1521:mysid";
conn = driverManager.getConnection(url, "myusername", "mypassword");
}catch(Exception asd){
System.out.println(asd.getMessage());
}
return conn;
}
}
I have a main Method to Call this:
import javax.xml.ws.Endpoint;
public class CallService{
public static void main(String[] args){
Endpoint.publish("http://localhost:8080/kollega_services", new DatabaseService());
System.out.println("service Started");
}
}
When I execute I get this Error:
Exception in thread "main" javax.xml.ws.WebServiceException: Unable to create JAXBContext
at com.sun.xml.internal.ws.model.AbstractSEIModelImpl.createJAXBContext(AbstractSEIModelImpl.java:153)
at com.sun.xml.internal.ws.model.AbstractSEIModelImpl.postProcess(AbstractSEIModelImpl.java:83)
at com.sun.xml.internal.ws.model.RuntimeModeler.buildRuntimeModel(RuntimeModeler.java:244)
at com.sun.tools.internal.ws.wscompile.WsgenTool.buildModel(WsgenTool.java:229)
at com.sun.tools.internal.ws.wscompile.WsgenTool.run(WsgenTool.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.tools.internal.ws.Invoker.invoke(Invoker.java:105)
at com.sun.tools.internal.ws.WsGen.main(WsGen.java:41)
Caused by: java.security.PrivilegedActionException: com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
java.lang.StackTraceElement does not have a no-arg default constructor.
this problem is related to the following location:
at java.sql.Connection
at public java.sql.Connection.webservice.jaxws.GetDBConnectionResponse._return
at webservice.jaxws.GetDBConnectionResponse
at com.sun.xml.internal.ws.model.AbstractSEIModelImpl.createJAXBContext(AbstractSEIModelImpl.java:140)
... 10 more
Caused by: com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
java.lang.StackTraceElement does not have a no-arg default constructor.
this problem is related to the following location:
at java.sql.Connection
at public java.sql.Connection.webservice.jaxws.GetDBConnectionResponse._return
at webservice.jaxws.GetDBConnectionResponse
at com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:91)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:436)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.(JAXBContextImpl.java:277)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1100)
at com.sun.xml.internal.bind.v2.ContextFactory.createContext(ContextFactory.java:143)
at com.sun.xml.internal.bind.api.JAXBRIContext.newInstance(JAXBRIContext.java:95)
at com.sun.xml.internal.ws.developer.JAXBContextFactory$1.createJAXBContext(JAXBContextFactory.java:97)
at com.sun.xml.internal.ws.model.AbstractSEIModelImpl$1.run(AbstractSEIModelImpl.java:148)
at com.sun.xml.internal.ws.model.AbstractSEIModelImpl$1.run(AbstractSEIModelImpl.java:140)
... 12 more
What else do I need to add to Make this work?

why does the javax.naming.NamingException occur here?

when i run the following :
package NonServletFiles;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.sql.DataSource;
import javax.naming.*;
public class GetTagsFromDatabase {
public GetTagsFromDatabase() {
}
public String[] getTags() {
String tags[] = null;
try {
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/photog"); // <<----- line 23
Connection connection = ds.getConnection();
String sqlQuery = "select NAMEOFTHETAG from tagcollection";
PreparedStatement statement = connection.prepareStatement(sqlQuery);
ResultSet set = statement.executeQuery();
int i = 0;
while(set.next()) {
tags[i] = set.getString("NameOfTheTag");
System.out.println(tags[i]);
i++;
}
}catch(Exception exc) {
exc.printStackTrace();
}
return tags;
}
public static void main(String args[]) {
new GetTagsFromDatabase().getTags(); // <<----- line 43
}
}
I get the following exceptions :
javax.naming.NamingException: Lookup failed for 'java:comp/env/jdbc/photog' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.url.pkgs=com.sun.enterprise.naming, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl} [Root exception is javax.naming.NamingException: Invocation exception: Got null ComponentInvocation ]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:518)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at NonServletFiles.GetTagsFromDatabase.getTags(GetTagsFromDatabase.java:23)
at NonServletFiles.GetTagsFromDatabase.main(GetTagsFromDatabase.java:43)
Caused by: javax.naming.NamingException: Invocation exception: Got null ComponentInvocation
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.getComponentId(GlassfishNamingManagerImpl.java:873)
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:742)
at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:172)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:498)
... 4 more
I don't know the reason for this exception,all other servlets that need to connect to the database with the url java:comp/env/jdbc/photog work fine.
The stacktrace hints that you're using Glassfish. Remove the java:comp/env/ part. It's the default JNDI context root already. Only in Tomcat you need to specify it explicitly. Also, you should be invoking this in webapp context, not as a plain Java Application with main().
Unrelated to the concrete problem, do you really need to get the DataSource everytime? I'd create a helper class which obtains it only once on webapp's startup or in a static initializer. It's application wide and threadsafe. Only the Connection indeed needs to be obtained (and closed! you're not closing it, so you're leaking DB resources) everytime you need to fire a SQL query.

Runtime Exception while executing Contacts Demo in Google Data API

I have downloaded the google data API plugin for eclipse. While dealing with the Contacts template (Demo.java)
/* INSTRUCTION: This is a command line application. So please execute this template with the following arguments:
arg[0] = username
arg[1] = password
*/
/**
* #author (Your Name Here)
*
*/
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
/**
* This is a test template
*/
public class Contacts {
public static void main(String[] args) {
try {
// Create a new Contacts service
ContactsService myService = new ContactsService("My Application");
myService.setUserCredentials(args[0],args[1]);
// Get a list of all entries
URL metafeedUrl = new URL("http://www.google.com/m8/feeds/contacts/"+args[0]+"#gmail.com/base");
System.out.println("Getting Contacts entries...\n");
ContactFeed resultFeed = myService.getFeed(metafeedUrl, ContactFeed.class);
List<ContactEntry> entries = resultFeed.getEntries();
for(int i=0; i<entries.size(); i++) {
ContactEntry entry = entries.get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
System.out.println("\nTotal Entries: "+entries.size());
}
catch(AuthenticationException e) {
e.printStackTrace();
}
catch(MalformedURLException e) {
e.printStackTrace();
}
catch(ServiceException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
it is getting compiled successfully, but throwing this runtime exception (i am providing correct required credentials as arguments).
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/collect/Maps
at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:118)
at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:100)
at com.google.gdata.client.Service.<clinit>(Service.java:532)
at Contacts.main(Contacts.java:36)
Caused by: java.lang.ClassNotFoundException: com.google.common.collect.Maps
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 4 more
I am sure, i am missing something, but enable to resolve it.
You seem to be missing a dependency. Download this google-collections and add the jar to your build-path.

Categories

Resources