I'm using mongo-java-driver-2.11.3.jar and also tried with mongo-2.10.1.jar both are giving the following error.The database is
connected but the collection insert and selection are not working.
import java.net.UnknownHostException;
import java.util.Set;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
public class mongo_test {
public MongoClient mongo = null;
public DB mongodb = null;
private void mongo_startconnection() {
try {
mongo = new MongoClient("10.0.2.15", 27017);
mongodb = mongo.getDB("foobar");
System.out.println("Mongodb is connected");
BasicDBObject doc = new BasicDBObject();
DBCollection collection = mongodb.getCollection("url_ta");
Set<String> colls = mongodb.getCollectionNames();
for (String s : colls) {
System.out.println(s);
}
System.out.println("done");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e1) {
e1.printStackTrace();
}
}
public static void main(String args[]) {
mongo_test MT = new mongo_test();
MT.mongo_startconnection();
}
}
I'm getting this error:
Mongodb is connected
Nov 26, 2013 11:34:39 AM com.mongodb.DBTCPConnector initDirectConnection
WARNING: Exception executing isMaster command on /10.0.2.15:27017
java.net.SocketTimeoutException: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(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 com.mongodb.DBPort._open(DBPort.java:223)
at com.mongodb.DBPort.go(DBPort.java:125)
at com.mongodb.DBPort.go(DBPort.java:106)
at com.mongodb.DBPort.findOne(DBPort.java:162)
at com.mongodb.DBPort.runCommand(DBPort.java:170)
at com.mongodb.DBTCPConnector.initDirectConnection(DBTCPConnector.java:547)
at com.mongodb.DBTCPConnector.checkMaster(DBTCPConnector.java:526)
at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:236)
at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:216)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:288)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:273)
at com.mongodb.DB.getCollectionNames(DB.java:400)
at mongo_test.mongo_startconnection(mongo_test.java:29)
at mongo_test.main(mongo_test.java:69)
com.mongodb.MongoException$Network: Read operation to server /10.0.2.15:27017 failed on database foobar at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:253)
at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:216)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:288)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:273)
at com.mongodb.DB.getCollectionNames(DB.java:400)
at mongo_test.mongo_startconnection(mongo_test.java:29)
at mongo_test.main(mongo_test.java:69)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(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 com.mongodb.DBPort._open(DBPort.java:223)
at com.mongodb.DBPort.go(DBPort.java:125)
at com.mongodb.DBPort.call(DBPort.java:92)
at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:244)
... 6 more
1.Trying to find out whether your ip address and port number is reachable.
use command: telnet 10.0.2.15",27017 to check if such a port for this ip is open for connection.
2.If you have the authority to login the mongodb server ,just login and then:
If your mongodb is a cluster , Use commmand : ps -ef|grep mongos to check the mongodb server instance is up and the port is just
27017.
if your mongodb is just a single machine ,use ps -ef|grep mongod to make the same check.
package raamji.com.start;
//import com.mongodb.MongoClient;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
public class Start {
public static void main(String[] args) throws UnknownHostException {
//crete Connection
Mongo mongoClient = new Mongo("ind-asingh", 27017);//or "localhost",27017
System.out.println("mongoClient :" + mongoClient);
DB db = mongoClient.getDB("DB Name");//e.g. MYDB
System.out.println("db :" + db);
//---------------------------Access your Collection-----------------------------
DBCollection collection = db.getCollection("message");
System.out.println("collection :" + collection);
System.out.println("Message Count: " + collection.getCount());
DBCursor cursor = collection.find();
try {
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
}//end pf psvm
}//end of class
Related
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");
I have trying to connect to Amazon RDS and were able to connect it once though I am unable to connect it again. I have checked my username, password, database name, server, etc. and they are all correct. I have all the required files included before the compilation.
I have attached my code below:
import java.io.File;
import java.net.URL;
import java.sql.*;
import java.util.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.InputSource;
import java.net.URL;
import java.sql.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.InputSource;
public class test_url {
#SuppressWarnings("null")
public static void main(String[] args){
String url = "jdbc:mysql://newtes.ctt52jgw7nwb6.eu-west-1.rds.amazonaws.com:3306/";
String userName = "amankijawani";
String password = "vegasishere";
String dbName = "newtesDB";
String driver = "com.mysql.jdbc.Driver";
System.out.println("Connecting database...");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url + dbName, userName, password);
System.out.println("Database connected!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ERROR
Connecting database...
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:988)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:341)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2251)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at test_url.main(test_url.java:44)
Caused by: 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 com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:211)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300)
... 15 more
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
HI I am having problem in java related to write on the web server from the client. I am using following code please help me where I am wrong
For Server class
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.util.Scanner;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class Server
{
public static void main(String args[]){
try{
ServerSocket s = new ServerSocket(8080);
System.out.println("ashish");
Socket incoming = s.accept();
System.out.println("the status of the socket="+incoming.isConnected());
InputStream inStream = incoming.getInputStream();
InputStreamReader isr=new InputStreamReader(inStream);
BufferedReader br=new BufferedReader(isr);
String str=null;
while((str=br.readLine()).equals("exit")==false){
System.out.println(str);
}
System.out.println("System exit");
}catch(Exception e){
e.printStackTrace();
}
}
}
And for the client class which is actually applet have folowing code
import java.applet.Applet;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class testApplet extends Applet
{
public void init(){}
public void start(){
try{
URL url = new URL("http://localhost:8080");
HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
PrintWriter out = new PrintWriter( httpCon.getOutputStream());
out.print("Resource content\n");
out.print("exit");
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
public void stop(){}
public void destroy(){}
}
Now when I run the server then the server display only the following
PUT / HTTP/1.1
User-Agent: Mozilla/4.0 (Windows Vista 6.1) Java/1.6.0
Host: localhost:8080
Accept: text/html, image/gif. image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
But it did not write the content which I write by the out object of PrintWriter
and next goes into wait state
on the other hand the applet does not started just initiated. and when I close server program then applet gives following exception
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.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.parseHTTP(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at testApplet.start(testApplet.java:19)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Please tell what's wrong with me
Try
httpCon.setChunkedStreamingMode(0);
before writing to outputstream. You should always do this on http connections if content length is not known in advance.