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.
Related
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
This is probably a common question but I can't figure it out.
I have this URL which returns the expected ticket detail if I plug it into a browser, so I know it is working:
https://www.myconnectwise.net/v4_6_release/services/system_io/integration_io/processClientAction.rails?actionString=%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-16%22%3F%3E%0A%3CGetTicketAction%20xmlns%3Axsi%3D%22http%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchemainstance%22%20xmlns%3Axsd%3D%22http%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchema%22%3E%0A%3CCompanyName%3Exxxxxxx%3C%2FCompanyName%3E%3CIntegrationLoginId%3Exxxxxx%3C%2FIntegrationLoginId%3E%3CIntegrationPassword%3Exxxxxx%3C%2FIntegrationPassword%3E%0A%3CSrServiceRecid%3E1921%3C%2FSrServiceRecid%3E%3C%2FGetTicketAction%3E
For a more readable version it is this URL:
https://www.myconnectwise.net/v4_6_release/services/system_io/integration_io/processClientAction.rails
Followed by:
?actionString=
Followed by this xml:
<?xml version="1.0" encoding="utf-16"?>
<GetTicketAction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CompanyName>xxxx</CompanyName><IntegrationLoginId>xxxx</IntegrationLoginId><IntegrationPassword>xxxx</IntegrationPassword>
<SrServiceRecid>1921</SrServiceRecid></GetTicketAction>
I am having problems putting this into code and getting it to work.
I get this error:
???????????????????????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????? o?????????????????????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????o???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
com.google.gwt.xml.client.impl.DOMParseException: Failed to parse: error on line 1 at column 1: Document is empty
at com.google.gwt.xml.client.impl.XMLParserImplSafari.throwDOMParseException(XMLParserImplSafari.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:338)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:219)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:279)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.xml.client.impl.XMLParserImplSafari.parseImpl(XMLParserImplSafari.java)
at com.google.gwt.xml.client.impl.XMLParserImpl.parse(XMLParserImpl.java:278)
at com.google.gwt.xml.client.XMLParser.parse(XMLParser.java:47)
at com.google.gwt.HelpDeskTest.client.HelpDeskTest.processXML(HelpDeskTest.java:232)
at com.google.gwt.HelpDeskTest.client.HelpDeskTest$2$1.onSuccess(HelpDeskTest.java:199)
at com.google.gwt.HelpDeskTest.client.HelpDeskTest$2$1.onSuccess(HelpDeskTest.java:1)
at com.google.gwt.user.client.rpc.impl.RequestCallbackAdapter.onResponseReceived(RequestCallbackAdapter.java:232)
at com.google.gwt.http.client.Request.fireOnResponseReceived(Request.java:258)
at com.google.gwt.http.client.RequestBuilder$1.onReadyStateChange(RequestBuilder.java:412)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:338)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:219)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:279)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:242)
at sun.reflect.GeneratedMethodAccessor29.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:293)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
at java.lang.Thread.run(Thread.java:695)
On this line:
System.out.println(line);
Here is all the code. As you can see I've tried setting serverParameters to both a URL encoded string as well as an xml string:
package com.google.gwt.HelpDeskTest.server;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.gwt.HelpDeskTest.client.HelpDeskTestService;
import com.google.gwt.HelpDeskTest.shared.HelpDeskTestException;
#SuppressWarnings("serial")
public class HelpDeskTestImpl extends RemoteServiceServlet implements
HelpDeskTestService {
#Override
public String postToRemoteServer(String serviceUrl)
throws HelpDeskTestException {
try {
final String serverPath = "https://www.myconnectwise.net/v4_6_release/services/system_io/integration_io/processClientAction.rails";
System.out.println(serverPath);
//DO I need to URL encode this???
//I’ve tried this:
//final String serverParameters= "%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-16%22%3F%3E%0A%3CGetTicketAction%20xmlns%3Axsi%3D%22http%3A%2F%2F" +
//"www.w3.org%2F2001%2FXMLSchema-instance%22%20xmlns%3Axsd%3D%22http%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchema%22%3E%0A%3CCompanyName" +
//"%3Exxxxx%3C%2FCompanyName%3E%3CIntegrationLoginId%3Exxxxx%3C%2FIntegrationLoginId%3E%3CIntegrationPassword%3Exxxxx%3C%2F" +
//"IntegrationPassword%3E%0A%3CSrServiceRecid%3E1921%3C%2FSrServiceRecid%3E%3C%2FGetTicketAction%3E";
final String serverParameters="<?xml version=%221.0%22 encoding=%22utf-16%22?><GetTicketAction xmlns:xsi=%22http://www.w3.org/2001/XMLSchema-instance%22 xmlns:xsd=%22http://www.w3.org/2001/XMLSchema%22><CompanyName>xxxx</CompanyName><IntegrationLoginId>xxxx</IntegrationLoginId><IntegrationPassword>xxxx</IntegrationPassword><SrServiceRecid>1921</SrServiceRecid></GetTicketAction>";
System.out.println(serverParameters);
//Open HttpURLConnection:
URL url = new URL(serverPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000); //added this to see if I can address the timeout issue.
connection.setReadTimeout(10000);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-16");
connection.setRequestProperty("Content-Length", "" + Integer.toString(serverParameters.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(serverParameters);
wr.flush();
wr.close();
//process response - need to get xml response back.
InputStream stream = connection.getInputStream();
//put output stream into a string
BufferedReader br = new BufferedReader(new InputStreamReader(stream,"utf-16"));
String result = "";
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
result+= line;
}
br.close();
connection.disconnect();
System.out.println(result);
return result;
} catch (final Exception e) {
System.out.println(e.getMessage());
throw new HelpDeskTestException();
//handle timeout error
}
}
}
I have got 'Server returned HTTP response code: 500 for URL: myconnectwise.net/v4_6_release/services/system_io/…; after executing of your code.
So check server (500 - Internal Server Error).
And analyze response code before parsing result as XML.
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
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.