FileNotFoundException while calling TheRockTrading API - java

I'm trying to access TheRockTrading Exchange APIs, but when i try to access the private balance query, gives FileNotFoundException
public static void main(String[] args) throws InterruptedException {
try {
//MANNAGGIA ALLA MADONNA
URL a = null;
try {
a = new URL("https://api.therocktrading.com/v1/balance");
} catch (MalformedURLException ex) {
Logger.getLogger(Miner.class.getName()).log(Level.SEVERE, null, ex);
}
HttpsURLConnection ac = (HttpsURLConnection) a.openConnection();
ac.setRequestMethod("GET");
ac.setDoInput(true);
ac.setAllowUserInteraction(false);
ac.setRequestProperty("User-Agent", "infofetch");
ac.setRequestProperty("Connection", "close");
try(BufferedReader br = new BufferedReader(new InputStreamReader(ac.getInputStream()))) {
String l = null;
while ((l=br.readLine())!=null) {
System.out.println(l);
}
} catch(IOException ioex) {
System.err.println("IOException while reading");
ioex.printStackTrace();
}
} catch (IOException ex) {
Logger.getLogger(Miner.class.getName()).log(Level.SEVERE, null, ex);
}
}
APIkey and signature are missing but i should at least receive something instead of FileNotFoundException
java.io.FileNotFoundException: https://api.therocktrading.com/v1/balance
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1890)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)
at Miner.main(Miner.java:37)

Related

How can I call a WebMethod in Java Applet

How can I call a C# WebMethod in my Java Applet ?
The method called EnrollClient in C#
My Try
public void enroll(String teste) {
URL u;
InputStream is = null;
try {
u = new URL("http://localhost:5154/lb.ashx?pwd=abci/EnrollClient");
is = u.openStream();
BufferedReader d = new BufferedReader(new InputStreamReader(is));
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
is.close();
} catch (IOException ioe) {
}
}
C# WebMethod
public class lb : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
strings pwd = context.Request["pwd"].ToString();
business.Client.lb cli = new business.Client.lb();
JavaScriptSerializer jss = new JavaScriptSerializer();
StringBuilder sbRes = new StringBuilder();
jss.Serialize(cli.ReturnJSon(), sbRes);
context.Response.Write(sbRes.ToString());
}
[WebMethod]
public void EnrollClient()
{
string template = string.Empty;
string client = string.Empty;
try
{
business.Client.lb cli = new business.Client.lb();
cli.EnrollClient(template, client);
}
catch (Exception e)
{
}
}
If I do the same code but with the code
u = new URL("http://localhost:5154/lb.ashx?pwd=abci");
it will access the ProcessRequest of my C# code.

Sockets ClassCastException HashMap

I've created a serverSocket and accept a client connection. However, when I try to read from the client, it is throwing the following exception. If I change HashMap to ArrayList, it does not work either.
Exception in thread "Thread-3" java.lang.ClassCastException: java.awt.Point cannot be cast to java.util.HashMap
at ServerSide.Server.getPoints(Server.java:112)
at ServerSide.Server.run(Server.java:69)
public void getPoints() throws IOException, ClassNotFoundException {
points = (HashMap<Point, Boolean>) objectInputStream.readObject();
Iterator iterator = points.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Point, Boolean> currentPoint = (Map.Entry<Point, Boolean>) iterator.next();
currentPoint.setValue(firgure.isHit(currentPoint.getKey().x, currentPoint.getKey().y));
}
objectOutputStream.writeObject(points);
}
Sending method:
#Override
public HashMap<Point, Boolean> update(HashMap<Point, Boolean> points) throws IOException {
output.println("hit");
output.flush();
toServer.writeObject(points);
try {
return (HashMap<Point, Boolean>) fromServer.readObject();
} catch (ClassNotFoundException e) {
System.out.println("Some shit with classCast!");
return null;
}
}
UDP new type exception:
java.io.StreamCorruptedException: invalid type code: 3F
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1377)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
at ServerSide.Server.getPoints(Server.java:102)
at ServerSide.Server.run(Server.java:69)
This video shows how it's (not) working:
http://www.youtube.com/watch?v=8924rrSyWfY&feature=youtu.be
Maybe my server or client is bad? Can anyone see some mistake? (I so sorry for my English)
Server
public class Server extends Thread {
public static final int PORT = 1234;
private static ServerSocket serverSocket;
private Socket client;
private ObjectInputStream objectInputStream;
private ObjectOutputStream objectOutputStream;
private BufferedReader bufferedReader;
private PrintWriter printWriter;
private Firgure firgure;
private HashMap<Point, Boolean> points;
private Server(Socket client) {
System.out.println("Client connected");
this.client = client;
firgure = new Firgure();
try {
this.client.setSoTimeout(0);
} catch (SocketException e) {
e.printStackTrace();
}
setDaemon(true);
setPriority(NORM_PRIORITY);
start();
}
static public void serverStart() throws IOException {
System.out.println("Server startes");
serverSocket = new ServerSocket(PORT);
serverSocket.setSoTimeout(0);
System.out.println("Wait client");
while (true) new Server(serverSocket.accept());
}
static public void main(String[] args) throws IOException {
serverStart();
}
#Override
public void run() {
try {
objectInputStream = new ObjectInputStream(client.getInputStream());
objectOutputStream = new ObjectOutputStream(client.getOutputStream());
bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
printWriter = new PrintWriter(client.getOutputStream(), true);
points = new HashMap<Point, Boolean>();
String inputLine;
do {
inputLine = bufferedReader.readLine();
if (inputLine.equalsIgnoreCase("hit")) getPoints();
else if (inputLine.equalsIgnoreCase("echo")) echo();
else if (inputLine.equalsIgnoreCase("close")) close();
else if (inputLine.equalsIgnoreCase("set")) set();
else if (inputLine.equalsIgnoreCase("get")) get();
else continue;
} while (true);
} catch (NullPointerException e) {
System.out.println("Client disconnect");
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (java.lang.ClassNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public int getR() {
return firgure.getR();
}
public void setR(int R) {
firgure.setR(R);
}
public void set() throws IOException, ClassNotFoundException {
setR((Integer) objectInputStream.readObject());
}
public void get() throws IOException {
objectOutputStream.writeObject(new Integer(getR()));
}
public void getPoints() throws IOException, ClassNotFoundException {
try {
points = (HashMap<Point, Boolean>) objectInputStream.readObject();
} catch (StreamCorruptedException e) {
e.printStackTrace();
points = new HashMap<Point, Boolean>();
} catch (ClassCastException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Iterator iterator = points.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Point, Boolean> currentPoint = (Map.Entry<Point, Boolean>) iterator.next();
currentPoint.setValue(firgure.isHit(currentPoint.getKey().x, currentPoint.getKey().y));
}
objectOutputStream.writeObject(points);
}
public void echo() throws IOException {
printWriter.println(bufferedReader.readLine());
}
private void close() {
try {
if (objectInputStream != null) objectInputStream.close();
if (objectOutputStream != null) objectOutputStream.close();
if (bufferedReader != null) bufferedReader.close();
if (client != null) client.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
CLient
public class Client implements IModel {
private static final int PORT = 1234;
private static final String HOST = "localhost";
private Socket server;
private ObjectOutputStream toServer;
private ObjectInputStream fromServer;
private BufferedReader input;
private PrintWriter output;
#Override
public HashMap<Point, Boolean> update(HashMap<Point, Boolean> points) throws IOException {
output.println("hit");
output.flush();
toServer.writeObject(points);
try {
return (HashMap<Point, Boolean>) fromServer.readObject();
} catch (ClassNotFoundException e) {
System.out.println("Some shit with classCast!");
return null;
}
}
#Override
public void connect() throws IOException {
server = new Socket(HOST, PORT);
toServer = new ObjectOutputStream(server.getOutputStream());
fromServer = new ObjectInputStream(server.getInputStream());
input = new BufferedReader(new InputStreamReader(server.getInputStream()));
output = new PrintWriter(server.getOutputStream(), true);
}
#Override
public void disconnect() throws IOException {
if (output != null) output.close();
if (input != null) input.close();
if (fromServer != null) fromServer.close();
if (toServer != null) toServer.close();
if (server != null) server.close();
}
#Override
public boolean isConnected() throws IOException {
if (server == null) return false;
return server.isConnected();
}
#Override
public int getFigureRadius() throws IOException {
output.println("get");
output.flush();
try {
return (Integer) fromServer.readObject();
} catch (ClassNotFoundException e) {
System.out.println("Some shit with cast");
return 0;
}
}
#Override
public void setFigureRadius(int newRadius) throws IOException {
output.println("set");
output.flush();
toServer.writeObject(newRadius);
}
}
This is very clear from your exception message. You are sending a Point and trying to receive a HashMap.
From log you get error on casting:
points = (HashMap<Point, Boolean>) objectInputStream.readObject();
To debug try:
Object obj = objectInputStream.readObject();
if(obj instanceof Map<Point, Boolean>){
...
}
else if(obj instanceof String){
...
}

Error 500 with Google AppEngine, and class java.net

I have a problem with gae. I have an application http://www.similarityface.appspot.com/query. I am trying through a program in java to communicate with this application to perform query, via the POST method. The problem that is generating 500 error.
The code is below, could someone help me telling what I'm doing wrong.
public class Vetores_Facebook {
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
final String server = "https://www.similarityface.appspot.com/query";
URL url = null;
try {
url = new URL(server);
} catch (MalformedURLException ex) {
Logger.getLogger(Vetores_Facebook.class.getName()).log(Level.SEVERE, null, ex);
}
HttpURLConnection urlConn = null;
try {
// URL connection channel.
urlConn = (HttpURLConnection) url.openConnection();
} catch (IOException ex) {
Logger.getLogger(Vetores_Facebook.class.getName()).log(Level.SEVERE, null, ex);
}
urlConn.setDoOutput (true);
// No caching, we want the real thing.
urlConn.setUseCaches (false);
try {
urlConn.setRequestMethod("POST");
} catch (ProtocolException ex) {
Logger.getLogger(Vetores_Facebook.class.getName()).log(Level.SEVERE, null, ex);
}
try {
urlConn.connect();
} catch (IOException ex) {
Logger.getLogger(Vetores_Facebook.class.getName()).log(Level.SEVERE, null, ex);
}
String message = URLEncoder.encode("get_object(\"me\", metadata=1)", "UTF-8");
try (OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream())) {
writer.write(message);
writer.close();
}
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("ok");
}
else{
int x = urlConn.getResponseCode();
System.out.println("error "+x);
}
}
}
try {
urlConn.connect();
} catch (IOException ex) {
Logger.getLogger(Vetores_Facebook.class.getName()).log(Level.SEVERE, null, ex);
}
String message = URLEncoder.encode("get_object(\"me\", metadata=1)", "UTF-8");
try (OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream())) {
writer.write(message);
writer.close();
}
The problem is you are calling urlConn.connect(); which seems to flush any output buffers you may have and prepares the connection to get an input stream. Trying to write to open an output stream after this will cause an exception.
Use the example given here for the correct way to do this: https://developers.google.com/appengine/docs/java/urlfetch/usingjavanet#Using_HttpURLConnection

Java Socket connection timeout Error Coming while contacting SMS gateway

Here is the code I am trying to send SMS through the red Oxygen server
Here is the code I am executing below
final String requestURL = "http://www.redoxygen.net/sms.dll?Action=SendSMS";
final StringBuilder stringBuilder = new StringBuilder();
try {
stringBuilder.append("AccountId=").append(URLEncoder.encode("****", "UTF-8"))
.append("&Email=").append(URLEncoder.encode("*******", "UTF-8"))
.append("&Password=").append(URLEncoder.encode("******", "UTF-8"))
.append("&Recipient=").append(URLEncoder.encode("******", "UTF-8"))
.append("&Message=").append(URLEncoder.encode("hello", "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
final URL address;
try {
address = new URL(requestURL);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
final HttpURLConnection connection;
try {
connection = (HttpURLConnection) address.openConnection();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new RuntimeException(e);
}
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(100000000);
DataOutputStream output = null;
try {
output = new DataOutputStream(connection.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
output.writeBytes(stringBuilder.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
While executing I am getting the below exception :
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:525)
at sun.net.NetworkClient.doConnect(NetworkClient.java:158)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:233)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.http.HttpClient.New(HttpClient.java:323)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:860)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:801)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:904)
at com.nextenders.server.LoginServlet.SendSMS(LoginServlet.java:143)
I tried with increasing connection timeout and turn off the firewall ...etc but no luck .Can anyone help me to trace the problem ??
Here is the tutorial I'm following :
http://www.redoxygen.com/developers/java/
The "*"s in my code is credentials for the gateway .
This is a network topology problem. You can't connect to that site from where you are. Some intervening firewall, probably your own, is preventing it. Talk to your netadmin.
The following code runs fine when I have tested it with other websites (as I don't have access your the messaging API):
final String requestURL = "http://www.redoxygen.net/sms.dll?Action=SendSMS";
final StringBuilder stringBuilder = new StringBuilder();
try {
stringBuilder.append("AccountId=").append(URLEncoder.encode("****", "UTF-8"))
.append("&Email=").append(URLEncoder.encode("*******", "UTF-8"))
.append("&Password=").append(URLEncoder.encode("******", "UTF-8"))
.append("&Recipient=").append(URLEncoder.encode("******", "UTF-8"))
.append("&Message=").append(URLEncoder.encode("hello", "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
final URL address;
try {
address = new URL(requestURL);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
final HttpURLConnection connection;
try {
connection = (HttpURLConnection) address.openConnection();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new RuntimeException(e);
}
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(100000000);
try {
connection.connect();
} catch (IOException e) {
throw new RuntimeException(e);
}
final DataOutputStream output;
try {
output = new DataOutputStream(connection.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
output.writeUTF(stringBuilder.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
final InputStream inputStream;
try {
inputStream = connection.getInputStream();
} catch (IOException e) {
final char[] buffer = new char[0x10000];
final StringBuilder stackBuilder = new StringBuilder();
final Reader in;
try {
in = new InputStreamReader(connection.getErrorStream(), "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
try {
int read;
do {
read = in.read(buffer, 0, buffer.length);
if (read > 0) {
stackBuilder.append(buffer, 0, read);
}
} while (read >= 0);
System.out.println("Error response code from server. Error was:");
System.out.println(stackBuilder.toString());
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
try {
in.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
throw new RuntimeException(e);
}
final char[] buffer = new char[0x10000];
final StringBuilder stackBuilder = new StringBuilder();
final Reader in;
try {
in = new InputStreamReader(inputStream, "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
try {
int read;
do {
read = in.read(buffer, 0, buffer.length);
if (read > 0) {
stackBuilder.append(buffer, 0, read);
}
} while (read >= 0);
System.out.println(stackBuilder.toString());
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
try {
in.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
It will toString the various streams and has error handling when the stream doesn't connect.
The most important change is using the DataOutputStream.writeUTF method rather than just the write method - this will ensure than the POST data is encoded correctly. I don't think this is your issue as the problem is on connect.
The example code you used seems to be unaware of Java naming conventions or best practices to I have tidied it considerably.
The stream reader can be pulled out and into a separate method to avoid duplication.
I would recommend pointing it at another website (I used my work's) and seeing if you get output.

StreamCorruptedException: invalid type code: 00

Server code:
while (true) {
Socket sock = serv.accept();
try {
new ClientSession(sock, outQueue, activeSessions);
System.out.println("CS");
} catch (IOException e) {
System.out.println("Sock error");
sock.close();
}
}
ClientSession:
class ClientSession extends Thread {
private Socket socket;
private OutboundMessages outQueue;
private ActiveSessions activeSessions;
private ObjectInputStream netIn;
private ObjectOutputStream netOut;
int n = 0;
boolean inGame = false;
boolean ready = false;
Player p;
public ClientSession(Socket s, OutboundMessages out, ActiveSessions as)
throws IOException {
socket = s;
outQueue = out;
activeSessions = as;
netOut = new ObjectOutputStream(socket.getOutputStream());
netOut.flush();
netIn = new ObjectInputStream(socket.getInputStream());
System.out.println("ClientSession " + this + " starts...");
while (true) {
Object nameMsg = null;
try {
nameMsg = netIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (nameMsg instanceof NameMessage) {
this.setName(((NameMessage) nameMsg).name);
break;
}
}
start();
}
public void run() {
try {
activeSessions.addSession(this);
while (true) {
Object inMsg = null;
try {
try {
inMsg = netIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
if (inMsg instanceof ReadyMessage) {
ready = true;
} else if (inMsg instanceof DirMessage) {
p.setDir(((DirMessage)inMsg).dir);
}
}
} finally {
try {
socket.close();
} catch (IOException e) {
}
}
}
public void sendMessage(Message msg) {
try {
if (!socket.isClosed()) {
netOut.writeObject(msg);
netOut.flush();
} else {
throw new IOException();
}
} catch (IOException eee) {
try {
socket.close();
} catch (IOException ee) {
}
}
}
Creating input and output on client side:
public void connect() {
try {
InetAddress serverAddr = InetAddress.getByName(serverName);
try {
System.out.println("Connecting with "
+ serverAddr.getHostName() + ":" + port);
socket = new Socket(serverAddr, port);
try {
System.out.println("Connected to "
+ serverAddr.getHostName());
netOut = new ObjectOutputStream(socket.getOutputStream());
netOut.flush();
netIn = new ObjectInputStream(socket.getInputStream());
netOut.writeObject(new NameMessage(name));
netOut.flush();
} finally {
}
} catch (ConnectException e) {
System.out.println("Cannot connect to server");
} catch (IOException e) {
System.out.println("Input error");
}
} catch (UnknownHostException e) {
System.out.println("Unknown server: " + e.getMessage());
}
}
receiver on client end:
public void run() {
while (true) {
Object a = null;
try {
a = netIn.readObject();
netIn.reset();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (a != null && a instanceof CoordMessage) {
setXY((CoordMessage)a);
}
}
}
Stacktrace:
java.io.StreamCorruptedException: invalid type code: 00
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at twoPlayerClient.Receiver.run(Receiver.java:28)
After creating input and output I keep passing them on to other classes and not creating new ones.
I have read other similar questions but can't find an answer to why this keeps happening.
new ClientSession(sock, outQueue, activeSessions);
I think, there is a new session for each client, and so you cannot use a stream variable, with global scope. Since its used by other session threads also.

Categories

Resources