Trouble creating a Java policy server for a simple Flash app - java

I'm trying to create a simple Flash chat application for educational purposes, but I'm stuck trying to send a policy file from my Java server to the Flash app (after several hours of googling with little luck).
The policy file request reaches the server that sends a harcoded policy xml back to the app, but the Flash app doesn't seem to react to it at all until it gives me a security sandbox error.
I'm loading the policy file using the following code in the client:
Security.loadPolicyFile("xmlsocket://myhostname:" + PORT);
The server recognizes the request as "<policy-file-request/>" and responds by sending the following xml string to the client:
public static final String POLICY_XML =
"<?xml version=\"1.0\"?>"
+ "<cross-domain-policy>"
+ "<allow-access-from domain=\"*\" to-ports=\"*\" />"
+ "</cross-domain-policy>";
The code used to send it looks like this:
try {
_dataOut.write(PolicyServer.POLICY_XML + (char)0x00);
_dataOut.flush();
System.out.println("Policy sent to client: " + PolicyServer.POLICY_XML);
} catch (Exception e) {
trace(e);
}
Did I mess something up with the xml or is there something else I might have overlooked?

I've seen your approach and after some time trying i wrote a working class, listening on any port you want:
package Server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class PolicyServer {
public static final String POLICY_XML =
"<?xml version=\"1.0\"?>"
+ "<cross-domain-policy>"
+ "<allow-access-from domain=\"*\" to-ports=\"*\" />"
+ "</cross-domain-policy>";
public PolicyServer(){
ServerSocket ss = null;
try {
ss = new ServerSocket(843);
} catch (IOException e) {e.printStackTrace();}
while(true){
try {
final Socket client = ss.accept();
new Thread(new Runnable() {
#Override
public void run() {
try {
client.setSoTimeout(10000); //clean failed connections
client.getOutputStream().write(PolicyServer.POLICY_XML.getBytes());
client.getOutputStream().write(0x00); //write required endbit
client.getOutputStream().flush();
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
//reading two lines emties flashs buffer and magically it works!
in.readLine();
in.readLine();
} catch (IOException e) {
}
}
}).start();
} catch (Exception e) {}
}
}
}

Try add \n at the end of policy xml.

Related

Socket connection not workin in flutter release apk

I am new to working with sockets, and I am working on this project where a connection between my android flutter app and a java server is needed, to do this I am trying socket programming.
The server code is fairly simple, I create a new thread for every client connected and I give them a bunch of URLs, later on, this should be replaced by a query result. here is the java code:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CrawlitServer {
// The port number on which the server will listen for incoming connections.
public static final int PORT = 6666;
//main method
public static void main(String[] args) {
System.out.println("The server started .. ");
// Create a new server socket
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
// Listen for incoming connections and create a new thread for each one
while (true) {
try {
new CrawlitServerThread(serverSocket.accept()).start();
}
catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
public static class CrawlitServerThread extends Thread {
private final Socket socket;
public CrawlitServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
List<String> list = new ArrayList<>();
//assign a value to list
list.add("http://www.google.com");
list.add("http://www.yahoo.com");
list.add("http://www.bing.com");
list.add("http://www.facebook.com");
list.add("http://www.twitter.com");
list.add("http://www.linkedin.com");
list.add("http://www.youtube.com");
list.add("http://www.wikipedia.com");
list.add("http://www.amazon.com");
list.add("http://www.ebay.com");
list.add("http://stackoverflow.com");
list.add("http://github.com");
list.add("http://quora.com");
list.add("http://reddit.com");
list.add("http://wikipedia.org");
try {
// Get the input stream from the socket
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
Scanner scanner = new Scanner(inputStream);
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
PrintWriter writer = new PrintWriter(outputStream, true);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println("Received Message from client: " + line);
writer.println(list + "\n");
}
}
catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}
Now I run this server and connect to it using sockets in Flutter, I give it the IP address I get from the ipconfig command, and here is the dart code:
import 'dart:async';
import 'dart:io';
//Utilities that manage connections with server sockets.
//ServerUtil Class
class ServerUtil {
static const port = 6666;
static const host = MY_IP_GOES_HERE;
static late Socket socket;
static bool connected = false;
//a list of urls returned by the server
static List<String> urls = [];
//Constructor
ServerUtil() {
//Initialize the socket.
Socket.connect(host, port).then((Socket sock) {
socket = sock;
connected = true;
socket.listen(dataHandler,
onError: errorHandler, onDone: doneHandler, cancelOnError: false);
//send a message to the server.
}).catchError((e) {
print("Unable to connect: $e");
});
}
//Query method that sends a message to the server. The server will return a list of urls.
//The urls will be added to the urls list.
//The urls list will be returned.
static Future<List<String>> query(String userQuery) async {
urls.clear();
//check if socket is connected.
if (connected) {
//send the query to the server.
socket.writeln(userQuery);
await Future.delayed(const Duration(milliseconds: 200));
print(urls);
return urls;
}
//if socket is not connected, wait for 5 seconds and try again.
await Future.delayed(const Duration(milliseconds: 50));
return query(userQuery);
}
//Handles data from the server.
void dataHandler(data) {
//String of received data.
String dataString = String.fromCharCodes(data).trim();
//remove first and last character from the string.
dataString = dataString.substring(1, dataString.length - 1);
//remove all the whitespace characters from the string.
dataString = dataString.replaceAll(RegExp(r'\s+'), '');
urls = dataString.split(',');
}
//Handles errors from the server.
void errorHandler(error, StackTrace trace) {
print(error);
}
//Handles when the connection is done.
void doneHandler() {
socket.destroy();
}
}
This works perfectly fine while using a debug apk running it on my real Note 9 device. The problem however is that when I build a release apk and try it out, nothing happens.
The way I set it up is that I wait for the query method in an async and then I send the result to a new screen and push that screen into the navigator.
But in the release apk nothing happens, the new screen doesn't load.
So this leads me to my first question:
Is there a way to debug a release apk? see what exceptions it throws or print some stuff to console?
I have the server running on my Laptop, and the app runs on my phone which is on the same WIFI network.
My second question is:
Do I need to enable some sort of option with my router or my laptop to allow my phone to connect? it does connect in debug mode without any modifications
I tried some random things, like using 'localhost' instead of my IP, as I would normally connect say with a java client for example, but it didn't work.
My last question is:
Does the release apk or like android OS prevent connections to local hosts, maybe because it thinks it is not secure? but then it still connects in debug mode.
Thank you for your time.

Reading Outbound messages from HTTP Streaming Connection in JAVA

I am implementing an integration client which will be connected to an API Gateway and send requests to the gateway. In short, I am the consumer of the API.
Now, the architecture the opposite party has built that I have to open a http streaming connection and read the outbound messages sent by the system.
In case of http streaming connection, it will be automatically closed if kept on idle state for a while so we have to send continuous heart-beat request to the system so that the stream connection shall stay alive.
Now I have following queries:
Do I have to use URLConnection.openConnection to open streaming channel?
How can I keep the stream open by sending requests? Do I have to open a separate thread for achieving this?
What are Outbound messages? Is the term refers to the responses I receive from the API?
How can I test it before getting actual testing setup? is there any dummy test case available on the internet where I can open stream and read data? if yes, please suggest any link?
I have to read JSON Data.
I have been provided with following Example Code for HTTP Streaming
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import javax.ws.rs.core.HttpHeaders;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
/** * Sample on Java * Open stream and start StreamReader to read stream in separate thread */
/** * Sample of stream processing */
public class StreamReader implements Runnable {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
final private BufferedReader in;
final private boolean toConsole;
final private String serviceName;
private final Crypto crypto;
StreamReader(BufferedReader in, boolean toConsole, String serviceName, Crypto crypto) {
this.in = in;
this.toConsole = toConsole;
this.serviceName = serviceName;
this.crypto = crypto;
}
#Override
public void run() {
String inputLine;
try {
stop:
while (!Thread.currentThread().isInterrupted()) {
try {
while (!StringUtils.isEmpty(inputLine = in.readLine())) {
if ( inputLine.startsWith( serviceName + ":" ) ) {
log.info("Stream message (outgoing from IPS):");
if (toConsole)
System.out.println("Stream message (outgoing from IPS):");
String[] s = inputLine.split(":");
if (s.length >= 2) {
log.debug("Encoded:");
log.debug(inputLine);
log.trace("Decoded:");
String decoded = URLDecoder.decode(s[1], "UTF-8");
log.trace(decoded);
NReply n = Gson.fromJson(decoded, NReply.class);
log.info("Readable:");
log.info(n.o.toString());
if (toConsole) {
System.out.println("Readable:");
System.out.println(n.o.toString());
}
if (s.length > 2) {
int lastSemicolon = inputLine.lastIndexOf(':');
log.debug("Signed data:");
final String signedData = inputLine.substring(0, lastSemicolon);
log.debug(signedData);
log.debug("base64 encoded signature:");
log.debug(s[2]);
try {
//crypto.checkSignSep(signedData, s[2]);
}
catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
else {
log.error("Invalid stream message:");
log.error(inputLine);
if (toConsole) {
System.out.println("Invalid stream message:");
System.out.println(inputLine);
}
}
}
else {
log.debug("View's info:");
log.debug(inputLine);
}
if ("CLOSED".equals(inputLine)) {
Thread.currentThread().interrupt();
break stop;
}
}
Thread.sleep(1000L);
}
catch (InterruptedException e) {
log.error(e.getMessage(), e);
Thread.currentThread().interrupt();
break;
}
catch (Exception e) {
log.error(e.getMessage(), e);
break;
}
}
log.info("polling has been stopped");
}
finally {
try {
in.close();
}
catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
public void openStream(boolean toConsole) throws IOException
{
//final URL stream = new URL (hostName+"/stream");
final URL stream = new URL ("url");
final URLConnection uc = stream.openConnection();
//uc.setRequestProperty(HttpHeaders.COOKIE, "JSESSIONID=" + heartBeat.getSessionId() );
uc.setRequestProperty(HttpHeaders.COOKIE, "JSESSIONID=" + "SessionIDFROMSERVICE" );
final BufferedReader in =new BufferedReader(new InputStreamReader(uc.getInputStream()));
StreamReader reader=new StreamReader(in,toConsole,serviceName,crypto);
Thread thread=new Thread(reader);
thread.setDaemon(true);
thread.start();
}
}
Any sort of help is appreciated.. :).

Get full URL path from browser with using ServerSocket and Socket classes

I'm trying write my individual HTTP Server and I need a help .
What is the method of ServerSocket or Socket class can to invoke on the URL and brining it into a code.
For example, if I write following link <b>http://localhost:8080/coupon/add?name=coupon name</b> in browser, I would be want to get this link into my code.
Maybe who know how can I do this?
my simple code:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class HTTPServer {
public static void main(String[] args) {
new HTTPServer().startServer();
}
public void startServer() {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server is started");
while (true) {
Socket socket = serverSocket.accept();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks
All your code does right now is set up a TCP server.
HTTP is a Layer 7 protocol.
Once you accept the connection from the client, HTTP can be used for communication over that TCP socket.
You'd have to parse the HTTP request that the client sends, and from that, you'd know the URL.
In your case, you said:
I write following link http://localhost:8080/coupon/add?name=coupon name in browser
Your browser will send an HTTP request like the following example:
GET /coupon/add?name=coupon+name HTTP/1.0
Host: localhost:8080
In reality, there will be more HTTP headers there, as well as a trailing \r\n, but for our sake, let's keep it simple.
Note that special characters like space are URL-encoded, however space is also encoded as + in the query string - it could be either + or %20 depending on the client.
Hopefully it's reasonably clear to you from this explanation how you get the URL from this HTTP request.
The only missing part from the actual full link is the http:// part. The distinction between HTTP and HTTPS is not part of the HTTP protocol - it's above the socket layer but below the HTTP protocol layer. If you had SSL sockets, you'd know that on the server side, and determine based on whether it was an SSL socket or a "plain" socket, whether it was http or https.
Hope that helps.
I improved for testing the startServer method for getting information.
I'm trying to include the data that comes from URL from any browsers to URI or URL class of JAVA.
This impossible ? Maybe who know how can I do this ?
public void startServer() {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server is started");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("SERVER SOCKET TESTS:");
System.out.println("getChannel: " + serverSocket.getChannel());
System.out.println("getInetAddress: " + serverSocket.getInetAddress());
System.out.println("getLocalPort: " + serverSocket.getLocalPort());
System.out.println("getLocalSocketAddress: " + serverSocket.getLocalSocketAddress());
System.out.println();
System.out.println("CLIENT SOCKET TESTS:");
System.out.println("getChannel: " + socket.getChannel());
System.out.println("getLocalAddress: " + socket.getLocalAddress());
System.out.println("getLocalPort: " + socket.getLocalPort());
System.out.println("getLocalSocketAddress: " + socket.getLocalSocketAddress());
System.out.println("getRemoteSocketAddress: " + socket.getRemoteSocketAddress());
System.out.println("getInetAddress: " + socket.getInetAddress());
System.out.println("getInputStream: " + socket.getInputStream());
System.out.println("getOutputStream: " + socket.getOutputStream());
System.out.println();
System.out.println("URI - GET INFORMATION:");
URI uri = new URI("httpscheme://world.hello.com/thismy?parameter=value");
System.out.println(uri.getHost());
System.out.println(uri.getPath());
System.out.println(uri.getQuery());
System.out.println(uri.getScheme());
}
} catch (Exception e) {
System.out.println("error");
}
}
little test:
when I run code and after that open the browser and I write in my browser, for example: http://localhost:8080 I get information, but I don't understand following:
why the serverSocket object in getInetAddress method (serverSocket.getInetAddress) have an IP4 and it 0.0.0.0 (why not a standard local ip that defined on my computer) and the socket object of getInetAddress method (socket.getInetAddress) have an IP6 and it 0:0:0:0:0:0:0:1 . How can I get a standard host name localhost how to get the URI class (with chunks of data of link)?
The port is gated nice: 8080.
The problem for getting URL path , solved.
package pk6HttpServer;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by Morris on 08/10/16.
*/
public class HTTPServer {
private static String headerData;
public static void main(String[] args) {
new HTTPServer().startServer();
}
public void startServer() {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
boolean isClosed = false;
System.out.println("Server is started");
while (true) {
Socket socket = serverSocket.accept();
try {
try (InputStream raw = socket.getInputStream()) { // ARM
System.out.println("=================BEFORE STARTING READING HEADER =======================");
System.out.println("Collecting data to string array...");
headerData = getHeaderToArray(raw);
//
System.out.println("+++++++++++++++++ AFTER ENDING READING HEADER +++++++++++++++++++++++");
System.out.println("Hello World");
}
} catch (MalformedURLException ex) {
System.err.println(socket.getLocalAddress() + " is not a parseable URL");
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
} catch (Exception ex) {
System.out.println("error# " + ex.getMessage());
}
}
public static String getHeaderToArray(InputStream inputStream) {
String headerTempData = "";
// chain the InputStream to a Reader
Reader reader = new InputStreamReader(inputStream);
try {
int c;
while ((c = reader.read()) != -1) {
System.out.print((char) c);
headerTempData += (char) c;
if (headerTempData.contains("\r\n\r\n"))
break;
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
headerData = headerTempData;
return headerTempData;
}
}

Hmlt5 audio not working with java http server

I'm creating one java http server, that usues html5 to play music.
The problem is that when I connect to the server over my browser ( chromium, firefox) it does not play the audio. But if I select to my browser show me the font code and I copy the font code and paste it on a file .html and I open this file with browser its works. What is my problem?
This is my java server
package br.ufla.sd.trabfinal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerHttp extends Thread {
private Socket clientSocket;
private static ServerSocket serverSocket;
private static int portNumber = 8088;
private PrintWriter out;
/**
* WebServer constructor.
*/
private ServerHttp(Socket clientSoc) {
clientSocket = clientSoc;
start();
}
public static void main(String args[]) {
serverSocket = null;
try {
serverSocket = new ServerSocket(portNumber);
System.out.println("Connection Socket Created");
try {
while (true) {
System.out.println("Waiting for Connection");
new ServerHttp(serverSocket.accept());
}
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
} catch (IOException e) {
System.err.println("Could not listen on port:" + portNumber);
System.exit(1);
} finally {
try {
serverSocket.close();
} catch (IOException e) {
System.err.println("Could not close port: " + portNumber);
System.exit(1);
}
}
}
public void run() {
System.out.println("New Communication, Thread " + this.getId()
+ " Started");
try {
// remote is now the connected socket
System.out.println("Connection, sending data.");
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream());
// read the data sent. We basically ignore it,
// stop reading once a blank line is hit. This
// blank line signals the end of the client HTTP
// headers.
String str = ".";
while (!str.equals(""))
str = in.readLine();
// Send the response
// Send the headers
out.println("HTTP/1.1 200 OK");
//out.println("Content-Type: text/html");
//out.println("Server: Bot");
// this blank line signals the end of the headers
out.println("");
// Send the HTML page
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<meta charset=\"UTF-8\">");
out.println("<title> Músicas</title>");
out.println("</head>");
out.println("<body>");
out.println("<H1>Welcome</H1>");
out.println("<audio controls>");
out.println("<source src=\"/****/Horse.wav\" type=\"audio/wav\">");
out.println("Your browser does not support the audio element.");
out.println("</audio>");
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
And another thing, if I change the file location to a online sound like this site : Site sound it works... Is someone know what is my problem?
Thanks!!
The problem is that you are just giving a path to the audio source. Think what will happen once this page loads on a browser and the user clicks to start the audio file.
Your browser will send a request again to the server to fetch the audio file. At this point in time, your server should accept the request and send the audio file back to the browser as an output stream.
The external link works because the file is present at the external link.
For your browser, the file is not present as your server doesn't seem to return any file for the request that the browser is making.
To confirm this you can check your browser's console. You will get a 404 for the audio file.

Listen to port via a Java socket

A server software my client communicates with regularly sends transaction messages on port 4000. I need to print those messages to the console line by line. (Eventually I will have to write those values to a table, but I’m saving that for later.)
I tried this code but it doesn’t output anything:
package merchanttransaction;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MerchantTransaction {
public static void main(String[] args) {
try {
InetAddress host = InetAddress.getLocalHost();
Socket socket = new Socket("192.168.1.104", 4000);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
ois.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
By the way, I need to be able to monitor that port until the program terminates. I’m not sure if the code above will be able to do that because I don’t see any iteration to the code.
I’m using Java version 1.6.0_24, SE Runtime Environment (build 1.6.0_24-b07) running on Ubuntu.
You need to use a ServerSocket. You can find an explanation here.
What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:
$ nc -l 4000
...and change socket address to localhost:4000, it will work and try to read something from nc-created server.
What you probably want is to create a ServerSocket and listen on it:
ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();
The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)
Try this piece of code, rather than ObjectInputStream.
BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
while (true)
{
String cominginText = "";
try
{
cominginText = in.readLine ();
System.out.println (cominginText);
}
catch (IOException e)
{
//error ("System: " + "Connection to server lost!");
System.exit (1);
break;
}
}

Categories