I am trying to get native messaging between a chrome extension and a Java program to work.
After some struggling I now can open my Java program with:
var port = chrome.extension.connectNative('fbehost');
port.postMessage({ text: "Hello, my_application" });
But I don't know how I can read the message send from my extension. I created a program which opens a simple JFrame with a textarea. As it says in the documentation that native messaging communicates with stdin and stdout, I tried to get the message with:
while(true) {
try {
input=br.readLine();
tf.setAreaText(input);
} catch(Exception e) {
}
}
Also tried it with:
System.in.read()
The jar gets executed but the textarea stays empty. I can't find any information on the internet how to get the data in Java. Can you help me?
I haven't been able to get any native messaging to work in Google Chrome recently. I remember reading somewhere that a semi-recent update appeared to prevent compatibility between Java and Chrome for native messaging. Best of luck.
Related
Info about the project: I am creating a C++ console application that manages a Minecraft server by listening to port activity. When server port is pinged, it starts the server and then periodically checks if there are established connections on that port. If none, the server is shut down and app goes into listening mode once again.
The problem arises when the server is stopped. Somehow my main console app is getting killed by the child server process and I can't seem to find out how and why or any solutions to this.
My console app creates a new cmd.exe child process that runs a "java -jar server.jar" command when starting the server. When stopping the server a simple "stop" message is written to the standard input of the child process. This all works fine and the java server stops.
However as soon as the child process exits, the console app unexpectedly crashes and the Windows "Program has stopped working." dialog appears. The curious thing is that I have tested the application on my programming laptop that runs Windows 10 and it runs without any issues there both in release and debug mode. My server machine is running Windows 7 however, so it seems to somehow be a Windows 7 problem.
Now there's no code I can really show you since it's the java and cmd.exe child process performing the exit and I of course didn't code the server.jar file. But I will attach an image link of the console when it crashes just for fun.
The child process does not have a separate window, it inherits handles from the parent console app and writes to the parent's STDOUT so messages from the child show in the main app's console.
I have tried starting the child process with CREATE_NEW_PROCESS_GROUP flag, still crashes.
I have tried ignoring SIGINT and SIGTERM signals, still crashes.
I have also verified that the application doesn't start execution of the commands following the server shutdown call (writing stop message to stdin of server process) so they can't be the problem.
If anyone has any tips or ideas about what could be the issue I'm all ears. Thanks!
Console application crashes, Windows "Program has stopped working." dialog is not shown on picture.
EDIT:
Okay, so I created a minimal reproducible example. Here is all the needed code (for C++ main function):
//security attributes for pipes
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
//handles for child standard input/output
HANDLE child_stdin_rd = NULL;
HANDLE child_stdin_wr = NULL;
if (!CreatePipe(&child_stdin_rd, &child_stdin_wr, &saAttr, 0))
return -1;
if (!SetHandleInformation(child_stdin_wr, HANDLE_FLAG_INHERIT, 0))
return -1;
STARTUPINFOW startupInfo;
ZeroMemory(&startupInfo, sizeof(STARTUPINFOW));
startupInfo.cb = sizeof(STARTUPINFOW);
startupInfo.hStdInput = child_stdin_rd;
startupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
startupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
startupInfo.dwFlags |= STARTF_USESTDHANDLES;
PROCESS_INFORMATION processInfo;
ZeroMemory(&processInfo, sizeof(PROCESS_INFORMATION));
//cmd.exe path
wstring exepath = L"c:\\windows\\system32\\cmd.exe";
//cmd command to start server
wstring command = L"cmd.exe /c java -Xms1G -Xmx4G -jar server.jar nogui";
LPWSTR com = new wchar_t[command.size() + 1];
copy(command.begin(), command.end(), com);
com[command.size()] = 0;
if (!CreateProcessW(exepath.c_str(), com, 0, 0, TRUE, CREATE_NEW_PROCESS_GROUP, 0, 0, &startupInfo, &processInfo))
return -1;
//sleep for 1 min, letting server start up
this_thread::sleep_for(chrono::minutes(1));
//command to stop server
string stopCmd = "stop\n\0";
DWORD stopCmdByteSize = stopCmd.size() * sizeof(char);
if (!WriteFile(child_stdin_wr, stopCmd.c_str(), stopCmdByteSize, 0, 0))
return -1;
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
CloseHandle(child_stdin_wr);
To reproduce this, your machine would need to be running Windows 7 and in the same folder as the application must be a Minecraft server.jar file (version 1.15.2 at time of writing this) which you can get from their website. Also, the server might need some setting up first, running it for the first time by double-clicking .jar file creates all needed server files, you must open "eula.txt" and accept the EULA by changing eula=false to eula=true. Then the server should be good to go.
Like stated before, I didn't code the server.jar file and thus do not know the complete behavior of the java server program.
Bug found! Problem solved!
Ahh, after some vigorous thinking and reading the docs again to verify the code is correct I found the culprit.
In the call to the WriteFile() function I forgot to give it a pointer to a DWORD so that it can update the number of bytes the function has written.
So the following code:
if (!WriteFile(child_stdin_wr, stopCmd.c_str(), stopCmdByteSize, 0, 0))
return -1;
Needed to be changed to:
DWORD bytesWritten = 0;
if (!WriteFile(child_stdin_wr, stopCmd.c_str(), stopCmdByteSize, &bytesWritten, 0))
return -1;
So I guess it was a kind of undefined behavior that Windows 10 could handle but Windows 7 couldn't, resulting in the program crashing.. Kind of feel embarrassed for writing this lengthy post because of a small error in a function call, but there you have it folks! Thanks to those who gave tips! :)
You may have better luck using RCON, which is a protocol built into the Java edition server used to remotely manage a server with a simple TCP packet format, rather than trying to write commands to the standard input of the server directly.
See wiki.vg's page on RCON for an explanation on the packet format.
i built java application that get data from chrome extension and return data.
the chrome extension work perfect when my java app without this line:
scanner = Scanner.getDevice();
in this code:
ImageIO.scanForPlugins();
scanner = Scanner.getDevice();
scanner.addListener(this);
but when i not delete the line i got error on my background.js:
Error when communicating with the native messaging host
how can i debug the problem ?
the Scanner its:
uk.co.mmscomputing.device.scanner
library
tnx a lot.
I designed a chat application to support a store. The chat is very important for the store because it sells and trade items, so there's lot of communication. There's two end-points, the website that contains the chat as an icon and the help desk which is accessed through a web page.
I designed a chat using the socket.io library. The system is basically a web chat. I want to make an android application that will perform the help desk tasks. Using the the javascript library was a piece of cake but I am having trouble using a java package . I using Netbeans as IDE I created a project set up as java Maven. I am just testing out and afterwards I want to build an Android App as said before.
I wrote a code like this to try to connect. I add console.log on the server to check if it was connecting but nothing happens.
io.socket.client.Socket socket = IO.socket("https://example.com.br:3009");
JSONObject obj = new JSONObject();
obj.put("id", "null");
obj.put("nome", "android");
IO.Options ops = new IO.Options();
ops.secure = true;
ops.reconnection = true;
socket.on(io.socket.client.Socket.EVENT_CONNECT, new Emitter.Listener(){
#Override
public void call(Object... os) {
socket.emit("join", obj);
System.out.println("executou");
}
});
socket.connect();
What am I doing wrong?
It turned out that I had okhttp as a dependency and the version that was using 3.9.1 generates this issue. I changed it to 3.4.1 on pom.xml and it worked. I was getting exception on the Netbeans Window but I was ignoring it "okHttp3 java.lang.NoSuchMethodError: No virtual method setCallWebSocket". I thought it was a minor issue.
So I'm running the Google App Engine development server (Java) on localhost. I'm trying to retrieve a URL using Python 2.7 urllib.urlopen. The initial retrieve works, but then when I try to call read() or readlines() I get:
Traceback (most recent call last):
File "./getMap.py", line 6, in <module>
lst = f.readlines()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 513, in readlines
line = self.readline()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 445, in readline
data = self._sock.recv(self._rbufsize)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 552, in read
s = self.fp.read(amt)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 378, in read
data = self._sock.recv(left)
socket.error: [Errno 54] Connection reset by peer
The browser works, wget works. Problem occurs with both urllib and urllib2. Here's the code:
import urllib2
f = urllib2.urlopen("http://localhost:8080/default.jsp")
lst = f.readlines()
for a in lst:
print a
Strangely, I can print out the first line of the file using readline() -- I just can't get the whole file. I get the sense that maybe Python is "lazily" not requesting the entire contents of the URL until I request it via readlines(), and by then the app engine dev server has overzealously closed the connection. But I could be totally wrong about that.
I tried researching this problem but I didn't see anything applicable. Most of the Google hits I'm seeing surround random, intermittant timing issues (this isn't an intermittant problem, it's reliable) or proxy/firewall issues (nothing like that going on here).
Assuming my theory is correct -- is there a way to tell urlopen to get the whole response right away, as wget and the browser seem to be doing? Or is there a way to tell the GAE dev server to chill out and not close the connection so quickly? I'd rather not dive into lower-level python socket stuff if I don't have to.
thanks
p.s. clarification: the python script is just running from the command line and trying to make a connection to the GAE dev server, which is running on the same box. I'm NOT trying to connect to the GAE dev server from itself or something weird like that, the GAE server is running Java, not Python. What I'm actually trying to do here is this: my GAE web app has some web services and I'm writing a batch script to get/post to those webservices, so that when I need to reset/clear the data store (example: data gets corrupted) I can use this python script to back up the data first, then I erase the data store, and then use the script again to load that data back in.
UPDATE: so I tried a few more tests. Python has no trouble reading any HTML file served by the GAE dev server. However any JSP, even the simplest "hello world" JSP, fails to read with the same "connection reset by peer" error. I'll try updating to the 1.6.1 version of the GAE SDK, I have to do that anyway at some point, might as well be now. Hopefully it will fix this.
While I cannot see anything wrong with your python code and have no idea what might be wrong with your Java GAE setup I instead propose a different take on the problem.
You mention that you basically want to send GET/POST requests to your server and save/later read the content and that command line tools like wget works. I suggest you use a bash script and curl and python for the cases when you need to do more advanced text editing.
curl http://localhost:8080/default.jsp > default.bak
... wipe db ...
data = $(cat default.bak)
curl -X "POST" -d "backup=$data" http://localhost:8080/default_restore.jsp
If you need to edit the data before sending it you can use python to either read from default.bak or by piping it to stdin
data = $(cat default.bak)
python your_script.py $data
curl http://localhost:8080/default.jsp | python yourscript.py > default.bak
Obviously a bit late to the party, but I had exactly the same issue, and I solved it by swapping out urllib for httplib:
import httplib
conn = httplib.HTTPConnection('localhost:8080')
# get the current image and save to file
url = 'default.jsp'
conn.request("GET", url)
response = conn.getresponse()
if response.status == 404:
return None
img_file = open("out.jpg",'wb')
img_file.write(response.read())
img_file.close()
response.close()
conn.close()
I don't know why this works, I can only assume that httplib is slightly better behaved than urllib
We're writing a web application that is trying to replace all ReportManager functionality using calls to Reporting Services SOAP API.
We started working with SSRS 2008 and had our Java code working correctly. We've since had to downgrade to SSRS 2005 and now we're having problems connecting to the Server to get the list of reports available.
We make the following call:
catalog = _reportingService.listChildren(_reportCredentials.getFolder(), false);
which returns an exception - (401)Unauthorized
_reportCredentials just holds information from a properties file (like the folder to use, the username and password, etc.). _reportService is defined as:
private ReportingService2005Soap _reportingService;
...
_reportingServiceLocator = new ReportingService2005Locator();
_reportingServiceLocator.setReportingService2005SoapEndpointAddress(soapURL);
try {
_reportingService = _reportingServiceLocator.getReportingService2005Soap();
} catch (Exception e) {
throw new ReportServicesException("Could not retrieve SOAP Reporting Service.");
}
I can also connect to ReportManager as the user/password we're connecting with in the code.
All of the 'documentation' I can find is just .NET code that doesn't seem to apply to the Java code. Has anybody experienced problems like this, or know of a good resource for Java developers using these services?
We traced the problem back to having SSRS 2005 installed on Windows Server 2008. Following the steps here: http://www.omegaprojex.com/index.php/2008/10/10/ssrs-2005-on-windows-server-2008/ fixed our problem.