Error during EJB3 call - java

I have written a simple Ejb program, by looking from
http://mrbool.com/how-to-use-enterprise-java-beans-3-x-based-application-with-websphere-8-5-application-server/28063
The files are
package ejb3.test;
import javax.ejb.Remote;
/**
* TODO: Document me!
*
* #author aprashanth
*
*/
#Remote
public interface ITestEJBRemoteInterface {
public boolean checkNames(String fsName);
}
Implementation Class:
package ejb3.test;
/**
* TODO: Document me!
*
* #author aprashanth
*
*/
import java.util.Arrays;
import java.util.List;
import javax.ejb.Stateless;
/** * Session Bean implementation class TestEJB */
#Stateless
public class TestEJB implements ITestEJBRemoteInterface {
List<String> moListOfNames = Arrays.asList("Kevin","Jiten","Martina","Brian");
/** * Default constructor. */
public TestEJB() { }
/** * Find if the passed name is present in the default list of names * *
*
* #return */
public boolean checkNames(String fsName) {
boolean lboolNamePresent = false;
if(fsName != null)
{
lboolNamePresent = moListOfNames.contains(fsName);
}
return lboolNamePresent;
}
}
Ejb-jar.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd" version="3.1">
<display-name>TestEJB3 </display-name>
<ejb-client-jar>TestEJB3Client.jar</ejb-client-jar>
</ejb-jar>
At the client side:
I have created the stub using createStub.bat of IBM.and that jar is imported at the client side.
package ejb31.test;
/**
* TODO: Document me!
*
* #author aprashanth
*
*/
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import ejb3.test.ITestEJBRemoteInterface;
public class TestEJBClient {
/** * #param args */
public static void main(String[] args) {
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.ibm.websphere.naming.WsnInitialContextFactory");
props.put(javax.naming.Context.PROVIDER_URL, "iiop://localhost:2809");
ITestEJBRemoteInterface loEJB =null;
Object lobj; try { InitialContext ctx = new InitialContext(props);
lobj = ctx.lookup("checkName");
if (lobj instanceof ITestEJBRemoteInterface) {
loEJB = (ITestEJBRemoteInterface) lobj;
}
String lsName = "Imran";
System.out.println("Is "+ lsName + " present in the list:: "+loEJB.checkNames(lsName));
System.out.println("EJB run successful");
} catch (NamingException e) {
e.printStackTrace();
}
}
}
My project structure and the imported libraries as in the below figure:
At the WAS side, setup steps are as below:
Port
Installation Steps
Lastly JndI Configuration.
When I run the client code, I get the following error.
JSAS1480I: Security is not enabled because the ConfigURL property file is not set.
javax.naming.NamingException: Error getting WsnNameService properties [Root exception is org.omg.CORBA.TRANSIENT: initial and forwarded IOR inaccessible vmcid: 0x4942f000 minor code: 3591 completed: No]
at com.ibm.ws.naming.util.WsnInitCtxFactory.mergeWsnNSProperties(WsnInitCtxFactory.java:1552)
at com.ibm.ws.naming.util.WsnInitCtxFactory.getRootContextFromServer(WsnInitCtxFactory.java:1042)
at com.ibm.ws.naming.util.WsnInitCtxFactory.getRootJndiContext(WsnInitCtxFactory.java:962)
at com.ibm.ws.naming.util.WsnInitCtxFactory.getInitialContextInternal(WsnInitCtxFactory.java:614)
at com.ibm.ws.naming.util.WsnInitCtx.getContext(WsnInitCtx.java:128)
at com.ibm.ws.naming.util.WsnInitCtx.getContextIfNull(WsnInitCtx.java:765)
at com.ibm.ws.naming.util.WsnInitCtx.lookup(WsnInitCtx.java:164)
at com.ibm.ws.naming.util.WsnInitCtx.lookup(WsnInitCtx.java:179)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at ejb31.test.TestEJBClient.main(TestEJBClient.java:27)
Caused by: org.omg.CORBA.TRANSIENT: initial and forwarded IOR inaccessible vmcid: 0x4942f000 minor code: 3591 completed: No
at com.ibm.rmi.corba.ClientDelegate.createRequest(ClientDelegate.java:1276)
at com.ibm.CORBA.iiop.ClientDelegate.createRequest(ClientDelegate.java:1457)
at com.ibm.rmi.corba.ClientDelegate.createRequest(ClientDelegate.java:1164)
at com.ibm.CORBA.iiop.ClientDelegate.createRequest(ClientDelegate.java:1423)
at com.ibm.rmi.corba.ClientDelegate.request(ClientDelegate.java:1886)
at com.ibm.CORBA.iiop.ClientDelegate.request(ClientDelegate.java:1379)
at org.omg.CORBA.portable.ObjectImpl._request(ObjectImpl.java:449)
at com.ibm.WsnBootstrap._WsnNameServiceStub.getProperties(_WsnNameServiceStub.java:38)
at com.ibm.ws.naming.util.WsnInitCtxFactory.mergeWsnNSProperties(WsnInitCtxFactory.java:1549)
... 9 more
Caused by: java.net.ConnectException: connect: Address is invalid on local machine, or port is not valid on remote machine
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:83)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at com.ibm.ws.orbimpl.transport.WSTCPTransportConnection.createSocket(WSTCPTransportConnection.java:313)
at com.ibm.CORBA.transport.TransportConnectionBase.connect(TransportConnectionBase.java:357)
at com.ibm.ws.orbimpl.transport.WSTransport.getConnection(WSTransport.java:437)
at com.ibm.CORBA.transport.TransportBase.getConnection(TransportBase.java:187)
at com.ibm.rmi.iiop.TransportManager.get(TransportManager.java:97)
at com.ibm.rmi.iiop.GIOPImpl.getConnection(GIOPImpl.java:130)
at com.ibm.rmi.iiop.GIOPImpl.locate(GIOPImpl.java:219)
at com.ibm.rmi.corba.ClientDelegate.locate(ClientDelegate.java:1983)
at com.ibm.rmi.corba.ClientDelegate._createRequest(ClientDelegate.java:2008)
at com.ibm.rmi.corba.ClientDelegate.createRequest(ClientDelegate.java:1186)
at com.ibm.rmi.corba.ClientDelegate.createRequest(ClientDelegate.java:1272)
... 17 more
Note: Port and address is correct:
Screen Shot of Security
New error on changing the inbound Configuration
JSAS1480I: Security is not enabled because the ConfigURL property file is not set.
Exception in thread "P=818203:O=0:CT" java.lang.NullPointerException
at ejb31.test.TestEJBClient.main(TestEJBClient.java:32)
The war file which is deployed.
inside Client
Inside server.jar inside war file

Hmm, you have to look better on your screenshot, as it is clearly visible that Enable Administrative Security is CHECKED.
So you either have to disable SSL in the RMI/IIOP inbound transport configuration, or properly configure your client to use SSL.
Something like this:
<java_install_root>/bin/java
-classpath com.ibm.ws.ejb.thinclient_8.5.0.jar:<list_of_your_application_jars_and_classes>
-Djava.naming.provider.url=iiop://<your_application_server_machine_name>
-Dcom.ibm.SSL.ConfigURL=file:///home/user1/ssl.client.props
-Dcom.ibm.CORBA.ConfigURL=file:///home/user1/sas.client.props
<fully_qualified_class_name_to_run>
For details check the following page - Running the IBM Thin Client for Enterprise JavaBeans (EJB)
UPDATE
Now you have issue in the code. You have to use PortableRemoteObject.narrow for unmanaged clients.
Instead of:
Object lobj; try { InitialContext ctx = new InitialContext(props);
lobj = ctx.lookup("checkName");
if (lobj instanceof ITestEJBRemoteInterface) { // <##### this is the problem
loEJB = (ITestEJBRemoteInterface) lobj;
}
use:
lobj = initCtx.lookup(ejbJNDIName);
loEJB = (ITestEJBRemoteInterface) javax.rmi.PortableRemoteObject.narrow(lobj , ITestEJBRemoteInterface.class);
For details see How to lookup the Remote Interface of an EJB 3 without using Dependency Injection

Related

Connect Java to Access DB on network drive

I'm creating a desktop Java application that will connect to an access database, using ucanaccess as a driver.
The entire thing will be located on a shared network drive.
I use an absolute file path to connect to my database. I expect this database to outlast my tenure at the office. What happens when another user moves the database, or changes the name of the folder etc... I'm the only Java geek in the office, so this needs to be somewhat automated or easily doable for someone who is... well let's just say not computer literate.
I'm looking for ideas on how to get around this. I thought of opening a file dialog and having the user select the location of the file, but this seems like too much work for the kind of people I work with. It should just open...
Any help is much appreciated. Code sample below.
package databaseTest;
import java.sql.Connection;
import java.sql.DriverManager;
public class test {
public test() {
try {
String driver = "net.ucanaccess.jdbc.UcanaccessDriver";
Class.forName(driver);
Connection cnct = DriverManager.getConnection("jdbc:ucanaccess://c:\\users\\Christopher\\Desktop\\JavaProject\\Database11.accdb", "", "");
System.out.println("Connected");
} catch(Exception ex) {System.out.println(ex.getMessage());}
}
public static void main(String[] args) {
System.out.println("connecting...");
new test();
}
}
Suggestion:
I would suggest you to store the database related parameters/configurations
Path to database
Name of network shared directory
Database Name
etc. in a properties file. You can then load the properties file using getResourceAsStream. You only need to ensure two things —
The properties file is in a directory which is in the project build path.
If any of the parameter(s) are changed(files moved/renamed), the corresponding value(s) in the properties file are changed also.
Here's one concrete example(tested on Ubuntu Linux).
Let's say we have a:
MS Access database named Foo.mdb stored under a shared directory /path/to/sharedDirectory
Shared directory named shared_dir
MyDatabaseProperties.properties:
pathToDB = /path/to/sharedDirectory
sharedFolderName = shared_dir
databaseName = Foo.mdb
Table Definition:
Example:
package com.stackoverflow.questions.Q32641670;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
/**
* Initializes a connection to an MS-Access DB using JDBC/UCanAccess API, inserts a record and closes the connection.
* <p>
* ADDITIONAL JARS REQUIRED:
* ------------------------
* commons-lang-2.6.jar
* commons-logging-1.1.1.jar
* hsqldb.jar
* jackcess-2.1.0.jar
* ucanaccess-2.0.9.5.jar
*
* #see #link {https://stackoverflow.com/questions/32641670/connect-java-to-access-db-on-network-drive}
* #since 18/9/15.
*/
/**
* #author Sandeep Chatterjee
* #version 1.0
*/
public class ConnectRemoteDB {
/**
* #param args The command line arguments
*/
public static void main(String[] args) throws IOException {
initializeConnection();
}
/**
* Initializes remote database connection and inserts a record and closes the connection.
*/
private static void initializeConnection() throws IOException {
System.out.println("Attempting Database Connection...");
Connection connection = null;
PreparedStatement preparedStatement;
try {
final Properties PROPERTIES = new Properties();
InputStream inputStream = ConnectRemoteDB.class.getResourceAsStream("/MyDatabaseProperties.properties");
PROPERTIES.load(inputStream);
String pathToDB = PROPERTIES.getProperty("pathToDB");
String sharedFolderName = PROPERTIES.getProperty("sharedFolderName");
String databaseName = PROPERTIES.getProperty("databaseName");
String connectionString = "jdbc:ucanaccess:///" + pathToDB + "/" + sharedFolderName + "/" + databaseName;
connection = DriverManager.getConnection(connectionString, PROPERTIES);
System.out.println("CONNECTION ESTABLISHED....");
String insertTableSQL = "INSERT INTO Table1" + "(Name) VALUES"
+ "(?)";
preparedStatement = connection.prepareStatement(insertTableSQL);
preparedStatement.setString(1, "A");
preparedStatement.executeUpdate();
System.out.println("RECORD INSERTED...");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connection.close();
System.out.println("CONNECTION CLOSED...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Again:
If you move the database to a different shared directory, set the value of pathToDB accordingly.
If you rename the shared directory, set the value of sharedFolderName accordingly.
If you rename the database, set the value of databaseName accordingly.
The simplest solution is to put the accdb file in a location relative to the java class and not use an absolute path.
For example if the java class (or jar you have packaged your program into as it may be) resides at c:\share\foo.class (or c:\share\foo.jar) then put the acdb file in the same directory structure e.g. c:\share\database\Database11.accdb.
You can then use a relative path in the connection string:
Connection cnct = DriverManager.getConnection("jdbc:ucanaccess:database/Database11.accdb", "", "")

Java, Websockets, tyrus server: handshake error [duplicate]

I have written a client program that connects to my websocket on the server. I set up tomcat8 with the examples working and hit the EchoAnnotation endpoint with my client program.
I wrote this endpoint program as follows:
#ServerEndpoint(value = "/websocket")
public class PortServer implements AirMessageListener {
public PortServer() { }
#OnOpen
public void start(Session session) {
//do stuff
}
#OnClose
public void end() {
//do stuff
}
}
#OnMessage
public void incoming(String message) {
//do stuff
}
#OnError
public void onError(Throwable tw) throws Throwable {
//do stuff
}
I compile this and create a war file called portserver and drop it into my tomcat webapps directory. I then switched my client program from connecting to: ws://localhost:8080/examples/websocket/echoAnnotation to ws://localhost:8080/portserver/websocket and run it. I get:
Connecting to:ws://localhost:8080/portserver/websocket
Exception in thread "main" com.corrisoft.air.exception.AirException: Error connecting to server
at com.corrisoft.air.socket.AirSocketClient.<init>(AirSocketClient.java:60)
at test.corrisoft.air.portserver.SocketConversation.<init>(SocketConversation.java:46)
at test.corrisoft.air.portserver.RunPortServerTester.initConfigProperties(RunPortServerTester.java:76)
at test.corrisoft.air.portserver.RunPortServerTester.<init>(RunPortServerTester.java:34)
at test.corrisoft.air.portserver.RunPortServerTester.main(RunPortServerTester.java:109)
Caused by: javax.websocket.DeploymentException: Handshake error.
at org.glassfish.tyrus.client.ClientManager$1$1.run(ClientManager.java:466)
at org.glassfish.tyrus.client.ClientManager$1.run(ClientManager.java:502)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.glassfish.tyrus.client.ClientManager$SameThreadExecutorService.execute(ClientManager.java:654)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
at org.glassfish.tyrus.client.ClientManager.connectToServer(ClientManager.java:359)
at org.glassfish.tyrus.client.ClientManager.connectToServer(ClientManager.java:195)
at com.corrisoft.air.socket.AirSocketClient.<init>(AirSocketClient.java:58)
... 4 more
Caused by: org.glassfish.tyrus.core.HandshakeException: Response code was not 101: 404.
at org.glassfish.tyrus.core.Handshake.validateServerResponse(Handshake.java:279)
at org.glassfish.tyrus.client.TyrusClientEngine.processResponse(TyrusClientEngine.java:138)
at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientFilter.handleHandshake(GrizzlyClientFilter.java:318)
at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientFilter.handleRead(GrizzlyClientFilter.java:288)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:291)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:209)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:137)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:115)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:550)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:744)
I placed an index.html inside my portserver app and can hit: http://localhost:8080/portserver just fine, which means the directories are OK. I then verified that my class was in my WEB-INF/classes directory.
I looked at the examples and found the ExamplesConfig class that I thought might be a "magic" class that enables the endpoints, so I implemented my own and and stuck in the jar file.
/**
*
*/
package com.corrisoft.air.portserver;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.Endpoint;
import javax.websocket.server.ServerApplicationConfig;
import javax.websocket.server.ServerEndpointConfig;
/**
* #author Corrisoft Android Development
*/
public class WebSocketConfig implements ServerApplicationConfig {
/* (non-Javadoc)
* #see javax.websocket.server.ServerApplicationConfig#getAnnotatedEndpointClasses(java.util.Set)
*/
#Override
public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) {
// Deploy all WebSocket endpoints defined by annotations in the
// web application. Filter out all others to avoid issues when running
// tests on Gump
Set<Class<?>> results = new HashSet<>();
for (Class<?> clazz : scanned) {
if (clazz.getPackage().getName().startsWith("com.corrisoft.air")) {
System.out.println("Adding endpoint for:" + clazz.getName());
results.add(clazz);
}
}
return results;
}
/* (non-Javadoc)
* #see javax.websocket.server.ServerApplicationConfig#getEndpointConfigs(java.util.Set)
*/
#Override
public Set<ServerEndpointConfig> getEndpointConfigs( Set<Class<? extends Endpoint>> scanned) {
return null;
}
}
It does not seem to be running this class.
Is there some configuration I missed?
Turns out that the problem was that one of my dependent classes was missing from the classpath. Tomcat 8, under these circumstances, doesn't add the endpoint and doesn't throw an exception into the log.
I deployed the same war file to tomcat 7 and got an exception. Worked the classpath until it was good and then deployed back to tomcat 8 where it is now working.
I created defect 56442 here: https://issues.apache.org/bugzilla/show_bug.cgi?id=56442 for tomcat eating the exception instead of displaying in the log.
For anyone else plagued by this; take a CLOSE look at your URI. I was piecing my url together, based on a configuration file. I missed a single "/" character when constructing the URL, and was convinced that it was correct! If you do stuff like the following, I suggest, printing out the "constructed URL" and studying that closely before chasing your tail:
public static final String WEBSOCKETHOST = "localhost"; // TODO: Get from configuration
public static final int WEBSOCKETPORT = 10080; // TODO: Get from configuration
public static final String WEBSOCKETSERVERROOT = "/sceagents"; // TODO: Get from configuration
public static final String WEBSOCKETSERVERENDPOINT = "neo"; // TODO: Get from configuration
public static final String WEBSOCKETPROTOCOL = "ws"; // TODO: Get from configuration
String uri = WEBSOCKETPROTOCOL + "://" + WEBSOCKETHOST + ":" + Integer.toString(WEBSOCKETPORT) + WEBSOCKETSERVERROOT + "/" + WEBSOCKETSERVERENDPOINT;

Error when trying to do LDAP lookup in active directory

I'm trying to lookup a user on a local active-directory using java.
When I try to execute the code, I get the following error:
Error:
Lookup failed: javax.naming.NamingException: [LDAP: error code 1 -
000004DC: Lda pErr: DSID-0C0906DC, comment: In order to perform this
operation a successful bi nd must be completed on the connection.,
data 0, v1db1 ]; remaining name: 'CN= John Doe, OU=Accounts'
Could anyone tell me what I'm doing wrong?
My code:
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.ldap.LdapContext;
/**
* Demonstrates how to look up an object.
*
* usage: java Lookup
*/
class Lookup {
public static void main(String[] args) {
// Set up the environment for creating the initial context
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL,
"ldap://localhost:389/DC=PORTAL-UAT,DC=COMPANY,DC=COM");
try {
// Create the initial context
Context ctx = new InitialContext(env);
// Perform lookup and cast to target type
LdapContext b = (LdapContext) ctx
.lookup("CN=John Doe,OU=Accounts");
System.out.println(b);
// Close the context
ctx.close();
} catch (NamingException e) {
System.out.println("Lookup failed: " + e);
}
}
}
As the error message states you have to perform bind operation, i.e. login into the AD. Here is the LDAP Authentication tutorial from Oracle.
The coder should use the ldapsearch command line utility to verify that the connection can be
established that the credentials for the bind DN are correct. This low-level approach will
ensure that a connection can be made from the client system to the target directory server. This
is a basic troubleshooting technique.
For more information, see LDAP: Programming Practices

Using Dropbox Java API for uploading files to dropbox

I want to upload files using the java API for DropBox. The following code gets me the oauth_token and oauth_secret. but when ever I try to upload a file I get a exception.
Java Class
package com.dropbox.client;
import com.dropbox.client.DropboxAPI.Config;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
*
* #author Charan
*/
public class DBmain {
public DBmain() {
System.setProperty("java.net.useSystemProxies", "true");
Map configuration= new HashMap();
configuration.put("consumer_key", "XXXXXXXXXXXXXXXX");
configuration.put("consumer_secret", "XXXXXXXXXXXXXXXX");
configuration.put("request_token_url", "http://api.dropbox.com/0/oauth/request_token");
configuration.put("access_token_url", "http://api.dropbox.com/0/oauth/access_token");
configuration.put("authorization_url", "http://api.dropbox.com/0/oauth/authorize");
configuration.put("port",80);
//configuration.put("trusted_access_token_url","http://api.getdropbox.com/0/token");
configuration.put("server","api.getdropbox.com");
configuration.put("content_server","api-content.dropbox.com");
String username="myMailAddress#domain.com";
String password="myPassword";
try {
Authenticator auth = new Authenticator(configuration);
String url = auth.retrieveRequestToken("");
String access_key = auth.getTokenKey();
String access_secret = auth.getTokenSecret();
System.out.println(access_key);
System.out.println(access_secret);
DropboxAPI api = new DropboxAPI();
DropboxAPI.Config conf = api.new Config(configuration);
api.authenticateToken("XXXXXXXXXXXX", "XXXXXXXXXXX", conf);
System.out.println(api.isAuthenticated());
URL resource = this.getClass().getResource("/config/testing.json");
File f= new File(resource.toURI());
api.putFile("dropbox", "/Project", f);
//api.accountInfo(); //even this method gives me a exception
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new DBmain();
}
}
Exception
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.http.protocol.BasicHttpContext: method <init>()V not found
at org.apache.http.impl.client.DefaultHttpClient.createHttpContext(DefaultHttpClient.java:205)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:532)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.dropbox.client.DropboxClient.putFile(DropboxClient.java:299)
at com.dropbox.client.DropboxAPI.putFile(DropboxAPI.java:463)
at com.dropbox.client.DBmain.<init>(DBmain.java:58)
at com.dropbox.client.DBmain.main(DBmain.java:70)
Java Result: 1
Some extra info
Edit Date:18-6-2011
I changed the httpclient-4.0-beta1.jar and httpcore-4.0-alpha6.jar to httpclient-4.0.jar and httpcore-4.0.1.jar respectively and I no longer get the above exception [ java.lang.NoSuchMethodError ]
This stackoverflow question helped me in solving this : java.lang.NoSuchMethodError: org.apache.http.protocol.BasicHttpContext: method <init>()V not found
But Now I get UnknownhostException on execution of any methods of the API
com.dropbox.client.DropboxException: java.net.UnknownHostException: api.getdropbox.com:80
at com.dropbox.client.RESTUtility.request(RESTUtility.java:250)
at dump.DropboxClient.accountInfo(DropboxClient.java:121)
at com.charan.client.DBmain.<init>(DBmain.java:57)
at com.charan.client.DBmain.main(DBmain.java:65)
Caused by: java.net.UnknownHostException: api.getdropbox.com:80
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
at java.net.Socket.connect(Socket.java:525)
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:123)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:123)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:147)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:101)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:381)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
at com.dropbox.client.RESTUtility.executeRequest(RESTUtility.java:172)
at com.dropbox.client.RESTUtility.request(RESTUtility.java:248)
... 3 more
You should use http-client 4.0.3 jar
Your class should NOT be in package com.dropbox.client. Try moving it to a different (i.e. com.yourname.client). It looks like you might be creating a name clash and inadvertently overriding something in the Dropbox client API.
You have specified api.getdropbox.com:80 as the host name. Try using api.getdropbox.com instead.

Easy way to start a standalone JNDI server (and register some resources)

For testing purposes, I'm looking for a simple way to start a standalone JNDI server, and bind my javax.sql.DataSource to "java:/comp/env/jdbc/mydatasource" programmatically.
The server should bind itself to some URL, for example: "java.naming.provider.url=jnp://localhost:1099" (doesn't have to be JNP), so that I can look up my datasource from another process. I don't care about which JNDI server implementation I'll have to use (but I don't want to start a full-blown JavaEE server).
This should be so easy, but to my surprise, I couldn't find any (working) tutorial.
The JDK contains a JNDI provider for the RMI registry. That means you can use the RMI registry as a JNDI server. So, just start rmiregistry, set java.naming.factory.initial to com.sun.jndi.rmi.registry.RegistryContextFactory, and you're away.
The RMI registry has a flat namespace, so you won't be able to bind to java:/comp/env/jdbc/mydatasource, but you will be able to bind to something so it will accept java:/comp/env/jdbc/mydatasource, but will treat it as a single-component name (thanks, #EJP).
I've written a small application to demonstrate how to do this: https://bitbucket.org/twic/jndiserver/src
I still have no idea how the JNP server is supposed to work.
I worked on the John´s code and now is working good.
In this version I'm using libs of JBoss5.1.0.GA, see jar list below:
jboss-5.1.0.GA\client\jbossall-client.jar
jboss-5.1.0.GA\server\minimal\lib\jnpserver.jar
jboss-5.1.0.GA\server\minimal\lib\log4j.jar
jboss-remote-naming-1.0.1.Final.jar (downloaded from http://search.maven.com)
This is the new code:
import java.net.InetAddress;
import java.util.Hashtable;
import java.util.concurrent.Callable;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.jnp.server.Main;
import org.jnp.server.NamingBeanImpl;
public class StandaloneJNDIServer implements Callable<Object> {
public Object call() throws Exception {
setup();
return null;
}
#SuppressWarnings("unchecked")
private void setup() throws Exception {
//configure the initial factory
//**in John´s code we did not have this**
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
//start the naming info bean
final NamingBeanImpl _naming = new NamingBeanImpl();
_naming.start();
//start the jnp serve
final Main _server = new Main();
_server.setNamingInfo(_naming);
_server.setPort(5400);
_server.setBindAddress(InetAddress.getLocalHost().getHostName());
_server.start();
//configure the environment for initial context
final Hashtable _properties = new Hashtable();
_properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
_properties.put(Context.PROVIDER_URL, "jnp://10.10.10.200:5400");
//bind a name
final Context _context = new InitialContext(_properties);
_context.bind("jdbc", "myJDBC");
}
public static void main(String...args){
try{
new StandaloneJNDIServer().call();
}catch(Exception _e){
_e.printStackTrace();
}
}
}
To have good logging, use this log4j properties:
log4j.rootLogger=TRACE, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
To consume the Standalone JNDI server, use this client class:
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
/**
*
* #author fabiojm - Fábio José de Moraes
*
*/
public class Lookup {
public Lookup(){
}
#SuppressWarnings("unchecked")
public static void main(String[] args) {
final Hashtable _properties = new Hashtable();
_properties.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
_properties.put("java.naming.provider.url", "jnp://10.10.10.200:5400");
try{
final Context _context = new InitialContext(_properties);
System.out.println(_context);
System.out.println(_context.lookup("java:comp"));
System.out.println(_context.lookup("java:jdbc"));
}catch(Exception _e){
_e.printStackTrace();
}
}
}
Here's a code snippet adapted from JBoss remoting samples. The code that is
in the samples (version 2.5.4.SP2 ) no longer works. While the fix
is simple it took me more hours than I want to think about to figure it out.
Sigh. Anyway, maybe someone can benefit.
package org.jboss.remoting.samples.detection.jndi.custom;
import java.net.InetAddress;
import java.util.concurrent.Callable;
import org.jnp.server.Main;
import org.jnp.server.NamingBeanImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StandaloneJNDIServer implements Callable<Object> {
private static Logger logger = LoggerFactory.getLogger( StandaloneJNDIServer.class );
// Default locator values - command line args can override transport and port
private static String transport = "socket";
private static String host = "localhost";
private static int port = 5400;
private int detectorPort = 5400;
public StandaloneJNDIServer() {}
#Override
public Object call() throws Exception {
StandaloneJNDIServer.println("Starting JNDI server... to stop this server, kill it manually via Control-C");
//StandaloneJNDIServer server = new StandaloneJNDIServer();
try {
this.setupJNDIServer();
// wait forever, let the user kill us at any point (at which point, the client will detect we went down)
while(true) {
Thread.sleep(1000);
}
}
catch(Exception e) {
e.printStackTrace();
}
StandaloneJNDIServer.println("Stopping JBoss/Remoting server");
return null;
}
private void setupJNDIServer() throws Exception
{
// start JNDI server
String detectorHost = InetAddress.getLocalHost().getHostName();
Main JNDIServer = new Main();
// Next two lines add a naming implemention into
// the server object that handles requests. Without this you get a nice NPE.
NamingBeanImpl namingInfo = new NamingBeanImpl();
namingInfo.start();
JNDIServer.setNamingInfo( namingInfo );
JNDIServer.setPort( detectorPort );
JNDIServer.setBindAddress(detectorHost);
JNDIServer.start();
System.out.println("Started JNDI server on " + detectorHost + ":" + detectorPort );
}
/**
* Outputs a message to stdout.
*
* #param msg the message to output
*/
public static void println(String msg)
{
System.out.println(new java.util.Date() + ": [SERVER]: " + msg);
}
}
I know I'm late to the party, but I ended up hacking this together like so
InitialContext ctx = new InitialContext();
// check if we have a JNDI binding for "jdbc". If we do not, we are
// running locally (i.e. through JUnit, etc)
boolean isJndiBound = true;
try {
ctx.lookup("jdbc");
} catch(NameNotFoundException ex) {
isJndiBound = false;
}
if(!isJndiBound) {
// Create the "jdbc" sub-context (i.e. the directory)
ctx.createSubcontext("jdbc");
//parse the jetty-web.xml file
Map<String, DataSource> dataSourceProperties = JettyWebParser.parse();
//add the data sources to the sub-context
for(String key : dataSourceProperties.keySet()) {
DataSource ds = dataSourceProperties.get(key);
ctx.bind(key, ds);
}
}
Have you considered using Mocks? If I recall correctly you use Interfaces to interact with JNDI. I know I've mocked them out at least once before.
As a fallback, you could probably use Tomcat. It's not a full blown J2EE impl, it starts fast, and is fairly easy to configure JNDI resources for. DataSource setup is well documented. It's sub-optimal, but should work.
You imply you've found non-working tutorials; that may mean you've already seen these:
J2EE or J2SE? JNDI works with both
Standalone JNDI server using jnpserver.jar
I had a quick go, but couldn't get this working. A little more perseverance might do it, though.
For local, one process standalone jar purpouses I would use spring-test package:
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
SQLServerConnectionPoolDataSource myDS = new SQLServerConnectionPoolDataSource();
//setup...
builder.bind("java:comp/env/jdbc/myDS", myDS);
builder.activate();
startup log:
22:33:41.607 [main] INFO org.springframework.mock.jndi.SimpleNamingContextBuilder - Static JNDI binding: [java:comp/env/jdbc/myDS] = [SQLServerConnectionPoolDataSource:1]
22:33:41.615 [main] INFO org.springframework.mock.jndi.SimpleNamingContextBuilder - Activating simple JNDI environment
I have been looking for a similar simple starter solution recently. The "file system service provider from Sun Microsystems" has worked for me well. See https://docs.oracle.com/javase/jndi/tutorial/basics/prepare/initial.html.
The problem with the RMI registry is that you need a viewer - here you just need to look at file contents.
You may need fscontext-4.2.jar - I obtained it from http://www.java2s.com/Code/Jar/f/Downloadfscontext42jar.htm

Categories