I have a question about php/java bridge. I have run it and I got prompt like this one
I want to set this for only run in http_local port 8080 and not show again the prompt choice?
I have a search in my php/javabridge I cannot get the location of class which call this prompt and set the http_local port 8080
how to set it? it is possible? if it is possible where is the code must I edit it?
after I check the code for a call this prompt is from standalone.java
public void init(final String[] s) {
String sockname = null;
int logLevel = -1;
final String tcpSocketName = "9267";
if (s.length > 3) {
this.checkOption(s);
}
try {
if (s.length > 0) {
sockname = s[0];
if (sockname.startsWith("-")) {
this.checkOption(s);
}
}
try {
if (s.length > 1) {
logLevel = Integer.parseInt(s[1]);
}
}
catch (NumberFormatException e2) {
this.usage();
}
catch (Throwable t) {
t.printStackTrace();
}
if (s.length == 0) {
try {
final int tcpSocket = Integer.parseInt(tcpSocketName);
final int freeJavaPort = findFreePort(tcpSocket);
final int freeHttpPort = findFreePort(8080);
final int freeHttpsPort = findFreePort(8443);
final Object result = JOptionPane.showInputDialog(null, "Start a socket listener on port", "Starting the PHP/Java Bridge ...", 3, null, new String[] { "INET_LOCAL:" + freeJavaPort, "INET:" + freeJavaPort, "HTTP_LOCAL:" + freeHttpPort, "HTTP:" + freeHttpPort, "HTTPS_LOCAL:" + freeHttpsPort, "HTTPS:" + freeHttpsPort }, "HTTP_LOCAL:" + freeHttpPort);
if (result == null) {
System.exit(0);
}
sockname = result.toString();
}
catch (Throwable t2) {}
}
if (s.length == 0) {
TCPServerSocket.TCP_PORT_BASE = Integer.parseInt(tcpSocketName);
}
if (checkServlet(logLevel, sockname, s)) {
return;
}
final ISocketFactory socket = bind(logLevel, sockname);
if ("true".equals(System.getProperty("php.java.bridge.test.startup"))) {
System.exit(0);
}
JavaBridge.initLog(String.valueOf(socket), logLevel, s);
JavaBridge.init(socket, logLevel, s);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
so this is possible to set only like this code for only run in http_local 8080? I use javabridge from maven
To make the port to be a static value and the prompt not to popup,you can make the below code change
if (s.length == 0) {
try {
final int tcpSocket = Integer.parseInt(tcpSocketName);
final int freeJavaPort = findFreePort(tcpSocket);
final int freeHttpPort = findFreePort(8080);
final int freeHttpsPort = findFreePort(8443);
//comment the JOptionPane to disable the dialog prompt
/*final Object result = JOptionPane.showInputDialog(null, "Start a socket listener on port", "Starting the PHP/Java Bridge ...", 3, null, new String[] { "INET_LOCAL:" + freeJavaPort, "INET:" + freeJavaPort, "HTTP_LOCAL:" + freeHttpPort, "HTTP:" + freeHttpPort, "HTTPS_LOCAL:" + freeHttpsPort, "HTTPS:" + freeHttpsPort }, "HTTP_LOCAL:" + freeHttpPort);
if (result == null) {
System.exit(0);
}*/
sockname = "8080"; //<--hardcode the sockname variable with the desired valid port value
}
catch (Throwable t2) {}
}
Related
i have problem when i use php java bridge i got error like this
Warning: require_once(http://localhost:8080/JavaBridge/java/Java.inc): failed to open stream: HTTP request failed! in /Library/WebServer/Documents/test2.php on line 3
Fatal error: require_once(): Failed opening required 'http://localhost:8080/JavaBridge/java/Java.inc' (include_path='.:') in /Library/WebServer/Documents/test2.php on line 3
my tomcat has running at port 8080. i use force to use port 8080 but i still got error
here my standalone class for java bridge
package php.java.bridge;
import php.java.bridge.util.Thread;
import java.lang.reflect.Method;
import php.java.bridge.http.JavaBridgeRunner;
import php.java.bridge.util.Logger;
import java.io.File;
import javax.swing.Icon;
import java.awt.Component;
import javax.swing.JOptionPane;
import java.net.ServerSocket;
import java.io.IOException;
import php.java.bridge.http.TCPServerSocket;
import php.java.bridge.http.ISocketFactory;
public class Standalone
{
public static final int HTTP_PORT_BASE = 8080;
public static final int HTTPS_PORT_BASE = 8443;
public static ISocketFactory bind(final int logLevel, final String sockname) throws IOException {
ISocketFactory socket = null;
socket = TCPServerSocket.create(sockname, 20);
if (null == socket) {
throw new IOException("Could not create socket: " + sockname);
}
return socket;
}
protected static void disclaimer() {
System.err.println("Copyright (C) 2003, 2006 Jost Boekemeier and others.");
System.err.println("This is free software; see the source for copying conditions. There is NO");
System.err.println("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.");
}
protected void javaUsage() {
System.err.println("PHP/Java Bridge version " + Util.VERSION);
disclaimer();
System.err.println("Usage: java -jar JavaBridge.jar [SOCKETNAME LOGLEVEL LOGFILE]");
System.err.println("SOCKETNAME is one of INET_LOCAL, INET, HTTP_LOCAL, HTTP, HTTPS_LOCAL, HTTPS");
System.err.println("");
System.err.println("Example 1: java -jar JavaBridge.jar");
System.err.println("Example 2: java -jar JavaBridge.jar HTTP_LOCAL:8080 3 JavaBridge.log");
System.err.println("Example 3: java -Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=YOURPASSWD -jar JavaBridge.jar HTTPS:8443 3 JavaBridge.log");
System.err.println("The certificate for example 3 can be created with e.g.: jdk1.6.0/bin/keytool -keystore mySrvKeystore -genkey -keyalg RSA");
System.err.println("");
System.err.println("Influential system properties: threads, daemon, php_exec, default_log_file, default_log_level, base.");
System.err.println("Example: java -Djava.awt.headless=\"true\" -Dphp.java.bridge.threads=50 -Dphp.java.bridge.base=/usr/lib/php/modules -Dphp.java.bridge.php_exec=/usr/local/bin/php-cgi -Dphp.java.bridge.default_log_file= -Dphp.java.bridge.default_log_level=5 -jar JavaBridge.jar");
System.err.println("Example: java -Dphp.java.bridge.daemon=\"true\" -jar JavaBridge.jar");
}
protected void usage() {
this.javaUsage();
System.exit(1);
}
protected void checkOption(final String[] s) {
if ("--version".equals(s[0])) {
System.out.println(Util.VERSION);
System.exit(0);
}
this.usage();
}
private static boolean testPort(final int port) {
try {
final ServerSocket sock = new ServerSocket(port);
sock.close();
return true;
}
catch (IOException ex) {
return false;
}
}
private static int findFreePort(final int start) {
for (int port = start; port < start + 100; ++port) {
if (testPort(port)) {
return port;
}
}
return start;
}
public void init(final String[] s) {
String sockname = null;
int logLevel = -1;
// final String tcpSocketName = "9267";
final String tcpSocketName = "8080";
if (s.length > 3) {
this.checkOption(s);
}
try {
if (s.length > 0) {
sockname = s[0];
if (sockname.startsWith("-")) {
this.checkOption(s);
}
}
try {
if (s.length > 1) {
logLevel = Integer.parseInt(s[1]);
}
}
catch (NumberFormatException e2) {
this.usage();
}
catch (Throwable t) {
t.printStackTrace();
}
if (s.length == 0) {
try {
/* final int tcpSocket = Integer.parseInt(tcpSocketName);
final int freeJavaPort = findFreePort(tcpSocket);
final int freeHttpPort = findFreePort(8080);
final int freeHttpsPort = findFreePort(8443);
final Object result = JOptionPane.showInputDialog(null, "Start a socket listener on port", "Starting the PHP/Java Bridge ...", 3, null, new String[] { "INET_LOCAL:" + freeJavaPort, "INET:" + freeJavaPort, "HTTP_LOCAL:" + freeHttpPort, "HTTP:" + freeHttpPort, "HTTPS_LOCAL:" + freeHttpsPort, "HTTPS:" + freeHttpsPort }, "HTTP_LOCAL:" + freeHttpPort);
//final Object result = 8080;
if (result == null) {
System.exit(0);
}*/
//sockname = result.toString();
sockname = "8080";
}
catch (Throwable t2) {}
}
if (s.length == 0) {
TCPServerSocket.TCP_PORT_BASE = Integer.parseInt(tcpSocketName);
}
if (checkServlet(logLevel, sockname, s)) {
return;
}
final ISocketFactory socket = bind(logLevel, sockname);
if ("true".equals(System.getProperty("php.java.bridge.test.startup"))) {
System.exit(0);
}
JavaBridge.initLog(String.valueOf(socket), logLevel, s);
JavaBridge.init(socket, logLevel, s);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
public static File getCanonicalWindowsFile(final String path) {
try {
return new File(path).getCanonicalFile();
}
catch (IOException e) {
return new File(path);
}
}
private static boolean checkServlet(final int logLevel, String sockname, final String[] s) throws InterruptedException, IOException {
if (sockname == null) {
return false;
}
if (sockname.startsWith("SERVLET_LOCAL:") || sockname.startsWith("HTTP_LOCAL:") || sockname.startsWith("HTTPS_LOCAL:")) {
Util.JAVABRIDGE_PROMISCUOUS = false;
System.setProperty("php.java.bridge.promiscuous", "false");
}
else {
if (!sockname.startsWith("SERVLET:") && !sockname.startsWith("HTTP:") && !sockname.startsWith("HTTPS:")) {
return false;
}
Util.JAVABRIDGE_PROMISCUOUS = true;
System.setProperty("php.java.bridge.promiscuous", "true");
}
final boolean isSecure = sockname.startsWith("HTTPS");
JavaBridge.initLog(sockname, logLevel, s);
sockname = sockname.substring(sockname.indexOf(58) + 1);
final String serverPort = (Util.JAVABRIDGE_PROMISCUOUS ? "INET:" : "INET_LOCAL:") + sockname;
Logger.logMessage("JavaBridgeRunner started on port " + serverPort);
Class runner = JavaBridgeRunner.class;
JavaBridgeRunner r;
try {
runner = Util.classForName("php.java.script.JavaBridgeScriptRunner");
final Method m = runner.getMethod("getRequiredInstance", String.class, Boolean.TYPE);
r = (JavaBridgeRunner)m.invoke(runner, serverPort, new Boolean(isSecure));
}
catch (Throwable e) {
r = JavaBridgeRunner.getRequiredInstance(serverPort, isSecure);
}
r.waitFor();
r.destroy();
return true;
}
private static final boolean checkGNUVM() {
try {
return "libgcj".equals(System.getProperty("gnu.classpath.vm.shortname"));
}
catch (Throwable t) {
return false;
}
}
public static void main(final String[] s) {
if (!System.getProperty("php.java.bridge.daemon", "false").equals("false")) {
final String[] args = new String[s.length + 8];
args[0] = System.getProperty("php.java.bridge.daemon");
if ("true".equals(args[0])) {
args[0] = "java";
}
args[1] = "-Djava.library.path=" + System.getProperty("java.library.path", ".");
args[2] = "-Djava.ext.dirs=" + System.getProperty("java.ext.dirs", ".");
args[3] = "-Djava.awt.headless=" + System.getProperty("java.awt.headless", "true");
args[4] = "-Dphp.java.bridge.asDaemon=true";
args[5] = "-classpath";
args[6] = System.getProperty("java.class.path", ".");
args[7] = "php.java.bridge.Standalone";
for (int j = 0; j < s.length; ++j) {
args[j + 8] = s[j];
}
try {
System.in.close();
System.out.close();
System.err.close();
}
catch (IOException e) {
System.exit(12);
}
new Thread(new Runnable() {
#Override
public void run() {
try {
Runtime.getRuntime().exec(args);
}
catch (IOException e) {
System.exit(13);
}
}
}).start();
try {
java.lang.Thread.sleep(20000L);
}
catch (Throwable t2) {}
System.exit(0);
}
try {
System.loadLibrary("natcJavaBridge");
}
catch (Throwable t3) {}
try {
final String cp = System.getProperty("java.class.path", ".");
File jbFile = null;
final boolean isExecutableJavaBridgeJar = cp.indexOf(File.pathSeparatorChar) == -1 && cp.endsWith("JavaBridge.jar") && (jbFile = new File(cp)).isAbsolute();
final File wd = getCanonicalWindowsFile(isExecutableJavaBridgeJar ? jbFile.getParent() : "");
final boolean sunJavaInstalled = new File("/usr/java/default/bin/java").exists();
final String javaExec = sunJavaInstalled ? "/usr/java/default/bin/java" : "java";
if (s.length == 0 && System.getProperty("php.java.bridge.exec_sun_vm", "true").equals("true") && ((sunJavaInstalled && checkGNUVM()) || isExecutableJavaBridgeJar)) {
final Process p = Runtime.getRuntime().exec(new String[] { javaExec, "-Dphp.java.bridge.exec_sun_vm=false", "-classpath", cp, "php.java.bridge.Standalone" }, null, wd);
if (p != null) {
System.exit(p.waitFor());
}
}
}
catch (Throwable t4) {}
try {
new Standalone().init(s);
}
catch (Throwable t) {
t.printStackTrace();
System.exit(9);
}
}
}
in this source code i force manual choice 8080 using this code
/* final int tcpSocket = Integer.parseInt(tcpSocketName);
final int freeJavaPort = findFreePort(tcpSocket);
final int freeHttpPort = findFreePort(8080);
final int freeHttpsPort = findFreePort(8443);
final Object result = JOptionPane.showInputDialog(null, "Start a socket listener on port", "Starting the PHP/Java Bridge ...", 3, null, new String[] { "INET_LOCAL:" + freeJavaPort, "INET:" + freeJavaPort, "HTTP_LOCAL:" + freeHttpPort, "HTTP:" + freeHttpPort, "HTTPS_LOCAL:" + freeHttpsPort, "HTTPS:" + freeHttpsPort }, "HTTP_LOCAL:" + freeHttpPort);
//final Object result = 8080;
if (result == null) {
System.exit(0);
}*/
//sockname = result.toString();
sockname = "8080";
}
and at tcpServer i force to choice that port use this code
import java.net.Socket;
import java.net.UnknownHostException;
import java.net.InetAddress;
import java.io.IOException;
import java.net.ServerSocket;
public class TCPServerSocket implements ISocketFactory
{
public static int TCP_PORT_BASE;
private ServerSocket sock;
private int port;
boolean local;
public static ISocketFactory create(String name, final int backlog) throws IOException {
boolean local = false;
if (name == null) {
throw new NullPointerException("name");
}
if (name.startsWith("INET:")) {
name = name.substring(5);
}
else if (name.startsWith("INET_LOCAL:")) {
local = true;
name = name.substring(11);
}
final int p = Integer.parseInt(name);
final TCPServerSocket s = new TCPServerSocket(p, backlog, local);
return s;
}
private ServerSocket newServerSocket(final int port, final int backlog) throws IOException {
try {
if (this.local) {
return new ServerSocket(port, backlog, InetAddress.getByName("127.0.0.1"));
}
}
catch (UnknownHostException ex) {}
return new ServerSocket(port, backlog);
}
private void findFreePort(final int start, final int backlog) {
int port = start;
while (port < start + 100) {
try {
this.sock = this.newServerSocket(port, backlog);
this.port = port;
return;
}
catch (IOException e) {
++port;
continue;
}
}
}
private TCPServerSocket(final int port, final int backlog, final boolean local) throws IOException {
this.local = local;
if (port == 0) {
this.findFreePort(TCPServerSocket.TCP_PORT_BASE, backlog);
}
else {
this.sock = this.newServerSocket(port, backlog);
this.port = port;
}
}
#Override
public void close() throws IOException {
this.sock.close();
}
#Override
public Socket accept() throws IOException {
final Socket s = this.sock.accept();
s.setTcpNoDelay(true);
return s;
}
#Override
public String getSocketName() {
return String.valueOf(this.port);
}
#Override
public String toString() {
return (this.local ? "INET_LOCAL:" : "INET:") + this.getSocketName();
}
static {
// TCPServerSocket.TCP_PORT_BASE = 9267;
TCPServerSocket.TCP_PORT_BASE = 8080;
}
}
but my javabridge cannot open stream at that port why like that ? any idea for choice only port 8080 not choice the other ?
this problem close after i change this code
try { /*
final int tcpSocket = Integer.parseInt(tcpSocketName);
final int freeJavaPort = findFreePort(tcpSocket);
final int freeHttpPort = findFreePort(8080);
final int freeHttpsPort = findFreePort(8443);
final Object result = JOptionPane.showInputDialog(null, "Start a socket listener on port", "Starting the PHP/Java Bridge ...", 3, null, new String[] { "INET_LOCAL:" + freeJavaPort, "INET:" + freeJavaPort, "HTTP_LOCAL:" + freeHttpPort, "HTTP:" + freeHttpPort, "HTTPS_LOCAL:" + freeHttpsPort, "HTTPS:" + freeHttpsPort }, "HTTP_LOCAL:" + freeHttpPort);
//final Object result = 8080;
if (result == null) {
System.exit(0);
}*/
//sockname = result.toString();
sockname = "HTTP_LOCAL:8080";
System.out.println("sockname"+sockname);
}
so sockname use "HTTP_LOCAL:8080" not "8080"
I want to know some of the reasons that can cause below exception. I am unable to find this message Cannot find message in jsch-0.1.54.jar. There exists some straight forward messages like file not found and others that make sense. But I need more information about this one so that I can reach to the root cause.
SftpException while running get ---> 2: Cannot find message [/destination/file.txt]
at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2289)
at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:1741)
at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:1758)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:786)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:750)
at com.iyi.ftp.SFTP.get(SFTP.java:99)
Here is my calling method.
public boolean get(final String remoteFile, final String localFile) throws JSchException {
Vector connection = null;
Session session = null;
ChannelSftp c = null;
boolean status = false;
try {
connection = this.connect();
session = connection.get(0);
c = connection.get(1);
c.get(remoteFile, localFile);
status = true;
}
catch (JSchException e) {
SFTP.LGR.warn((Object)("JSchException in SFTP::get() ---> " + FTPFactory.getStackTrace((Throwable)e)));
throw e;
}
catch (SftpException e2) {
SFTP.LGR.warn((Object)("SftpException while running get ---> " + FTPFactory.getStackTrace((Throwable)e2)));
throw new JSchException(e2.getMessage());
}
catch (CredentialDecryptionException e3) {
SFTP.LGR.error((Object)"##CredentialDecryptionException##", (Throwable)e3);
throw new JSchException(e3.getMessage(), (Throwable)e3);
}
finally {
if (c != null) {
c.quit();
}
if (session != null) {
session.disconnect();
}
}
if (c != null) {
c.quit();
}
if (session != null) {
session.disconnect();
}
return status;
}
These methods are fetched from jsch-0.1.54.jar which is an open source utility.
public void get(String src, String dst, final SftpProgressMonitor monitor, final int mode) throws SftpException {
boolean _dstExist = false;
String _dst = null;
try {
((MyPipedInputStream)this.io_in).updateReadSide();
src = this.remoteAbsolutePath(src);
dst = this.localAbsolutePath(dst);
final Vector v = this.glob_remote(src);
final int vsize = v.size();
if (vsize == 0) {
throw new SftpException(2, "No such file");
}
final File dstFile = new File(dst);
final boolean isDstDir = dstFile.isDirectory();
StringBuffer dstsb = null;
if (isDstDir) {
if (!dst.endsWith(ChannelSftp.file_separator)) {
dst += ChannelSftp.file_separator;
}
dstsb = new StringBuffer(dst);
}
else if (vsize > 1) {
throw new SftpException(4, "Copying multiple files, but destination is missing or a file.");
}
for (int j = 0; j < vsize; ++j) {
final String _src = v.elementAt(j);
final SftpATTRS attr = this._stat(_src);
if (attr.isDir()) {
throw new SftpException(4, "not supported to get directory " + _src);
}
_dst = null;
if (isDstDir) {
final int i = _src.lastIndexOf(47);
if (i == -1) {
dstsb.append(_src);
}
else {
dstsb.append(_src.substring(i + 1));
}
_dst = dstsb.toString();
if (_dst.indexOf("..") != -1) {
final String dstc = new File(dst).getCanonicalPath();
final String _dstc = new File(_dst).getCanonicalPath();
if (_dstc.length() <= dstc.length() || !_dstc.substring(0, dstc.length() + 1).equals(dstc + ChannelSftp.file_separator)) {
throw new SftpException(4, "writing to an unexpected file " + _src);
}
}
dstsb.delete(dst.length(), _dst.length());
}
else {
_dst = dst;
}
final File _dstFile = new File(_dst);
if (mode == 1) {
final long size_of_src = attr.getSize();
final long size_of_dst = _dstFile.length();
if (size_of_dst > size_of_src) {
throw new SftpException(4, "failed to resume for " + _dst);
}
if (size_of_dst == size_of_src) {
return;
}
}
if (monitor != null) {
monitor.init(1, _src, _dst, attr.getSize());
if (mode == 1) {
monitor.count(_dstFile.length());
}
}
FileOutputStream fos = null;
_dstExist = _dstFile.exists();
try {
if (mode == 0) {
fos = new FileOutputStream(_dst);
}
else {
fos = new FileOutputStream(_dst, true);
}
this._get(_src, fos, monitor, mode, new File(_dst).length());
}
finally {
if (fos != null) {
fos.close();
}
}
}
}
catch (Exception e) {
if (!_dstExist && _dst != null) {
final File _dstFile2 = new File(_dst);
if (_dstFile2.exists() && _dstFile2.length() == 0L) {
_dstFile2.delete();
}
}
if (e instanceof SftpException) {
throw (SftpException)e;
}
if (e instanceof Throwable) {
throw new SftpException(4, "", e);
}
throw new SftpException(4, "");
}
}
private SftpATTRS _stat(final byte[] path) throws SftpException {
try {
this.sendSTAT(path);
Header header = new Header();
header = this.header(this.buf, header);
final int length = header.length;
final int type = header.type;
this.fill(this.buf, length);
if (type != 105) {
if (type == 101) {
final int i = this.buf.getInt();
this.throwStatusError(this.buf, i);
}
throw new SftpException(4, "");
}
final SftpATTRS attr = SftpATTRS.getATTR(this.buf);
return attr;
}
catch (Exception e) {
if (e instanceof SftpException) {
throw (SftpException)e;
}
if (e instanceof Throwable) {
throw new SftpException(4, "", e);
}
throw new SftpException(4, "");
}
}
The error message comes from your server. It's indeed quite strange message, but I assume that it's some custom SFTP server that deals with some "messages" rather than plain files.
So the message basically translates to "Cannot find file" error of a traditional SFTP server. Even the error code 2 (SSH_FX_NO_SUCH_FILE) supports that.
Your path in remoteFile is probably wrong.
I'm using a java server to facilitate online multiplayer in my game made with GameMaker Studio, the players will send data to the java server which will process the data and send it to the players. The problem is that when a player with a slow internet connection is not being able to handle the amount of data being send to it, it will cause the server to freeze for all players (the server will no longer process any data send by other players).
I have simulated slow internet speeds by using NetLimiter and setting the download speed of one laptop at 5 kb/s, while maintaining proper speed at other laptops. I have tried to send ACK packets from the java server to the client and if it doesn't respond in 1 second no more data will be send to that client (and eventually the client will be kicked). This has reduced the chance of freezing the server, but it will still happen occasionally.
Main.java
import java.net.Socket;
import java.net.SocketAddress;
import java.net.InetSocketAddress;
import java.io.IOException;
import java.util.HashMap;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
public class Main
{
static ServerSocket serverSocket_;
static HashMap<String, ServerInformation> servers_;
static int verboseLevel_;
static int threadTimeout_;
static int masterPort_;
static int serverNumber_;
static int socketTimeOut_;
static {
Main.serverSocket_ = null;
Main.servers_ = new HashMap<String, ServerInformation>();
Main.verboseLevel_ = 5;
Main.threadTimeout_ = 10;
Main.masterPort_ = 6510;
Main.serverNumber_ = 1;
Main.socketTimeOut_ = 6000;
}
public static void main(final String[] args) {
try {
setupServerAndCleanup(Main.masterPort_);
while (true) {
handleIncomingConnection();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
static void setupServerAndCleanup(final int port) throws IOException {
(Main.serverSocket_ = new ServerSocket()).setReuseAddress(true);
Main.serverSocket_.bind(new InetSocketAddress(Main.masterPort_));
System.out.println("Server socket up and running on port " + Main.masterPort_);
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
#Override
public void run() {
if (Main.serverSocket_ != null) {
try {
Main.serverSocket_.close();
System.out.println("Server socket closed, port released");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}));
}
static void handleIncomingConnection() throws IOException {
final Socket clientSocket = Main.serverSocket_.accept();
clientSocket.setSoTimeout(Main.socketTimeOut_);
final ClientThread client = new ClientThread(clientSocket);
client.start();
}
}
ClientThread.java
Case 1 is the part dealing with sending data to the clients, in particular this line:
thread2.out_.print(msg);
If more data is being send than one client can handle the server will freeze for all other clients as well.
import java.util.Iterator;
import java.io.IOException;
import java.io.Reader;
import java.io.InputStreamReader;
import java.util.regex.Pattern;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class ClientThread extends Thread
{
Socket clientSocket_;
String clientIp_;
String serverIp_;
ServerInformation server_;
PrintWriter out_;
BufferedReader in_;
boolean prepareTermination_;
boolean terminated_;
private static final Pattern numberPattern;
static {
numberPattern = Pattern.compile("\\d+");
}
public ClientThread(final Socket sock) {
this.clientSocket_ = sock;
this.clientIp_ = this.clientSocket_.getRemoteSocketAddress().toString();
this.serverIp_ = null;
this.server_ = null;
this.prepareTermination_ = false;
this.terminated_ = false;
}
#Override
public void run() {
try {
this.out_ = new PrintWriter(this.clientSocket_.getOutputStream(), true);
this.in_ = new BufferedReader(new InputStreamReader(this.clientSocket_.getInputStream()));
long lastActionTime = System.currentTimeMillis();
while (true) {
if (this.in_.ready() || System.currentTimeMillis() - lastActionTime >= 1000 * Main.threadTimeout_) {
if (System.currentTimeMillis() - lastActionTime >= 1000 * Main.threadTimeout_) {
//this.logDebugMessage(3, "Thread was killed due to prolonged inactivity (" + Main.threadTimeout_ + " seconds)");
this.terminateThread();
return;
}
final String tempInputLine;
if(((tempInputLine = this.in_.readLine()) == null )){
this.terminateThread(); //end thread
return;
}
else
{
lastActionTime = System.currentTimeMillis();
final String inputLine = tempInputLine.trim();
if (ClientThread.numberPattern.matcher(inputLine).matches()){
final int val = Integer.parseInt(inputLine);
switch (val) {
case 1: { //send data to other players
final int parseCount = Integer.parseInt(this.in_.readLine().trim());
final StringBuilder msg = new StringBuilder();
for (int j = 0; j < parseCount; ++j) {
msg.append(String.valueOf(this.in_.readLine().trim()) + "|");
}
for (final ClientThread thread2 : this.server_.ipToClientThread_.values()) {
if (thread2 != this) {
thread2.out_.print(msg);
thread2.out_.flush();
}
}
//this.logDebugMessage(5, "Packet for others: '" + msg.toString() + "'");
break;
}
case 2: { //remove game server
//this.logDebugMessage(1, "A game server has been deleted, ip: " + ipServer);
Main.servers_.remove(this.server_.ip_);
this.serverIp_ = null;
for (final ClientThread thread : this.server_.ipToClientThread_.values()) {
thread.prepareTermination_ = true;
}
this.terminateThread();
return;
}
case 3: { //connect new client
final String ipServer = this.in_.readLine().trim();
final String ipClient = this.in_.readLine().trim();
this.logDebugMessage(1, "A client wishes to connect to a server, client: " + ipClient + ", server: " + ipServer);
final ServerInformation info = Main.servers_.getOrDefault(ipServer, null);
if (info == null) {
System.out.println("Connection to the server failed, no such server in the server list");
this.out_.print("*" + 1 + "|" + 1 + "~" + "|");
this.out_.flush();
break;
}
this.server_ = info;
this.server_.ipToClientThread_.put(ipClient, this);
this.logDebugMessage(1, "Connection success");
this.logDebugMessage(5,"Map: " + this.server_.ipToClientThread_);
this.out_.print("*" + 1 + "|" + 2 + "~" + "|");
this.out_.flush();
break;
}
case 4: { //disconnect client
final String ipClient = this.in_.readLine().trim();
this.server_.ipToClientThread_.remove(ipClient);
this.logDebugMessage(1, String.valueOf(ipClient) + " disconnected from the server at " + this.server_.ip_);
this.serverIp_ = null;
this.terminateThread();
return;
}
case 5: { //host create new game
if (Main.serverNumber_ > 1000000) {
Main.serverNumber_ = 10;
}
Main.serverNumber_ += 1;
final String ipServer = Integer.toString(Main.serverNumber_); //unique server number
final String ipHost = this.in_.readLine().trim(); //host
final String name = this.in_.readLine().trim(); //Server name
final String description = this.in_.readLine().trim(); //class
final String servervar1 = this.in_.readLine().trim(); //max players
final String servervar3 = this.in_.readLine().trim(); //current lap
final String servervar4 = this.in_.readLine().trim(); //total laps
final String servervar5 = this.in_.readLine().trim(); //status
final String servervar6 = this.in_.readLine().trim(); //Password
final String servervar7 = this.in_.readLine().trim(); //Online version
final String servervar8 = this.in_.readLine().trim(); //Game server
final long servervar9 = System.currentTimeMillis(); //server creation time
//this.logDebugMessage(1, "A game server has been registered, ip: " + ipServer + ", name: " + name + ", description: " + description + ", servervar1: " + servervar1);
final ServerInformation gameServer = new ServerInformation(name, servervar1, servervar3, servervar4, servervar5, servervar6, servervar7, servervar8, servervar9, ipHost, ipServer, this.clientSocket_, this.out_, this.in_);
gameServer.description_ = description;
gameServer.ipToClientThread_.put(ipHost, this);
this.server_ = gameServer;
Main.servers_.put(ipServer, gameServer);
this.serverIp_ = ipServer;
break;
}
default: {
this.logDebugMessage(0, "Unrecognized case: '" + inputLine + "', " + val);
break;
}
}
}
else if (inputLine.length() > 0) {
this.logDebugMessage(0, "Unformated '" + inputLine + "'");
if (this.server_ != null) {
this.server_.out_.print(inputLine);
this.server_.out_.flush();
}
}
if (this.prepareTermination_) {
this.terminateThread();
return;
}
continue;
}
}
}
}
catch (SocketTimeoutException e) {
e.printStackTrace();
try {
this.terminateThread();
}
catch (IOException e2) {
e2.printStackTrace();
}
}
catch (IOException e3) {
e3.printStackTrace();
try {
this.terminateThread();
}
catch (IOException e4) {
e4.printStackTrace();
}
}
}
//debug messages
void logDebugMessage(final int requiredVerbose, final String msg) {
if (Main.verboseLevel_ >= requiredVerbose) {
System.out.println("[" + this.clientIp_ + "] " + msg);
}
}
//terminate thread
void terminateThread() throws IOException {
if (!this.terminated_) {
if (this.serverIp_ != null) {
Main.servers_.remove(this.serverIp_);
}
this.clientSocket_.close();
this.in_.close();
this.out_.close();
this.logDebugMessage(3, "Cleanup successful");
this.terminated_ = true;
}
}
}
How to avoid the server from freezing if more data is being send to a client than it can handle, so that the server can continue sending data to the other clients?
Edit
So I have tried using ExecutorService, but I must be doing something completely wrong because no data is being send by the java server.
for (final ClientThread thread2 : this.server_.ipToClientThread_.values()) {
if (thread2 != this) {
executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
public void run() {
thread2.out_.print(msg);
thread2.out_.flush();
}
});
executorService.shutdown();
}
}
It would be great if you could show me how to implement ExecutorService the right way.
If a delay in the client processing doesn't matter, this part should be done in a distinct flow execution for each client :
for (final ClientThread thread2 : this.server_.ipToClientThread_.values()) {
thread2.out_.print(msg);
thread2.out_.flush();
}
For example :
for (final ClientThread thread2 : this.server_.ipToClientThread_.values()) {
if (thread2 != this) {
new Thread(()-> {
thread2.out_.print(msg);
thread2.out_.flush();
})
.start();
}
}
Note that creating Threads has a cost. Using ExecutorService could be a better idea.
5 with jdk1.8 when I run the project. I got an Exception ExceptionInInitializerError. But when I run the same project in jdk1.6. It is running successfully. That error message as
Exception in thread "main" java.lang.ExceptionInInitializerError
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at java.lang.Class.newInstance(Class.java:442)
at org.ofbiz.entity.GenericDelegator.initEntityEcaHandler(GenericDelegator.java:339)
at org.ofbiz.entity.DelegatorFactory.getDelegator(DelegatorFactory.java:42)
at org.ofbiz.catalina.container.CatalinaContainer.init(CatalinaContainer.java:175)
at org.ofbiz.base.container.ContainerLoader.loadContainer(ContainerLoader.java:189)
at org.ofbiz.base.container.ContainerLoader.load(ContainerLoader.java:66)
at org.ofbiz.base.start.Start.initStartLoaders(Start.java:260)
at org.ofbiz.base.start.Start.init(Start.java:97)
at org.ofbiz.base.start.Start.main(Start.java:411)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 5747
at org.codehaus.aspectwerkz.org.objectweb.asm.ClassReader.readClass(Unknown Source)
at org.codehaus.aspectwerkz.org.objectweb.asm.ClassReader.accept(Unknown Source)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getClassInfo(AsmClassInfo.java:308)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getClassInfo(AsmClassInfo.java:331)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.createClassInfoFromStream(AsmClassInfo.java:790)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getClassInfo(AsmClassInfo.java:273)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getInterfaces(AsmClassInfo.java:619)
at org.codehaus.aspectwerkz.reflect.ClassInfoHelper.implementsInterface(ClassInfoHelper.java:56)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.collectCustomProceedMethods(AbstractJoinPointCompiler.java:237)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.collectCustomProceedMethods(AbstractJoinPointCompiler.java:208)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.initialize(AbstractJoinPointCompiler.java:149)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.(AbstractJoinPointCompiler.java:133)
at org.codehaus.aspectwerkz.transform.inlining.compiler.MethodExecutionJoinPointCompiler.(MethodExecutionJoinPointCompiler.java:33)
at org.codehaus.aspectwerkz.transform.inlining.compiler.JoinPointFactory.compileJoinPoint(JoinPointFactory.java:86)
at org.codehaus.aspectwerkz.joinpoint.management.JoinPointManager$CompiledJoinPoint.(JoinPointManager.java:262)
at org.codehaus.aspectwerkz.joinpoint.management.JoinPointManager.compileJoinPoint(JoinPointManager.java:251)
at org.codehaus.aspectwerkz.joinpoint.management.JoinPointManager.loadJoinPoint(JoinPointManager.java:118)
at org.ofbiz.entityext.eca.DelegatorEcaHandler.aw$initJoinPoints(DelegatorEcaHandler.java)
at org.ofbiz.entityext.eca.DelegatorEcaHandler.(DelegatorEcaHandler.java)
... 13 more"
I found two files are problem when I run the project in jdk1.8 that coding files are:
CatalinaContainer.java
/**
* CatalinaContainer - Tomcat 5
*
*/
public class CatalinaContainer implements Container {
public static final String CATALINA_HOSTS_HOME = System.getProperty("ofbiz.home") + "/framework/catalina/hosts";
public static final String J2EE_SERVER = "OFBiz Container 3.1";
public static final String J2EE_APP = "OFBiz";
public static final String module = CatalinaContainer.class.getName();
protected static Map<String, String> mimeTypes = new HashMap<String, String>();
// load the JSSE propertes (set the trust store)
static {
SSLUtil.loadJsseProperties();
}
protected Delegator delegator = null;
protected Embedded embedded = null;
protected Map<String, ContainerConfig.Container.Property> clusterConfig = new HashMap<String, ContainerConfig.Container.Property>();
protected Map<String, Engine> engines = new HashMap<String, Engine>();
protected Map<String, Host> hosts = new HashMap<String, Host>();
protected boolean contextReloadable = false;
protected boolean crossContext = false;
protected boolean distribute = false;
protected boolean enableDefaultMimeTypes = true;
protected String catalinaRuntimeHome;
/**
* #see org.ofbiz.base.container.Container#init(java.lang.String[], java.lang.String)
*/
public void init(String[] args, String configFile) throws ContainerException {
// get the container config
ContainerConfig.Container cc = ContainerConfig.getContainer("catalina-container", configFile);
if (cc == null) {
throw new ContainerException("No catalina-container configuration found in container config!");
}
// embedded properties
boolean useNaming = ContainerConfig.getPropertyValue(cc, "use-naming", false);
//int debug = ContainerConfig.getPropertyValue(cc, "debug", 0);
// grab some global context settings
this.delegator = DelegatorFactory.getDelegator(ContainerConfig.getPropertyValue(cc, "delegator-name", "default"));
this.contextReloadable = ContainerConfig.getPropertyValue(cc, "apps-context-reloadable", false);
this.crossContext = ContainerConfig.getPropertyValue(cc, "apps-cross-context", true);
this.distribute = ContainerConfig.getPropertyValue(cc, "apps-distributable", true);
this.catalinaRuntimeHome = ContainerConfig.getPropertyValue(cc, "catalina-runtime-home", "runtime/catalina");
// set catalina_home
System.setProperty("catalina.home", System.getProperty("ofbiz.home") + "/" + this.catalinaRuntimeHome);
// configure JNDI in the StandardServer
StandardServer server = (StandardServer) ServerFactory.getServer();
try {
server.setGlobalNamingContext(new InitialContext());
} catch (NamingException e) {
throw new ContainerException(e);
}
// create the instance of Embedded
embedded = new Embedded();
embedded.setUseNaming(useNaming);
// create the engines
List<ContainerConfig.Container.Property> engineProps = cc.getPropertiesWithValue("engine");
if (UtilValidate.isEmpty(engineProps)) {
throw new ContainerException("Cannot load CatalinaContainer; no engines defined!");
}
for (ContainerConfig.Container.Property engineProp: engineProps) {
createEngine(engineProp);
}
// load the web applications
loadComponents();
// create the connectors
List<ContainerConfig.Container.Property> connectorProps = cc.getPropertiesWithValue("connector");
if (UtilValidate.isEmpty(connectorProps)) {
throw new ContainerException("Cannot load CatalinaContainer; no connectors defined!");
}
for (ContainerConfig.Container.Property connectorProp: connectorProps) {
createConnector(connectorProp);
}
try {
embedded.initialize();
} catch (LifecycleException e) {
throw new ContainerException(e);
}
}
public boolean start() throws ContainerException {
// Start the embedded server
try {
embedded.start();
} catch (LifecycleException e) {
throw new ContainerException(e);
}
for (Connector con: embedded.findConnectors()) {
ProtocolHandler ph = con.getProtocolHandler();
if (ph instanceof Http11Protocol) {
Http11Protocol hph = (Http11Protocol) ph;
Debug.logInfo("Connector " + hph.getProtocols() + " # " + hph.getPort() + " - " +
(hph.getSecure() ? "secure" : "not-secure") + " [" + con.getProtocolHandlerClassName() + "] started.", module);
} else {
Debug.logInfo("Connector " + con.getProtocol() + " # " + con.getPort() + " - " +
(con.getSecure() ? "secure" : "not-secure") + " [" + con.getProtocolHandlerClassName() + "] started.", module);
}
}
Debug.logInfo("Started " + ServerInfo.getServerInfo(), module);
return true;
}
protected Engine createEngine(ContainerConfig.Container.Property engineConfig) throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot create Engine without Embedded instance!");
}
ContainerConfig.Container.Property defaultHostProp = engineConfig.getProperty("default-host");
if (defaultHostProp == null) {
throw new ContainerException("default-host element of server property is required for catalina!");
}
String engineName = engineConfig.name;
String hostName = defaultHostProp.value;
StandardEngine engine = (StandardEngine) embedded.createEngine();
engine.setName(engineName);
engine.setDefaultHost(hostName);
// set the JVM Route property (JK/JK2)
String jvmRoute = ContainerConfig.getPropertyValue(engineConfig, "jvm-route", null);
if (jvmRoute != null) {
engine.setJvmRoute(jvmRoute);
}
// create the default realm -- TODO: make this configurable
String dbConfigPath = "catalina-users.xml";
MemoryRealm realm = new MemoryRealm();
realm.setPathname(dbConfigPath);
engine.setRealm(realm);
// cache the engine
engines.put(engine.getName(), engine);
// create a default virtual host; others will be created as needed
Host host = createHost(engine, hostName);
hosts.put(engineName + "._DEFAULT", host);
// configure clustering
List<ContainerConfig.Container.Property> clusterProps = engineConfig.getPropertiesWithValue("cluster");
if (clusterProps != null && clusterProps.size() > 1) {
throw new ContainerException("Only one cluster configuration allowed per engine");
}
if (UtilValidate.isNotEmpty(clusterProps)) {
ContainerConfig.Container.Property clusterProp = clusterProps.get(0);
createCluster(clusterProp, host);
clusterConfig.put(engineName, clusterProp);
}
// request dumper valve
boolean enableRequestDump = ContainerConfig.getPropertyValue(engineConfig, "enable-request-dump", false);
if (enableRequestDump) {
RequestDumperValve rdv = new RequestDumperValve();
engine.addValve(rdv);
}
// configure the CrossSubdomainSessionValve
boolean enableSessionValve = ContainerConfig.getPropertyValue(engineConfig, "enable-cross-subdomain-sessions", false);
if (enableSessionValve) {
CrossSubdomainSessionValve sessionValve = new CrossSubdomainSessionValve();
engine.addValve(sessionValve);
}
// configure the access log valve
String logDir = ContainerConfig.getPropertyValue(engineConfig, "access-log-dir", null);
AccessLogValve al = null;
if (logDir != null) {
al = new AccessLogValve();
if (!logDir.startsWith("/")) {
logDir = System.getProperty("ofbiz.home") + "/" + logDir;
}
File logFile = new File(logDir);
if (!logFile.isDirectory()) {
throw new ContainerException("Log directory [" + logDir + "] is not available; make sure the directory is created");
}
al.setDirectory(logFile.getAbsolutePath());
}
// configure the SslAcceleratorValve
String sslAcceleratorPortStr = ContainerConfig.getPropertyValue(engineConfig, "ssl-accelerator-port", null);
if (UtilValidate.isNotEmpty(sslAcceleratorPortStr)) {
Integer sslAcceleratorPort = Integer.valueOf(sslAcceleratorPortStr);
SslAcceleratorValve sslAcceleratorValve = new SslAcceleratorValve();
sslAcceleratorValve.setSslAcceleratorPort(sslAcceleratorPort);
engine.addValve(sslAcceleratorValve);
}
String alp2 = ContainerConfig.getPropertyValue(engineConfig, "access-log-pattern", null);
if (al != null && !UtilValidate.isEmpty(alp2)) {
al.setPattern(alp2);
}
String alp3 = ContainerConfig.getPropertyValue(engineConfig, "access-log-prefix", null);
if (al != null && !UtilValidate.isEmpty(alp3)) {
al.setPrefix(alp3);
}
boolean alp4 = ContainerConfig.getPropertyValue(engineConfig, "access-log-resolve", true);
if (al != null) {
al.setResolveHosts(alp4);
}
boolean alp5 = ContainerConfig.getPropertyValue(engineConfig, "access-log-rotate", false);
if (al != null) {
al.setRotatable(alp5);
}
if (al != null) {
engine.addValve(al);
}
embedded.addEngine(engine);
return engine;
}
protected Host createHost(Engine engine, String hostName) throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot create Host without Embedded instance!");
}
Host host = embedded.createHost(hostName, CATALINA_HOSTS_HOME);
host.setDeployOnStartup(true);
host.setAutoDeploy(true);
host.setRealm(engine.getRealm());
engine.addChild(host);
hosts.put(engine.getName() + hostName, host);
return host;
}
protected Cluster createCluster(ContainerConfig.Container.Property clusterProps, Host host) throws ContainerException {
String defaultValveFilter = ".*.gif;.*.js;.*.jpg;.*.htm;.*.html;.*.txt;";
ReplicationValve clusterValve = new ReplicationValve();
clusterValve.setFilter(ContainerConfig.getPropertyValue(clusterProps, "rep-valve-filter", defaultValveFilter));
String mcb = ContainerConfig.getPropertyValue(clusterProps, "mcast-bind-addr", null);
String mca = ContainerConfig.getPropertyValue(clusterProps, "mcast-addr", null);
int mcp = ContainerConfig.getPropertyValue(clusterProps, "mcast-port", -1);
int mcf = ContainerConfig.getPropertyValue(clusterProps, "mcast-freq", 500);
int mcd = ContainerConfig.getPropertyValue(clusterProps, "mcast-drop-time", 3000);
if (mca == null || mcp == -1) {
throw new ContainerException("Cluster configuration requires mcast-addr and mcast-port properties");
}
McastService mcast = new McastService();
if (mcb != null) {
mcast.setMcastBindAddress(mcb);
}
mcast.setAddress(mca);
mcast.setPort(mcp);
mcast.setMcastDropTime(mcd);
mcast.setFrequency(mcf);
String tla = ContainerConfig.getPropertyValue(clusterProps, "tcp-listen-host", "auto");
int tlp = ContainerConfig.getPropertyValue(clusterProps, "tcp-listen-port", 4001);
int tlt = ContainerConfig.getPropertyValue(clusterProps, "tcp-sector-timeout", 100);
int tlc = ContainerConfig.getPropertyValue(clusterProps, "tcp-thread-count", 6);
//String tls = getPropertyValue(clusterProps, "", "");
if (tlp == -1) {
throw new ContainerException("Cluster configuration requires tcp-listen-port property");
}
NioReceiver listener = new NioReceiver();
listener.setAddress(tla);
listener.setPort(tlp);
listener.setSelectorTimeout(tlt);
listener.setMaxThreads(tlc);
listener.setMinThreads(tlc);
//listener.setIsSenderSynchronized(false);
ReplicationTransmitter trans = new ReplicationTransmitter();
try {
MultiPointSender mps = (MultiPointSender)Class.forName(ContainerConfig.getPropertyValue(clusterProps, "replication-mode", "org.apache.catalina.tribes.transport.bio.PooledMultiSender")).newInstance();
trans.setTransport(mps);
} catch (Exception exc) {
throw new ContainerException("Cluster configuration requires a valid replication-mode property: " + exc.getMessage());
}
String mgrClassName = ContainerConfig.getPropertyValue(clusterProps, "manager-class", "org.apache.catalina.ha.session.DeltaManager");
//int debug = ContainerConfig.getPropertyValue(clusterProps, "debug", 0);
// removed since 5.5.9? boolean expireSession = ContainerConfig.getPropertyValue(clusterProps, "expire-session", false);
// removed since 5.5.9? boolean useDirty = ContainerConfig.getPropertyValue(clusterProps, "use-dirty", true);
SimpleTcpCluster cluster = new SimpleTcpCluster();
cluster.setClusterName(clusterProps.name);
Manager manager = null;
try {
manager = (Manager)Class.forName(mgrClassName).newInstance();
} catch (Exception exc) {
throw new ContainerException("Cluster configuration requires a valid manager-class property: " + exc.getMessage());
}
//cluster.setManagerClassName(mgrClassName);
//host.setManager(manager);
//cluster.registerManager(manager);
cluster.setManagerTemplate((org.apache.catalina.ha.ClusterManager)manager);
//cluster.setDebug(debug);
// removed since 5.5.9? cluster.setExpireSessionsOnShutdown(expireSession);
// removed since 5.5.9? cluster.setUseDirtyFlag(useDirty);
GroupChannel channel = new GroupChannel();
channel.setChannelReceiver(listener);
channel.setChannelSender(trans);
channel.setMembershipService(mcast);
cluster.setChannel(channel);
cluster.addValve(clusterValve);
// removed since 5.5.9? cluster.setPrintToScreen(true);
// set the cluster to the host
host.setCluster(cluster);
Debug.logInfo("Catalina Cluster [" + cluster.getClusterName() + "] configured for host - " + host.getName(), module);
return cluster;
}
protected Connector createConnector(ContainerConfig.Container.Property connectorProp) throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot create Connector without Embedded instance!");
}
// need some standard properties
String protocol = ContainerConfig.getPropertyValue(connectorProp, "protocol", "HTTP/1.1");
String address = ContainerConfig.getPropertyValue(connectorProp, "address", "0.0.0.0");
int port = ContainerConfig.getPropertyValue(connectorProp, "port", 0);
boolean secure = ContainerConfig.getPropertyValue(connectorProp, "secure", false);
if (protocol.toLowerCase().startsWith("ajp")) {
protocol = "ajp";
} else if ("memory".equals(protocol.toLowerCase())) {
protocol = "memory";
} else if (secure) {
protocol = "https";
} else {
protocol = "http";
}
Connector connector = null;
if (UtilValidate.isNotEmpty(connectorProp.properties)) {
connector = embedded.createConnector(address, port, protocol);
try {
for (ContainerConfig.Container.Property prop: connectorProp.properties.values()) {
connector.setProperty(prop.name, prop.value);
//connector.setAttribute(prop.name, prop.value);
}
embedded.addConnector(connector);
} catch (Exception e) {
throw new ContainerException(e);
}
}
return connector;
}
protected Context createContext(ComponentConfig.WebappInfo appInfo) throws ContainerException {
// webapp settings
Map<String, String> initParameters = appInfo.getInitParameters();
List<String> virtualHosts = appInfo.getVirtualHosts();
Engine engine = engines.get(appInfo.server);
if (engine == null) {
Debug.logWarning("Server with name [" + appInfo.server + "] not found; not mounting [" + appInfo.name + "]", module);
return null;
}
// set the root location (make sure we set the paths correctly)
String location = appInfo.componentConfig.getRootLocation() + appInfo.location;
location = location.replace('\\', '/');
if (location.endsWith("/")) {
location = location.substring(0, location.length() - 1);
}
// get the mount point
String mount = appInfo.mountPoint;
if (mount.endsWith("/*")) {
mount = mount.substring(0, mount.length() - 2);
}
// configure persistent sessions
Property clusterProp = clusterConfig.get(engine.getName());
Manager sessionMgr = null;
if (clusterProp != null) {
String mgrClassName = ContainerConfig.getPropertyValue(clusterProp, "manager-class", "org.apache.catalina.ha.session.DeltaManager");
try {
sessionMgr = (Manager)Class.forName(mgrClassName).newInstance();
} catch (Exception exc) {
throw new ContainerException("Cluster configuration requires a valid manager-class property: " + exc.getMessage());
}
} else {
sessionMgr = new StandardManager();
}
// create the web application context
StandardContext context = (StandardContext) embedded.createContext(mount, location);
context.setJ2EEApplication(J2EE_APP);
context.setJ2EEServer(J2EE_SERVER);
context.setLoader(embedded.createLoader(ClassLoaderContainer.getClassLoader()));
context.setCookies(appInfo.isSessionCookieAccepted());
context.addParameter("cookies", appInfo.isSessionCookieAccepted() ? "true" : "false");
context.setDisplayName(appInfo.name);
context.setDocBase(location);
context.setAllowLinking(true);
context.setReloadable(contextReloadable);
context.setDistributable(distribute);
context.setCrossContext(crossContext);
context.setPrivileged(appInfo.privileged);
context.setManager(sessionMgr);
context.getServletContext().setAttribute("_serverId", appInfo.server);
context.getServletContext().setAttribute("componentName", appInfo.componentConfig.getComponentName());
// create the Default Servlet instance to mount
StandardWrapper defaultServlet = new StandardWrapper();
defaultServlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
defaultServlet.setServletName("default");
defaultServlet.setLoadOnStartup(1);
defaultServlet.addInitParameter("debug", "0");
defaultServlet.addInitParameter("listing", "true");
defaultServlet.addMapping("/");
context.addChild(defaultServlet);
context.addServletMapping("/", "default");
// create the Jasper Servlet instance to mount
StandardWrapper jspServlet = new StandardWrapper();
jspServlet.setServletClass("org.apache.jasper.servlet.JspServlet");
jspServlet.setServletName("jsp");
jspServlet.setLoadOnStartup(1);
jspServlet.addInitParameter("fork", "false");
jspServlet.addInitParameter("xpoweredBy", "true");
jspServlet.addMapping("*.jsp");
jspServlet.addMapping("*.jspx");
context.addChild(jspServlet);
context.addServletMapping("*.jsp", "jsp");
// default mime-type mappings
configureMimeTypes(context);
// set the init parameters
for (Map.Entry<String, String> entry: initParameters.entrySet()) {
context.addParameter(entry.getKey(), entry.getValue());
}
if (UtilValidate.isEmpty(virtualHosts)) {
Host host = hosts.get(engine.getName() + "._DEFAULT");
context.setRealm(host.getRealm());
host.addChild(context);
context.getMapper().setDefaultHostName(host.getName());
} else {
// assume that the first virtual-host will be the default; additional virtual-hosts will be aliases
Iterator<String> vhi = virtualHosts.iterator();
String hostName = vhi.next();
boolean newHost = false;
Host host = hosts.get(engine.getName() + "." + hostName);
if (host == null) {
host = createHost(engine, hostName);
newHost = true;
}
while (vhi.hasNext()) {
host.addAlias(vhi.next());
}
context.setRealm(host.getRealm());
host.addChild(context);
context.getMapper().setDefaultHostName(host.getName());
if (newHost) {
hosts.put(engine.getName() + "." + hostName, host);
}
}
return context;
}
protected void loadComponents() throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot load web applications without Embedded instance!");
}
// load the applications
List<ComponentConfig.WebappInfo> webResourceInfos = ComponentConfig.getAllWebappResourceInfos();
List<String> loadedMounts = FastList.newInstance();
if (webResourceInfos != null) {
for (int i = webResourceInfos.size(); i > 0; i--) {
ComponentConfig.WebappInfo appInfo = webResourceInfos.get(i - 1);
String mount = appInfo.getContextRoot();
if (!loadedMounts.contains(mount)) {
createContext(appInfo);
loadedMounts.add(mount);
} else {
appInfo.appBarDisplay = false; // disable app bar display on overrided apps
Debug.logInfo("Duplicate webapp mount; not loading : " + appInfo.getName() + " / " + appInfo.getLocation(), module);
}
}
}
}
public void stop() throws ContainerException {
try {
embedded.stop();
} catch (LifecycleException e) {
// don't throw this; or it will kill the rest of the shutdown process
Debug.logVerbose(e, module); // happens usually when running tests, disabled unless in verbose
}
}
protected void configureMimeTypes(Context context) throws ContainerException {
Map<String, String> mimeTypes = CatalinaContainer.getMimeTypes();
if (UtilValidate.isNotEmpty(mimeTypes)) {
for (Map.Entry<String, String> entry: mimeTypes.entrySet()) {
context.addMimeMapping(entry.getKey(), entry.getValue());
}
}
}
protected static synchronized Map<String, String> getMimeTypes() throws ContainerException {
if (UtilValidate.isNotEmpty(mimeTypes)) {
return mimeTypes;
}
if (mimeTypes == null) mimeTypes = new HashMap<String, String>();
URL xmlUrl = UtilURL.fromResource("mime-type.xml");
// read the document
Document mimeTypeDoc;
try {
mimeTypeDoc = UtilXml.readXmlDocument(xmlUrl, true);
} catch (SAXException e) {
throw new ContainerException("Error reading the mime-type.xml config file: " + xmlUrl, e);
} catch (ParserConfigurationException e) {
throw new ContainerException("Error reading the mime-type.xml config file: " + xmlUrl, e);
} catch (IOException e) {
throw new ContainerException("Error reading the mime-type.xml config file: " + xmlUrl, e);
}
if (mimeTypeDoc == null) {
Debug.logError("Null document returned for mime-type.xml", module);
return null;
}
// root element
Element root = mimeTypeDoc.getDocumentElement();
// mapppings
for (Element curElement: UtilXml.childElementList(root, "mime-mapping")) {
String extension = UtilXml.childElementValue(curElement, "extension");
String type = UtilXml.childElementValue(curElement, "mime-type");
mimeTypes.put(extension, type);
}
return mimeTypes;
}
}
Class.class file
try {
return tmpConstructor.newInstance((Object[])null);
} catch (InvocationTargetException e) {
Unsafe.getUnsafe().throwException(e.getTargetException());
// Not reached
return null;
}
I'm confused state. Please help me to recover this issue.
Thanks in advance.
In the stacktrace there is a
Caused by: java.lang.ArrayIndexOutOfBoundsException: 5747 at
org.codehaus.aspectwerkz.org.objectweb.asm.ClassReader.readClass(Unknown Source)
ASM is a tool to read and manipulate Java class files.
There have been changes to the class file format between JDK 6 and 8 and you (most probably) have an outdated version of ASM which runs into problems when reading Java 8 class files.
To solve the issue try to upgrade to the latest version of ASM (or Ofbiz).
EDIT: As commented by integratingweb Opentaps only supports JDK 6.
I'm trying to monitor temperature from a remote device using a TC65 modem. To request, 'C' has to be sent with a carriage return at the end. The problem is, I only get this on my phone: "This is test sms. The current temperature is " without the temperature I requested. I tried communicating with the thermostat using HyperTeminal without a problem.
Could you help me with instream.read? The output is double (accurate by two decimals).
Here's my code. Thanks.
package example.rs232demo;
import javax.microedition.midlet.*;
import java.io.*;
import javax.microedition.io.*;
import com.siemens.icm.io.*;
public class RS232Demo extends MIDlet {
CommConnection commConn;
InputStream inStream;
OutputStream outStream;
private ATCommand ATC;
public static String phone = "+97455781868";
public static String message = "This is test sms.";
/**
* RS232Demo - default constructor
*/
public RS232Demo() {
//System.out.println("RS232Demo: Constructor");
//System.out.println("Available COM-Ports: " + System.getProperty("microedition.commports"));
try {
//String strCOM = "comm:com0;blocking=on;baudrate=115200";
String strCOM = "comm:com0;blocking=on;baudrate=9600;bitsperchar=7;parity=even";
commConn = (CommConnection)Connector.open(strCOM);
//System.out.println("CommConnection(" + strCOM + ") opened");
//System.out.println("Real baud rate: " + commConn.getBaudRate());
inStream = commConn.openInputStream();
outStream = commConn.openOutputStream();
//System.out.println("InputStream and OutputStream opened");
} catch(IOException e) {
//System.out.println(e);
notifyDestroyed();
}
}
/**
* startApp()
*/
public void startApp() throws MIDletStateChangeException {
int ch = 0;
//System.out.println("RS232Demo: startApp");
//System.out.println("Looping back received data, leave with 'Q'...");
try {
outStream.write('C');
outStream.write('\r');
ch = inStream.read();
} catch(IOException e) {
//System.out.println(e);
}
try
{
this.ATC = new ATCommand(false);
}
catch (ATCommandFailedException ex)
{
ex.printStackTrace();
}
send_Simple_SMS(phone, message, ch);
try
{
this.ATC.release();
}
catch(ATCommandFailedException ex)
{
ex.printStackTrace();
}
destroyApp(true);
}
public void pauseApp() {
//System.out.println("RS232Demo: pauseApp()");
}
public int send_Simple_SMS(String phone, String message, int ch)
{
int res = -1;
String AT = "";
String response = "";
synchronized (System.out)
{
}
if(ATC==null){return res;}
try
{
synchronized (ATC)
{
ATC.send("AT+CMGF=1\r");
ATC.send("AT+IFC=1,1\r");
response = "";
response = ATC.send("AT+CMGS=?\r");
if (response.trim().indexOf("OK") < 0)
{
return res;
}
response = ATC.send("AT+CMGS=" + phone + '\r' + '\n');
//System.out.println("Sending.");
response = ATC.send(message + "The current temperature is " + (char)ch + '\032');
//System.out.println("Sent.");
if (response.trim().indexOf("OK") >= 0)
{
res = 0;
}
ATC.notifyAll();
}
}
catch (ATCommandFailedException ex)
{
ex.printStackTrace();
res = -1;
}
return res;
}
public void destroyApp(boolean cond) {
//System.out.println("RS232Demo: destroyApp(" + cond + ")");
try {
inStream.close();
outStream.close();
commConn.close();
//System.out.println("Streams and connection closed");
} catch(IOException e) {
//System.out.println(e);
}
notifyDestroyed();
}
}
Problem is here:
response = ATC.send(message + "The current temperature is " + (char)ch + '\032');
It converts ch to corrensponding character, not to number string.
Try the following:
response = ATC.send(message + "The current temperature is " + ch + '\032');