I am trying to access LDAP Server through Java code as I have founded a free hosted server on the internet and want to test the reading mechanism via LDAP. But when I access it I get the captioned exception.
I have surfed on the internet and found that the LDAP URL Format shall be as per the correct practice and standard. I fixed that too, but nothing worked.
I dont know where I have done a mistake.
The complete stack trace is provided below:
Exception
Rdentry example failed.
javax.naming.CommunicationException: www.btechldap.com:1389 [Root exception is java.net.UnknownHostException: www.btechldap.com]
at com.sun.jndi.ldap.Connection.<init>(Unknown Source)
at com.sun.jndi.ldap.LdapClient.<init>(Unknown Source)
at com.sun.jndi.ldap.LdapClient.getInstance(Unknown Source)
at com.sun.jndi.ldap.LdapCtx.connect(Unknown Source)
at com.sun.jndi.ldap.LdapCtx.<init>(Unknown Source)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(Unknown Source)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(Unknown Source)
at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(Unknown Source)
at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(Unknown Source)
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.init(Unknown Source)
at javax.naming.InitialContext.<init>(Unknown Source)
at javax.naming.directory.InitialDirContext.<init>(Unknown Source)
at LDAPAccess.main(LDAPAccess.java:33)
Caused by: java.net.UnknownHostException: www.btechldap.com
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.sun.jndi.ldap.Connection.createSocket(Unknown Source)
... 15 more
CODE
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class LDAPAccess {
public static void main(String[] args) {
Hashtable env = new Hashtable(5, 0.75f);
/*
* Specify the initial context implementation to use.
* This could also be set by using the -D option to the java program.
* For example,
* java -Djava.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory \
* Rdentry
*/
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
/* Specify host and port to use for directory service */
env.put(Context.PROVIDER_URL, "ldap://www.btechldap.com:1389/dc=btechsample,dc=com");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_CREDENTIALS, "btechpass");
try {
/* get a handle to an Initial DirContext */
DirContext ctx = new InitialDirContext(env);
/* Read Babs' entry */
Attributes attrs = ctx.getAttributes("uid");
if (attrs == null) {
System.out.println("uid" + "has no attributes");
} else {
/* print each attribute */
for (NamingEnumeration ae = attrs.getAll();
ae.hasMoreElements();) {
Attribute attr = (Attribute)ae.next();
String attrId = attr.getID();
/* print each value */
for (NamingEnumeration vals = attr.getAll();
vals.hasMoreElements();
System.out.println(attrId + ": " + vals.nextElement()))
;
}
}
} catch (NamingException e) {
System.err.println("Rdentry example failed.");
e.printStackTrace();
}
}
}
I am new to LDAP, Please help!
The code is specifying the credentials (password) but missing the principal (i.e. the user to authenticate as).
Just add the following line:
env.put(Context.SECURITY_PRINCIPAL, "cn=readonlybind,ou=admins,dc=btechsample,dc=com");
Related
I am trying to make a simple RMI execution engine to run on my local machine so that other java programs can easily run code on a second processor. (In the future this will be expanded to allow more processors).
The server starts up just fine, and the client appears to locate the registry ok, but when it tries to call the execution engine (and passes it a parameter) it causes a ClassNotFoundException.
I recognize that this is similar to many other questions on stack overflow, but as far as I can tell, all the other ones have to do with the client not being able to download the server's classes rather than the server not being able to download the client's classes.
Here is my code (copied almost exactly from this sample code):
RMIServer eclipse project
ComputeEngine Interface:
package interfaces;
import java.io.Serializable;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface ComputeEngine_IF extends Remote {
/**
* #param task The task object specifying the computation to be performed
* #return
* #throws RemoteException
*/
<T extends Serializable> T compute(TaskWithoutInput<T> task) throws RemoteException;
}
TaskWithoutInput interface:
package interfaces;
import java.io.Serializable;
public interface TaskWithoutInput<T> extends Serializable {
public T compute();
}
ComputeEngine Class:
package server;
import interfaces.ComputeEngine_IF;
import interfaces.TaskWithoutInput;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class ComputeEngine implements ComputeEngine_IF{
public ComputeEngine() {
super();
}
#Override
public <T extends Serializable> T compute(TaskWithoutInput<T> task) throws RemoteException {
return task.compute();
}
public static void main(String[] args) {
if(System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
String name = "Compute";
ComputeEngine_IF engine = new ComputeEngine();
ComputeEngine_IF stub = (ComputeEngine_IF) UnicastRemoteObject.exportObject(engine, 0);
Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind(name, stub);
System.out.println("Registry bound!");
}
catch (Exception e) {
System.err.println("ComputeEngine exception:");
e.printStackTrace();
}
}
}
RMIClient eclipse project
GetAnswerTask class
package client;
import interfaces.TaskWithoutInput;
public class GetAnswerTask implements TaskWithoutInput<Integer> {
private static final long serialVersionUID = 1L;
#Override
public Integer compute() {
return Integer.valueOf(42);
}
}
Client class
package client;
import interfaces.ComputeEngine_IF;
import interfaces.TaskWithoutInput;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class RmiClientExample {
public static void main(String args[]) {
if(System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
String name = "Compute";
Registry registry = LocateRegistry.getRegistry("localhost");
ComputeEngine_IF comp = (ComputeEngine_IF) registry.lookup(name);
TaskWithoutInput<Integer> getAnswer = new GetAnswerTask();
Integer answer = comp.compute(getAnswer);
System.out.println("Answer: " + answer);
}
catch (Exception e) {
System.err.println("RmiClientExample exception:");
e.printStackTrace();
}
}
}
Both projects contain an identical security policy file (in RMIServer it is called server.policy and in RMIClient it is called client.policy)
grant {
permission java.security.AllPermission;
};
I will, of course, restrict the permissions more once I get this working.
Building/Running
Since the code is pretty close to something I copied out of an example, my guess is that the code is right, or at least close, but that my mistake is in compiling/running the code. The example wasn't written for eclipse, so I don't have exact instructions.
The first thing I did was use eclipse's jar export wizard to jar the interface package into Interfaces.jar which I just placed in my RMIServer folder.
Then I run ComputeEngine with the following defines:
-Djava.rmi.server.codebase=file:/c:/Users/nate/workspace/RMIServer/Interfaces.jar
-Djava.rmi.server.hostname=localhost
-Djava.security.policy=c:/Users/nate/workspace/RMIServer/src/server.policy
The compute engine seems to run just find and outputs the print statement in the code.
I then run the client with the defines:
-Djava.rmi.server.codebase=file:/c:/Users/nate/workspace/RMIClient/bin/
-Djava.security.policy=c:/Users/nate/workspace/RMIClient/src/client.policy
And I get the following error message:
RmiClientExample exception:
java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: client.GetAnswerTask
at sun.rmi.server.UnicastServerRef.dispatch(Unknown Source)
at sun.rmi.transport.Transport$1.run(Unknown Source)
at sun.rmi.transport.Transport$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
at sun.rmi.server.UnicastRef.invoke(Unknown Source)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(Unknown Source)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(Unknown Source)
at com.sun.proxy.$Proxy0.compute(Unknown Source)
at client.RmiClientExample.main(RmiClientExample.java:24)
Caused by: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: client.GetAnswerTask
at sun.rmi.server.UnicastServerRef.dispatch(Unknown Source)
at sun.rmi.transport.Transport$1.run(Unknown Source)
at sun.rmi.transport.Transport$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: client.GetAnswerTask
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.rmi.server.LoaderHandler$Loader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at sun.rmi.server.LoaderHandler.loadClassForName(Unknown Source)
at sun.rmi.server.LoaderHandler.loadClass(Unknown Source)
at sun.rmi.server.LoaderHandler.loadClass(Unknown Source)
at java.rmi.server.RMIClassLoader$2.loadClass(Unknown Source)
at java.rmi.server.RMIClassLoader.loadClass(Unknown Source)
at sun.rmi.server.MarshalInputStream.resolveClass(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at sun.rmi.server.UnicastRef.unmarshalValue(Unknown Source)
at sun.rmi.server.UnicastServerRef.unmarshalParametersUnchecked(Unknown Source)
at sun.rmi.server.UnicastServerRef.unmarshalParameters(Unknown Source)
... 13 more
Any thoughts on what I might be doing wrong?
GetAnswerTask implements Serializable, so it will be serialized to the server when you call ComputeEngine_IF.compute(). So GetAnswerTask needs to be available at the server, on its classpath, and it isn't.
For those still struggling with oracle RMI tutorial, whose server doesn't download serializable class from given client's codebase (and stubbornly seeks class in its own codebase) - try to add
-Djava.rmi.server.useCodebaseOnly=false
to server's arguments
I'm trying to create a jms publisher/subscriber chat application in eclipse.
import java.util.Properties;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class TopicConsumer implements MessageListener {
public static void main(String[] args) throws JMSException, NamingException {
System.out.println(".....Entering JMS example TopicConsumer....");
Context context = TopicConsumer.getInitialContext();
TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
Topic topic = (Topic) context.lookup("topic/zaneacademy_jms_tutorial_01");
TopicConnection topicConnection = topicConnectionFactory.createTopicConnection();
TopicSession topicSession = topicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
topicSession.createSubscriber(topic).setMessageListener(new TopicConsumer());
topicConnection.start();
System.out.println("......Exiting JMS Example TopicConsumer.....");
}
public void onMessage(Message message) {
try {
System.out.println("Incoming Messages: " + ((TextMessage)message).getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
public static Context getInitialContext() throws JMSException, NamingException {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");
props.setProperty("java.naming.provider.url", "localhost:1099");
Context context = new InitialContext(props);
return context;
}
}
trying to run the program I'm getting the following errors in console
.....Entering JMS example TopicConsumer....
Exception in thread "main" javax.naming.NameNotFoundException: zaneacademy_jms_tutorial_01 not bound
at org.jnp.server.NamingServer.getBinding(NamingServer.java:564)
at org.jnp.server.NamingServer.getBinding(NamingServer.java:572)
at org.jnp.server.NamingServer.getObject(NamingServer.java:578)
at org.jnp.server.NamingServer.lookup(NamingServer.java:317)
at org.jnp.server.NamingServer.lookup(NamingServer.java:291)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.rmi.server.UnicastServerRef.dispatch(Unknown Source)
at sun.rmi.transport.Transport$1.run(Unknown Source)
at sun.rmi.transport.Transport$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
at sun.rmi.server.UnicastRef.invoke(Unknown Source)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(Unknown Source)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(Unknown Source)
at com.sun.proxy.$Proxy0.lookup(Unknown Source)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:669)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:629)
at javax.naming.InitialContext.lookup(Unknown Source)
at TopicConsumer.main(TopicConsumer.java:19)
As it says in the exception the zaneacademy_jms_tutorial_01 is not defined.
You need to configure it and assigne it to the topic/zaneacademy_jms_tutorial_01.
I would say, that the problem is your getInitialContext() which you configure mannaully, instead of returing the probably already configured context by new InitialContext();
I have tried many ways but i am always getting the same exception, PayPalRESTException: Connection timed out: connect . I have even downloaded sample code provided by paypal and tried using those code, but still same error.
Please help me to come out from this problem. or at least provide your opinion.
Error Log :
SEVERE: Servlet.service() for servlet [signup] in context with path [/PayPalDemo] threw exception [com.paypal.core.rest.PayPalRESTException: Connection timed out: connect] with root cause
java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at com.paypal.core.HttpConnection.execute(HttpConnection.java:93)
at com.paypal.core.rest.OAuthTokenCredential.generateOAuthToken(OAuthTokenCredential.java:132)
at com.paypal.core.rest.OAuthTokenCredential.generateAccessToken(OAuthTokenCredential.java:95)
at com.paypal.core.rest.OAuthTokenCredential.getAccessToken(OAuthTokenCredential.java:86)
at com.paypal.util.AccessTokenGenerator.getAccessToken(AccessTokenGenerator.java:20)
at com.paypal.util.AppHelper.createCreditCard(AppHelper.java:54)
at com.paypal.controller.UserServlet.handleSignup(UserServlet.java:268)
at com.paypal.controller.UserServlet.doPost(UserServlet.java:117)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I have visited several blogs also for figure out this problem but they suggested to check request URL.
I am using sendbox environment so i have provided following url :
https://api.sandbox.paypal.com
This is my SDK configuration file :
# Connection Information
http.ConnectionTimeOut=5000
http.Retry=1
http.ReadTimeOut=30000
http.MaxConnection=100
# HTTP Proxy configuration
# If you are using proxy set http.UseProxy to true and replace the following values with your proxy parameters
http.UseProxy=false
#http.ProxyPort=8080
#http.ProxyHost=127.0.0.1
#http.ProxyUserName=null
#http.ProxyPassword=null
#Set this property to true if you are using the PayPal SDK within a Google App Engine java app
http.GoogleAppEngine = false
# Service Configuration
service.EndPoint=https://api.sandbox.paypal.com
clientID=EOJ2S-Z6OoN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp (changed my own)
clientSecret=EClusMEUk8e9ihI7ZdVLF5cZ6y0SFdVsY9183IvxFyZp (changed my own)
Servlet File :
package com.paypal.api.payments.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.Address;
import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Authorization;
import com.paypal.api.payments.CreditCard;
import com.paypal.api.payments.Details;
import com.paypal.api.payments.FundingInstrument;
import com.paypal.api.payments.Payer;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.Transaction;
import com.paypal.api.payments.util.GenerateAccessToken;
import com.paypal.core.rest.APIContext;
import com.paypal.core.rest.PayPalRESTException;
import com.paypal.core.rest.PayPalResource;
public class GetAuthorizationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(GetAuthorizationServlet.class);
public void init(ServletConfig servletConfig) throws ServletException {
InputStream is = GetAuthorizationServlet.class
.getResourceAsStream("/sdk_config.properties");
try {
System.out.println("in read::");
PayPalResource.initConfig(is);
} catch (PayPalRESTException e) {
e.printStackTrace();
LOGGER.fatal(e.getMessage());
}
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
APIContext apiContext = null;
String accessToken = null;
try {
accessToken = GenerateAccessToken.getAccessToken();
System.out.println("Access Token ::"+accessToken);
} catch (PayPalRESTException e) {
e.printStackTrace();
req.setAttribute("error", e.getMessage());
}
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
}
Utility file that will get token from paypal
package com.paypal.util;
import com.paypal.core.ConfigManager;
import com.paypal.core.rest.OAuthTokenCredential;
import com.paypal.core.rest.PayPalRESTException;
public class AccessTokenGenerator {
private static String accessToken;
public static String getAccessToken() throws PayPalRESTException {
if (accessToken == null) {
// ClientID and ClientSecret retrieved from configuration
String clientID = ConfigManager.getInstance().getValue("clientID");
String clientSecret = ConfigManager.getInstance().getValue("clientSecret");
accessToken = new OAuthTokenCredential(clientID, clientSecret).getAccessToken();
}
return accessToken;
}
}
Thanks in advanced.
I was facing this problem continuously since last 9 hrs but now i found the solution.
There is no error in code implementation but my firewall was not let them go to connect.
When i was turned off my firewall from control panel then all code works perfectly.
Thanks you
I am programming on a system with client running Java Applet on one end and server on the other. Now I have the client and server on the same computer. But as a client, I cannot see the applet and I get error like below:
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at MainJApplet.init(MainJApplet.java:58)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at RequestServer.sendRequest(RequestServer.java:25)
at createGUI.createEditingBar(createGUI.java:1313)
at GUI.createAndShowGUI(GUI.java:813)
at MainJApplet.init(MainJApplet.java:137)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
java.net.ConnectException: Connection refused: connect
java.lang.NullPointerException
at createGUI.createEditingBar(createGUI.java:1315)
at GUI.createAndShowGUI(GUI.java:813)
at MainJApplet.init(MainJApplet.java:137)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception: java.lang.NullPointerException
Below is where the problem traced back:
URL url = new URL(ipAddr);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); // exception happens
I checked http://localhost:8080/ and port conflict. I have turn off windows firewall and yet the problem exists. Can someone kindly point me some direction? Any advice would be great! Thanks ahead!
I apologize for the long code. The first is for client.
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.io.*;
public class MainJApplet extends JApplet {
GUI gui = new GUI();
Thread renewThread;
public void init() {
//pass parameters from url to applet
String filePath = this.getParameter("FilePath");
//temporary solution to bypass the new extention
String userName = this.getParameter("UserName");
String ipAddr = this.getParameter("IpAddress");
String userLevel = this.getParameter("UserLevel");
String ticket = this.getParameter("Ticket");
String accessMode = this.getParameter("AccessMode"); //1-normal 2-shared 3-email
//sharedTo will be get from the file path infor
String sharedTo = this.getParameter("ShareTo");
String type = this.getParameter("Type");
gui.shareTo = sharedTo;
gui.ticket = ticket; //this gui.ticket is used to varify email access, will be replaced
String relativePath = "";
try {
//connect to servlet
URL url = new URL(ipAddr);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
//Passing NAME+FILE+TICKET+TYPE to server at the initialization stage
out.write("IN");
out.write(userName + "#");
out.write(filePath + "#");
out.write(ticket + "#");
out.write(type + "#");
out.close();
//Wait for server response
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String dcodedStr;
StringBuffer decodedStringBuffer = new StringBuffer("");
while ((dcodedStr = in.readLine()) != null) {
decodedStringBuffer.append(dcodedStr);
}
String dStr = decodedStringBuffer.toString();
in.close();
if (dStr.equals("NOT_AUTHORIZED")) { //not passing authentication check
JOptionPane.showMessageDialog(new JFrame(),
"Access Denied",
"Warning!",
JOptionPane.ERROR_MESSAGE);
return;
} else {//pass authentication check
String[] initResp = dStr.split("#");
gui.FID = initResp[0]; //file ID
gui.EditMode = Boolean.parseBoolean(initResp[1]);
gui.userLevel = 1; //temporary set all as normal user
boolean firstOpen = Boolean.parseBoolean(initResp[2]);
relativePath = initResp[3];
if (initResp[4].trim().equals("normal")) {//owner
gui.accessMode = 1;
} else {//shared user
gui.accessMode = 2;
}
}
}catch(UnknownServiceException exp){
exp.printStackTrace();
}catch(IOException ex){
ex.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
public void destroy() {
gui.check_upon_window_close();
if (gui.is_new_drawing == 0) {
//2010.9.29 workDir -> FID
if (gui.EditMode) {
RequestServer.canClose(gui.IpAddress, gui.user, gui.FID);
} else {
RequestServer.canCloseNoEdit(gui.IpAddress, gui.user, gui.FID);
}
}
renewThread.stop();
}
}
Based off your comments my guess is that your server is binding to the loopback address (127.0.0.1, aka localhost). You didn't post what the server software is, but change it's configuration so that it binds on 0.0.0.0 instead. That should fix your issue.
I am trying to send an email from my application when a user logs in for the first time. The email consists of a activation code.
Update: I downloaded the latest javamail API and also the latest JAF (JavaBeans Activation Framework) and it does not compile due to imports being unknown symbols. How do I import from the javax package?
Here is the code that I got so far:
import java.util.ArrayList;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Email {
static String smtpHost;
static int smtpPort;
static String from;
static String to;
static String subject;
static String content;
public Email(String toEmail, String code){
smtpHost = "localhost";
smtpPort = 25;
from = "admin#Nestroia.com";
to = toEmail;
subject = "Hello from Nestroia.com";
content = "This is your activation code: " + code;
}
public Email(String toEmail, String name, String password){
smtpHost = "localhost";
smtpPort = 25;
from = "admin#Nestroia.com";
to = toEmail;
subject = "Hello from Nestroia.com";
content = "This is your Login information.\n"
+ "Name: " + name + "\n"
+ "Password: " + password;
}
public static void send() throws AddressException, MessagingException {
// Create a mail session
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", ""+smtpPort);
Session session = Session.getDefaultInstance(props, null);
// Construct the message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText(content);
// Send the message
Transport.send(msg);
Here is the stacktrace:
java.lang.RuntimeException: java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/mail/Address
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(Unknown Source)
at com.sun.glass.ui.win.WinApplication$2$1.run(Unknown Source)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/mail/Address
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at Nestroia.Nestroia_Main$6$1.handle(Nestroia_Main.java:669)
at Nestroia.Nestroia_Main$6$1.handle(Nestroia_Main.java:559)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Node.fireEvent(Unknown Source)
at javafx.scene.control.Button.fire(Unknown Source)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at com.sun.javafx.scene.control.skin.SkinBase$5.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.SkinBase$5.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1300(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
... 7 more
I'm guessing you probably have just the javaee.jar in your classpath, which has the definitions of the javax.mail.* classes but not the actual implementation.
You should download the javamail api if you dont already have. Found here
You're running with a javaee.jar that does not contain implementations. It's a "stubbed" implementation that is just intended to enable compilation, not execution. This post provides more details. (It's referring to Java EE 5, but the same holds true for 6.)
This post provides explanation and possible solution. You might need to adjust your class path.