Calling a webpage without opening it from processing - java

I'm totally desperate trying to do this. I Started a new job where I was given an app made in Processing and now I need it to call a simple index.html(https://west-4f2bc.firebaseapp.com) but not opening it on the browser.
Is there anyway to do it?
later I'm going to pass data adding parameters in URL but now I just need to call it as it is without a window opening.
Please Help me.....
I tried a lot of variants of this code
import processing.net.*;
Client myClient;
void setup() {
// Connect to the local machine at port 10002.
// This example will not run if you haven't
// previously started a server on this port.
myClient = new Client(this, "west-4f2bc.firebaseapp.com", 80);
// Say hello
myClient.write("GET /\r\n");
}
void draw() {
}
Thanks.
With this I only get true, so it connects but I only get 0.
import processing.net.*;
Client myClient;
int dataIn;
void setup() {
size(200, 200);
// Connect to the local machine at port 5204.
// This example will not run if you haven't
// previously started a server on this port.
myClient = new Client(this, "west-4f2bc.firebaseapp.com", 80);
println(myClient.active());
println(dataIn);
}
void draw() {
}
with this I get connected but after Client SocketException: Socket closed
import processing.net.*;
Client myClient;
int dataIn;
void setup() {
Client client;
client = new Client(this, "west-4f2bc.firebaseapp.com", 80);
if (client.active()==true) {
println("connected");
// Make a HTTP request:
client.write("GET /call.html?id=ola&nome=artur\r\n");
client.write("\r\n");
client.stop();
} else {
// if you didn't get a connection to the server:
println("connection failed");
}
}

I've never really used Processing's Networking library, but from what I can tell it's not usually used to read data from a website- it's used for lower-level communication between a client and server. It might be possible to use it to read a website, but what you have already looks more complicated than it has to be.
Remember that Processing is built on top of Java, so anything you can do in Java, you can do in Processing. If I were you, I would do a google search for "java read website" for a ton of results, including:
Reading Directly from a URL
How to read a text file directly from Internet using Java?
Reading website's contents into string
How to read a text from a web page with Java?
Using Java to pull data from a webpage?

I used another library.
import http.requests.*;
void setup()
{
size (100, 100);
}
void draw()
{
PostRequest post = new PostRequest("https://"+"www.example.com");
post.send();
System.out.println("Reponse Content: " + post.getContent());
System.out.println("Reponse Content-Length Header: " + post.getHeader("Content-Length"));
noLoop();
}
Still doesnt does my final objective but at least it can communicate with the page.

Related

Chat communication works while debugging but not while running from command-line

I am working in a chat application where I have a server and I can connect several clients to that server to talk between them using TCPIP.
I've done the application using the command-line and works perfectly. Now I am trying to do the same but using a UI with its corresponding buttons to connect to the server and to send messages. For the application using the command-line I've followed the Oracle's tutorial.
The problem I am having now is that when I click the SEND button when debugging, I can see that the message is sent from the corresponding client to the server, and then broadcasted to the rest of the clients, but when I am not debugging, I mean, running the .class file from the command-line so I can open several Client windows, when I click the SEND button, the Client is unable to send the message. I don't understand why while running the client debugging from the IDE it works, and when doing it from the cmd it doesn't.
When I click the SEND button, I am setting a global variable I have in my main class to true, so the WriteThread I have to send the messages can see the global variable set to true and send the message, changing again the global variable to false, as it already has sent the message.
While debugging, it seems that the listener of the SEND button is changing correctly the value of the global variable, and the WriteThread is able to read it, so it send the message. But this doesn't happens when running the application from the command-line, and the exact point where I have the problem is that I've seen that the listener of the button changes properly the value, but for some reason the WriteThread class is not reading it, so it is always false and never sends the message
This is the global variable I have in my Main class:
public static boolean sendButtonPressed = false;
(I know it is not the best practice to have this variable as a flag set here in the main, but I am just trying to make this works, so any different idea would be kindly accepted)
Here is the ActionListener attached to my SEND button:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SendMessageButtonController implements ActionListener {
JTextField messageTextField;
JTextArea chatArea;
public SendMessageButtonController(JTextField messageTextField, JTextArea chatArea) {
this.messageTextField = messageTextField;
this.chatArea = chatArea;
}
#Override
public void actionPerformed(ActionEvent e) {
this.chatArea.append(this.messageTextField.getText() + "\n");
ChatGUI.sendButtonPressed = true;
}
}
And here is the WriteThread class code (important to say here that I have a WriteThread for writting and a ReadThread for reading to be able to send and receive in parallel):
import javax.swing.*;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class WriteThreadUI extends Thread {
private PrintWriter writer;
private Socket socket;
private ChatClientUI chatClient;
private JTextField messageTextField;
private JTextArea chatArea;
public WriteThreadUI(Socket socket, ChatClientUI chatClient, JTextField messageTextField, JTextArea chatArea) {
this.socket = socket;
this.chatClient = chatClient;
this.messageTextField = messageTextField;
this.chatArea = chatArea;
try {
OutputStream out = this.socket.getOutputStream();
writer = new PrintWriter(out, true);
} catch (IOException e) {
this.chatArea.append("Error getting output stream: " + e.getMessage() + "\n");
e.printStackTrace();
}
}
public void run() {
String text = "";
do {
if (ChatGUI.sendButtonPressed) {
if (!this.messageTextField.getText().equals("")) {
text = this.messageTextField.getText();
this.writer.println(text);
this.messageTextField.setText("");
ChatGUI.sendButtonPressed = false;
}
}
} while (!text.equals("bye"));
try {
socket.close();
} catch (IOException e) {
this.chatArea.append("Error writing to server: " + e.getMessage());
}
}
}
I have more code, so if needed I can update the question with all of it, but as it is a little bit long I just tried to put the more relevant parts of the project.
Here is a small and summarized flow of the code so you can understand how the classes of my project are related:
How can I say from the SendMessageButtonController to the WriteThread that my flag is true, so Writethread can see the flag and send the message when it is true?
If more info is needed I can update the question.
Thank you

AWS Android Chat App

I am trying to make an android chat application. I am thinking about making it with aws. But the problem is that I am unable to find any good tutorial for doing this and I have no idea how to do it.
So could anyone please suggest some tutorial for sending push notification or on how to make a chat application?
Firebase is well suited to this due to its "realtime database" feature. Here's a few tutorials I found by Googling
https://code.tutsplus.com/tutorials/how-to-create-an-android-chat-app-using-firebase--cms-27397
http://myapptemplates.com/simple-android-chat-app-tutorial-firebase-integration/
https://codelabs.developers.google.com/codelabs/firebase-android/#0
Check Socket.IO for android. ( https://github.com/socketio/socket.io-client-java )
Its really easy to write a chat application. But you need a server side.
Easy to write a simple server for this chat app.
Server reveice the all message from clients and broadcast the message, to all.
Gradle:
compile 'com.github.nkzawa:socket.io-client:0.5.1'
Android manifest:
<uses-permission android:name="android.permission.INTERNET" />
Java
public static Socket mSocket;
try {
mSocket = IO.socket("http://192.168.1.104:4444");
mSocket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
Send messsage to server:
MainActivity.mSocket.emit("message","Text here...");
Create a listener for another message:
MainActivity.mSocket.on("newMessage", onMessageArrive); // Oncreate
private Emitter.Listener onMessageArrive = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String)args[0];
// Here is all message. add it to list :) Or Push notif
}
});
}
};
// Server side:
var http = require('http');
var express = require('express'),
app = module.exports.app = express();
var io = require('socket.io').listen(app.listen(4444));
io.on('connection', function (socket) {
socket.on("message",function(msg){
io.sockets.emit('newMessage', msg);
});
});
Run:
npm install express
npm install socket.io
node filename.js
Just dont forget to check you IP! :)
Done! You have a Real Time Chat!!

Limit web service access to only one app

Right now I am working on a android app and I am totally new to this.
I want to make sure my web-service is only accessible via my app.
My background is PHP. In PHP I don't need to worry about anything like that, because everything runs on a server.
In case of Java and especially Android programming things are different. Even with encryption. Everybody can just open an APK and see how the web service gets accessed. So is there a way to hide or to obfuscate the access to a web service, so only my app will be able to use it?
For test purposes I didn't add any security or encryption. This is the basic call to a web server I am doing right now:
String url = "http://thisismyurl.com/a.php?action=get";
String result = Web.executeWeb(url);
public class Web {
public static String executeWeb(final String url) {
final StringBuilder sb = new StringBuilder();
Thread thread = new Thread(new Runnable() {
public void run()
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String result, line = reader.readLine();
result = line;
while((line=reader.readLine())!=null){
result+=line;
}
sb.append(result);
//System.out.println(result);
//Log.i("My Response :: ", result);
} catch (Exception e)
{
// TODO: handle exception
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
}
How would I hide this from the prying eyes of hackers? ;-) Is that even possible?
Thanks in advance!
Deploy client authentication using (self signed) certificates within TLS.
This kind of configuration can be enabled on most web servers and Java application servers, and you can normally also configure the web or application server in such a way that you can retrieve the certificate of the private key that the client used to authenticate itself.
Note that HTTPS uses SSL (or now TLS) before any web trafic, so you cannot program this in your application, it does require server configuration.
Check this link on how to configure for Apache 2.
Use your Application's ID ( like IMEI ) as parameter in your webservice call. You need to make a table in database at server side which will store all registered device. Now only these registered device can access your webservice. This is my idea, there should be other idea as well.

Google App Engine HTTP ERROR 503 error

Ï am Taking data From server written in "C" using Sockets .
My java class name is ReceivingData, and here's the code for receiving the data and storing it in ArrayList and passing the ArrayList to other Class's Constructor.
package pack.exp;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ReceivingData implements Runnable
{
public static void main(String[] args)
{
Thread t = new Thread(new ReceivingData());
t.start();
}
public List<String> obj1;
#Override
public void run()
{
Socket s;
InputStream stream;
try
{
s = new Socket("10.9.211.22", 6870);
stream = s.getInputStream();
byte[] data = new byte[13];
int read;
String can_Id= null;
while((read = stream.read(data)) != -1)
{
String can_Data=
String.format("%02X:%02X:%02X:%02X,
data[0], data[1], data[2], data[3]);
List<String> obj1= new ArrayList<String>();
obj1.add(can_Data.substring(0, 2));
obj1.add(can_Data.substring(3, 5));
obj1.add(can_Data.substring(6, 8));
obj1.add(can_Data.substring(9, 11));
Receiving_At_Regular_IntervalServlet rari= new
Receiving_At_Regular_IntervalServlet(obj1);
Thread.sleep(3000);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
This is the Servlet which is receiving the data from ArrayList passed by the above File.
and storing this data from the arraylist in to the Entity for datastore and deploys it on the Google App engine.
package pack.exp;
#SuppressWarnings("serial")
public class Receiving_At_Regular_IntervalServlet extends HttpServlet
{
List<String> obj2= new ArrayList<String>();
public Receiving_At_Regular_IntervalServlet(List<String> obj2) throws
IOException
{
this.obj2= obj2;
System.out.println("Receiving in Web Project" + obj2);
System.out.println("");
System.out.println("");
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
IOException
{
Key k1 = KeyFactory.createKey("C","0D F0 0800 1");
String parameter1 = obj2.get(0);
Entity can1 = new Entity(k1);
can1.setProperty("First Parameter", parameter1);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(can1);
Entity can11 = null;
try
{
can11= datastore.get(k1);
}
catch (EntityNotFoundException e)
{
e.printStackTrace();
}
String first_P= (String) can11.getProperty("First Parameter");
resp.setContentType("text/plain");
resp.getWriter().println("Parameter--- " + first_P);
}
}
The ReceivingData code evidently runs a thread and reads data from 10.9.211.22 port 6870 using Socket from a local computer. That's fine. It converts four bytes to a List and passes that to Receiving_At_Regular_IntervalServlet. Fine but not what you need.
This part might work on a development computer but won't work if deployed to the cloud. AppEngine servers does not permit developers to define main(), use Socket or communicate with private IP subnet 10. Forget about deploying that code to AppEngine.
Receiving_At_Regular_IntervalServlet has a custom constructor. AppEngine does not call your constructor because its servlet code expects only the default constructor. That is probably when your 503 error occurs.
With servlets the data is not supposed to come in via a constructor. Data must come in via members of the request parameter of the doGet method (though to be RESTful you should rather use doPut in this example). You insert the data into the request parameter but sending a correctly constructed http request to the server. Your code lacks that web application design.
Build your main program and your AppEngine code in separate projects and make main talk to servlet using http.
HTTP ERROR 503 error
You can't help anything when a server throws this error. It is only thrown when a service from the server is unavailable.
You need explicit handling on such error codes, other than 200 OK, in the client app and appropriate message has to be shown or as the alternate requirement suggestion.
Refer to:
Status Code definitions
Java - 503 - SC_SERVICE_UNAVAILABLE

Firefox, websockets and odd behaviours

Background:
Using WebSockets with JavaScript + Play! framework (2.2).
Can send and receive data fine in Chrome.
Can only receive data (from server) in Firefox as send() doesn't trigger any callbacks.
In addition to the send issue, and in Firefox only again, the tab for the page is always stuck on "connecting" while the spinner keeps spinning (see figure 1).
Misbehaving Browser:
Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0)(Firefox 24.0)
(Figure 1. Firefox tab after page has loaded and data is shown)
Any time I refresh the web page, I receive the error below, attributed to the constant page loading behaviour I'm sure.
The connection to ws://localhost:9000/ was interrupted while the page was loading.
The entire JavaScript code:
$(function() {
var chatSocket = new WebSocket("#routes.Application.getMetaData().webSocketURL(request)");
var sendMessage = function() {
chatSocket.send(JSON.stringify({
id: "unique",
name: "a name",
age: 22
}));
}
var receiveEvent = function(event) {
var data = JSON.parse(event.data)
document.write(data.age);
document.write(data.name);
document.write(data.message);
document.write("\n");
sendMessage();
chatSocket.close();
}
chatSocket.onmessage = receiveEvent
})
Now In the past, I've been trying with MozWebSocket instead of the standard WebSocket, but I get nothing rendered on screen using that module therefore unless there is an angle I've missed, WebSocket is the better one to use.
The relevant Play! block:
public static WebSocket<JsonNode> getMetaData() {
return new WebSocket<JsonNode>() {
// Called when the Websocket Handshake is done.
public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) {
// For each event received on the socket,
in.onMessage(new Callback<JsonNode>() {
#Override
public void invoke(JsonNode jsonNode) {
System.out.println("Message Incoming!");
System.out.println(jsonNode.get("id"));
System.out.println(jsonNode.get("name"));
System.out.println(jsonNode.get("age"));
}
});
// When the socket is closed.
in.onClose(new Callback0() {
public void invoke() {
System.out.println("Disconnected");
}
});
ObjectNode node = Json.newObject();
node.put("message", "hello");
node.put("name", "client");
node.put("age", 1);
out.write(node);
//same result commented/uncommented
out.close();
}
};
}
So in Chrome, the flow would be:
document.write(...)
"Message Incoming!"
... JSON attributes
"Disconnected"
But in Firefox, the flow is:
document.write(...)
"Disconnected"
Any help in diagnosing these problems would be greatly appreciated. I have no intention of supporting IE, but having both Mozilla and Chrome working would be great.
Other JavaScript Warnings:
Below is a warning I occasionally get in Firefox's console while pointing at the "ws" protocol as the culprit. What its relevance is to my problem, I do not know.
Use of getPreventDefault() is deprecated. Use defaultPrevented instead.
You call document.write() after the document is loaded, which then implies document.open() which in turn replaces the document and by that unloads the old one and aborts stuff like timeouts or websockets.
Use something other than document.write() and you should be fine.

Categories