Start Java DB server without NetBeans - java

I am creating a Java APP that manages a database. I've been starting the JAVA DB server manually by right clicking - start server. with NetBeans but since I am not going to be the one that runs the application that can't be done anymore. I need a way to start it without NetBeans. Embedded or server mode, I don't really mind.
I've searched a lot but nothing seems to work.
I tried this: Java DB - Starting Server within application
NetworkServerControl server = new NetworkServerControl(InetAddress.getLocalHost(),1527);
server.start(null)
I got java.net.ConnectException: Error al conectarse al servidor localhost en el puerto 1527 con el mensaje Connection refused: connect.
I tried also starting it with the command line
String[] command =
{
"cmd",
};
Process p = Runtime.getRuntime().exec(command);
new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
try (PrintWriter stdin = new PrintWriter(p.getOutputStream())) {
stdin.println("cd C:\\Program Files\\Java\\jdk1.8.0_31\\db\\lib");
stdin.println("java -jar derbyrun.jar server start");
}
int returnCode = p.waitFor();
Also got connection refused, (database Citas not found) so the only way it could work is this:
String host = "jdbc:derby://localhost:1527/Citas";
con = DriverManager.getConnection(host, username, password);
But it works only if I start the server by clicking in Java DB -> start.
Any help would be higly appreciated

Can you try starting it using Runtime?
Runtime runtime = Runtime.getRuntime();
runtime.exec(new String[]{ "java", "-jar", "/path/to/derbyrun.jar", "server", "start");
If you were to do this in its own thread, you could also append .waitFor() to the .exec command which will hang until the process finishes. This would be good to determine if the db closed unexpectedly.
Also using runtime, you can get read the stdout / stderr of the process, and kill it if need be. Possibilities are endless.

Related

How to control netty server from spring-shell

I try to create a console with "spring shell", I would like to run my own netty socket server command. I have a command:
#CliCommand(value = "server", help = "Start socket server")
public String server(
#CliOption(key = {"port", "p"}, mandatory = true, help = "Port number [49152-65535]") final String port,
#CliOption(key = {"maxclients", "mc"}, mandatory = false, help = "Max clients", unspecifiedDefaultValue = "50") final String maxClients
)
{
NettyServer nettyServer = new NettyServer(Integer.parseInt(port), Integer.parseInt(maxClients));
nettyServer.run();
return "::CliCommand return::";
}
While the server is running, it blocks the console and can not enter other commands. Should not you have a solution? For example, how to let it run alone and only influence the server by the command. For example, I would like to send messages from my console to clients.
I can't answer for the whole architecture of your application, but your server object should not be created inside your command method.
It should be created prior to that (or at the very least, it should not be a local parameter of your command method that dies when your command ends) and acted upon by commands, using a different thread I assume.

Java Code stucking when attempt read output messages of Process

I use ProcessBuilder for execute the cmd commands in my application for Start & Stop Derby Network Server. But somethings going wrong and i don't find where the problem. Let me explain it;
Starting Network Server;
//Defining path of db files located
File file= new File(FirstTimeMainFrame.class.getProtectionDomain()
.getCodeSource()
.getLocation()
.getPath().replace(new File(FirstTimeMainFrame.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName(), "").replace("%20", " "));
String path = file+"\\DB";
//Process Creating
ProcessBuilder builder = new ProcessBuilder();
Process process = null;
String[] command = new String[3];
command[0] = "cmd.exe";
command[1] = "/c"; //This things say to CMD close when commands complete.
command[2] = "cd "+path+" && java -jar derbyrun.jar server start";
builder = new ProcessBuilder(command[0], command[1], command[2]);
builder.redirectErrorStream(true);
process = builder.start();
//Reading CMD outputs
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while (true) {
line = br.readLine();
if (line == null) { break; }
System.out.println(line);
}
When i debug the project i see output for two lines and debug stuck at line = br.readLine(); when While loop come and check for third time. Whole program stuck and can't continue.
Outputs;
Fri Dec 25 20:54:36 EET 2015 : Security manager installed using the Basic server security policy.
Fri Dec 25 20:54:36 EET 2015 : Apache Derby Network Server - 10.12.1.1 - (1704137) started and ready to accept connections on port 1527
Important P.S.: If i remove //Reading CMD outputs codes all things working perfectly. Server Starting, DB Created, Tables Created etc.
Also i tried same CMD Command under Windows directly. When i execute the command, two line writed and Command Prompt window stuck at the flashing cursor (not closed or complete i think) but Derby Server is started without problem in programaticly or directly in Windows.
There are actually two processes running in the scenario: CMD process started from java code and Derby server process spawned by CMD.
The output from Derby server process is directed to command line and then can be read in java code. Server process can run infinetly long until it will be terminated, that's why output stream never ends.
Hanging in java code happens because there are no available bytes in the stream at the moment - server process told you that it was successfully initialized and then moved to waiting state.

Start Selenium Hub and Node using ProcessBuilder.java - port error

I have Swing front end for use as a client to kick off Selenium tests. At the point where I kick off the test process, the first thing I do is fire up a local Selenium hub and node using the following code:
String[] nodeCmd = new String[]{"java", "-jar", "selenium-server-standalone-2.39.0.jar", "-role node", "-nodeConfig config\\DefaultNode.json"};
ProcessBuilder pbNode = new ProcessBuilder(nodeCmd);
pbNode.directory(new File("C:\\selenium\\"));
File nodeLog = new File("C:\\selenium\\logs\\nodeOut.log");
pbNode.redirectErrorStream(true);
pbNode.redirectOutput(nodeLog);
Process nodeP = pbNode.start();
String[] hubCmd = new String[]{"java", "-jar", "selenium-server-standalone-2.39.0.jar", "-role hub", "-hubConfig config\\DefaultHub.json"};
ProcessBuilder pbHub = new ProcessBuilder(hubCmd);
pbHub.directory(new File("C:\\selenium\\"));
File hubLog = new File("C:\\selenium\\logs\\hubOut.log");
pbHub.redirectErrorStream(true);
pbHub.redirectOutput(hubLog);
Process hubP = pbHub.start();
Whilst the hub is started up correctly, when the node process is started it seems to be doing so as a hub (log output is exactly the same) with the result that it complains the port is already in use.
Exception in thread "main" java.net.BindException: Selenium is already running on port 4444. Or some other service is.
at org.openqa.selenium.server.SeleniumServer.start(SeleniumServer.java:491)
at org.openqa.selenium.server.SeleniumServer.boot(SeleniumServer.java:300)
at org.openqa.selenium.server.SeleniumServer.main(SeleniumServer.java:245)
at org.openqa.grid.selenium.GridLauncher.main(GridLauncher.java:96)
Any ideas what I am doing wrong? I have checked the config files and they are definitely right.
Update
So I finally worked out what I was doing wrong! My mistake is in the way I was constructing my Array of parameters to pass into the ProcessBuilder constructor.
Wrong:
String[] nodeCmd = new String[]{"java", "-jar", "selenium-server-standalone-2.39.0.jar", "-role node", "-nodeConfig config\\DefaultNode.json"};
Right:
String[] nodeCmd = new String[]{"java", "-jar", "selenium-server-standalone-2.39.0.jar", "-role", "node", "-nodeConfig", "config\\DefaultNode.json"};
I wan't splitting the key string and value string for the role and config params. Grrr!
Make sure that your nodeConfig.json is using the "port" property of an unused port (defaults to 5555), and make sure that in your hubConfig.json, it is using the "port" property of an unused port (defaults to 4444)
If you can validate that the above are both correct, then the only other issue that i can imagine, is that the previous hubs (probably started up when testing this very functionality) were left open.
I would ensure that all java.exe processes are terminated, and add a failsafe in your code to quit the grid.

Automatically close and disconnect a java sshj session

I am using the sshj library for java.
I need to open an ssh session on a remote server, execute a command which could run for many minutes, and then continue on executing in my java code. Once the command running on the remote server is finished, i would like the ssh session to close, and the sshclient to disconnect.
I have seen the following code example:
public class Exec {
public static void main(String... args) throws IOException {
final SSHClient ssh = new SSHClient();
ssh.loadKnownHosts();
ssh.connect("localhost");
try {
ssh.authPublickey(System.getProperty("user.name"));
final Session session = ssh.startSession();
try {
final Command cmd = session.exec("ping -c 1 google.com");
System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
cmd.join(5, TimeUnit.SECONDS);
System.out.println("\n** exit status: " + cmd.getExitStatus());
} finally {
session.close();
}
} finally {
ssh.disconnect();
}
}
}
Basically I don't want to wait for the command to finish (no cmd.join call) and I need the session.close() and ssh.disconnect() to be called automatically once the command has exited. Is this possible?
I may not be able to exactly answer my question, but maybe provide help for others trying to do something similar to what I was doing. When I posted, I was under the impression that the ssh session had to stay open for the command to finish, but I don't think that is the case.
So what I was trying to do was start a remote ssh session via java, and run a shell script on the remote machine. The shell script could take up to 10-15 mins to complete. I tested a short timeout (5 secs) and the script continued to run after the session was disconnected... which is what I wanted.

Access running java program from shell command

I am looking for a way to access running java program from command line. The best woud be something that does the following:
Starting java app:
bash$java -jar MyBundle.jar App
Accessing app:
bash$test.sh param1 param2
So, test.sh calls App from MyBundle.jar somehow and passes values param1 & param2.
Important: I am looking for very fast approach. App hold database connection and it is very expensive to start App every time I need access do DB.
I need solution that will work in Ubuntu and Debian. If it will work on Mac - great.
Any help is appreciated!
I think you need to take a client-server approach. You app is the server, it runs as a background process and listens for connections on some port. And your client makes requests to the server and gets back the response.
A fast and simple way of implementing this in java would be to wrap your app in the Jetty servlet container. You could set it up to return JSON responses for example, which are easy to process.
It would be quite straightforward to open a TCP/IP socket and use netcat from the shell.
Java code
final ServerSocket serverSocket = new ServerSocket(9050);
while (true) {
final Socket socket = serverSocket.accept();
java.util.logging.Logger.getAnonymousLogger().info("Accepted");
final BufferedReader br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
final String input = br.readLine();
final BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
bw.write("You said [" + input + "]");
bw.flush();
socket.close();
}
Shell code
echo 'bla' | nc localhost 9050
You'd need to muck around with threads to keep the sockets open to serve multiple requests.

Categories