I am developing a project that needs booth a web and desktop application. The web app receives the tasks from my clients and stores them (in database). The desktop application gets the tasks (from database) and execute them one by one. In my web application i am using java servlets, web services ...
Sometimes my glassfish server (v 3.1.2) freezes or he becomes blocked and needs to be restarted so he can continue work properly. I can detect this kind of error by monitoring him and find out when he freezes (by calling simple web service method that throws exception, simple http request that also throws exception etc).
I want my desktop application get the Glassfish server status and if
"Everything is ok" then "Do nothing"
"Server is down" then "Start Glassfish Server"
"I detect an error" then "Restart Glassfish Server"
"Application quit" then "Shutdown Glassfish Server"
Does anyone had this problem and has any solution. I am tired of manually restarting the glassfish server.
I run Glassfish 3.1.2 in production for months at a time without issue. I would suspect the freezing your are seeing is a problem with the application you have deployed to it.
I think you would be best served spending time investigating and remediating your hanging issue. Have you tried taking a thread dump of the Glassfish java process when this happens?
I found my own solution that i want to share.
When i detect that something is wrong with my Glassfish server, i restart it. This solutions only works on Linux (i will edit this answer if i find simular for windows users). Also u might have to add this line for your user in "/etc/sudoers" under root user, adrian is my username.
adrian ALL=(ALL:ALL) ALL
GlassFish Class: (U will need to change glassfishPath and domainName with yours)
package es.web.glassfish;
import es.os.linux.Konsole;
import java.io.IOException;
/**
*
* #author adrian
*/
public class Glassfish {
private final static String glassfishPath = "/home/adrian/glassfish-4.0/";
private final static String domainName = "domain1";
public static String startGlassfishServer() throws IOException, InterruptedException {
String command = glassfishPath + "bin/asadmin start-domain "+domainName;
return Konsole.executeCommand(command);
}
public static String stopGlassfishServer() throws IOException, InterruptedException {
String command = glassfishPath + "bin/asadmin stop-domain "+domainName;
return Konsole.executeCommand(command);
}
public static String restrartGlassfishServer() throws IOException, InterruptedException {
String command = glassfishPath + "bin/asadmin restart-domain "+domainName;
return Konsole.executeCommand(command);
}
}
Konsole Class:
package es.os.linux;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* #author adrian
*/
public class Konsole {
static Process process;
static BufferedReader reader;
public static String executeCommand(String command) throws IOException, InterruptedException {
String rez = "";
process = Runtime.getRuntime().exec(command);
process.waitFor();
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
rez += line + "#";
}
return rez;
}
}
Test Class:
public class test {
/**
* #param args the command line arguments
*/
public static void main(String[] args){
try {
System.out.println("START");
System.out.println(Glassfish.startGlassfishServer());
System.out.println("RESTART");
System.out.println(Glassfish.restrartGlassfishServer());
System.out.println("STOP");
System.out.println(Glassfish.stopGlassfishServer());
} catch (IOException ex) {
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
Test class output:
START
Waiting for domain1 to start ............#Successfully started the domain : domain1#domain Location: /home/adrian/glassfish-4.0/glassfish/domains/domain1#Log File: /home/adrian/glassfish-4.0/glassfish/domains/domain1/logs/server.log#Admin Port: 4848#Command start-domain executed successfully.#
RESTART
Successfully restarted the domain#Command restart-domain executed successfully.#
STOP
Waiting for the domain to stop #Command stop-domain executed successfully.#
Related
When I run the client it's supposed to send an email to my server and then I want my email server to print out the email details (to, from, port, message) to console. For some reason after running the client, nothing apparent happens on the server.
server
package example;
import org.subethamail.smtp.server.SMTPServer;
public class EmailServer {
public static void main(String[] args) {
MyMessageHandlerFactory myFactory = new MyMessageHandlerFactory();
SMTPServer smtpServer = new SMTPServer(myFactory);
smtpServer.setPort(25000);
smtpServer.start();
}
}
server output
run: [main] INFO org.subethamail.smtp.server.SMTPServer - SMTP server
*:25000 starting [org.subethamail.smtp.server.ServerThread *:25000] INFO org.subethamail.smtp.server.ServerThread - SMTP server *:25000
started
client
package example;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.subethamail.smtp.client.*;
public class EmailClient {
public static void main(String[] args) {
try {
SMTPClient sc = new SMTPClient();
sc.close();
sc.connect("localhost", 25000);
sc.sendReceive("test");
} catch (IOException ex) {
Logger.getLogger(EmailClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
client output
run: BUILD SUCCESSFUL (total time: 0 seconds)
Version is 3.1.7 from https://code.google.com/p/subethasmtp/downloads/list
The server requires MyMessageHandlerFactory which I copied from: https://code.google.com/p/subethasmtp/wiki/SimpleExample
OK, let's check the source code (always a good idea) and see what happens.
You send "test" via
SMTPClient sc;
sc.sendReceive("test"); // which is actually sent to your SMTPServer as "test\r\n"
Now, considering that this is a new SMTP conversation (see RFC5321 for everything you always wanted to know but were afraid to ask about such things) and "test" isn't a valid command VERB at this point in the conversation, you would expect to see an error returned by sendReceive().
But since you're ignoring the SMTPClient.Response#75 returned from what should have been
Response resp=SMTPClient.sendReceive()
you're missing out on both
resp.code (which I am sure is 500 - Permanent Negative Completion reply / Syntax - see the RFC above) and
resp.message describing the reason your command could not be fulfulled
both of which are returned from CommandHandler#93.
I recently visited heroku.com site and tried to deploy my first java program there , I actually had a good start using their java deployment tutorial, and had it run ok. now I have a server code which I need to deploy there , I tried to follow the example but I had some question in mind like,
1- what will be the host in this case , I already tried the app link as if its the host but it throws errors ,
here is my sample server code
public class DateServer {
/** Runs the server. */
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket(6780);
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
} finally {
socket.close();
}
}
} finally {
listener.close();
}
}
}
here is my client code
public class DateClient {
/** Runs the client as an application. First it displays a dialog box asking for the IP address or hostname of a host running the date server, then connects to it and displays the date that it serves. */
public static void main(String[] args) throws IOException {
//I used my serverAddress is my external ip address
Socket s = new Socket(serverAddress, 6780);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}
I followed this tutorial https://devcenter.heroku.com/articles/java at their site to upload my server code is there something else I need to do ?!
thanks in advance
On Heroku, your application must bind to the HTTP port provided in the $PORT environment variable. Given this, the two major problems in your application code above are 1) you are binding to a hardcoded port (6780) and 2) your application is using TCP instead of HTTP. As shown in the tutorial, use something like Jetty to accomplish the HTTP equivalent of your application and use System.getenv("PORT") to bind to the right port, like this:
import java.util.Date;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.*;
public class HelloWorld extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().print(new Date().toString());
}
public static void main(String[] args) throws Exception{
Server server = new Server(Integer.valueOf(System.getenv("PORT")));
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
context.addServlet(new ServletHolder(new HelloWorld()),"/*");
server.start();
server.join();
}
}
I am copying the simplest web service example from CXF; it steps through writing an interface, then an implementation file, to say hello to a name provided by the webservice consumer. I changed a package name and the method name because I wanted to see where things showed up; if you name everything HelloWorld you can't see what is method, package, class, etc.
Those instructions include a program to publish the web service. After I do that, putting the URL
http://localhost:9000/helloWorld?wsdl
in a browser displays a wsdl file that contains enough stuff the way I spelled it to convince me that it was generated from my code. I assume, based on this, that both the WSDL generation and the publication worked.
This is the service interface:
package hw;
import javax.jws.WebParam;
import javax.jws.WebService;
#WebService
public interface HelloWorld
{
String sayHi(#WebParam(name="firstName") String firstName);
}
This is the service implementation:
package hwimpl;
import javax.jws.WebService;
#WebService(endpointInterface = "hw.HelloWorld", serviceName = "HelloWorld")
public class HelloWorldImpl
{
static public void say(String msg) { System.out.println(msg); }
public String sayHi(String firstName)
{ say ("sayHi called with " + firstName);
return "Hello " + firstName + " from the World.";
}
}
And this is the publishing program:
package hwimpl;
import javax.xml.ws.Endpoint;
public class PublishHelloWorldService
{
protected PublishHelloWorldService() throws Exception
{
// START SNIPPET: publish
System.out.println("Starting Server");
HelloWorldImpl implementor = new HelloWorldImpl();
String address = "http://localhost:9000/helloWorld";
Endpoint.publish(address, implementor);
// END SNIPPET: publish
}
public static void main(String args[]) throws Exception
{
new PublishHelloWorldService();
System.out.println("Server ready...");
Thread.sleep(5 * 60 * 1000);
System.out.println("Server exiting");
System.exit(0);
}
}
Now I compile and run this program:
package client;
import hw.HelloWorld;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.soap.SOAPBinding;
public final class HelloWorldClient
{
private static final QName SERVICE_NAME = new QName("http://server.hw.demo/", "HelloWorld");
private static final QName PORT_NAME = new QName("http://server.hw.demo/", "HelloWorldPort");
private HelloWorldClient()
{
}
public static void main(String args[]) throws Exception
{
Service service = Service.create(SERVICE_NAME);
String endpointAddress = "http://localhost:9000/helloWorld";
// If web service deployed on Tomcat deployment, endpoint should be changed
// to:
// String
// endpointAddress =
// "http://localhost:8080/java_first_jaxws/services/hello_world";
// Add a port to the Service
service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
HelloWorld hw = service.getPort(HelloWorld.class);
System.out.println(hw.sayHi("Albert"));
}
}
and I get this error:
Exception in thread "main" javax.xml.ws.WebServiceException: Could not send Message.
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:135)
at com.sun.proxy.$Proxy20.sayHi(Unknown Source)
at client.HelloWorldClient.main(HelloWorldClient.java:37)
Caused by: java.net.MalformedURLException: Invalid address. Endpoint address cannot be null.
at org.apache.cxf.transport.http.HTTPConduit.getURL(HTTPConduit.java:872)
at org.apache.cxf.transport.http.HTTPConduit.getURL(HTTPConduit.java:854)
at org.apache.cxf.transport.http.HTTPConduit.setupURL(HTTPConduit.java:800)
at org.apache.cxf.transport.http.HTTPConduit.prepare(HTTPConduit.java:548)
at org.apache.cxf.interceptor.MessageSenderInterceptor.handleMessage(MessageSenderInterceptor.java:46)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:255)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:516)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:313)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:265)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:73)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:124)
... 2 more
I am running the programs -- both publish and client -- from eclipse. The eclipse is set up with proxies for http and https in Window / Preferences; I removed the one for http before running the client, but it did not change the message.
It is in fact a tomcat server; I tried the alternate URL in the publish program with no change.
I don't run tomcat from within eclipse in this case; I run it by itself on my machine and then run the publish program (from eclipse), verify the url that displays the wsdl works correctly, and then run the client program (from eclipse) and get my error.
Can someone tell me what I'm doing wrong? I've seen other posts on this exact error message, but none of the answers were definitive and I appear to have tried them all.
Not sure this is your problem.
I've sometimes had problems with eclipse not being able to run tomcat applications on a running tomcat as you describe in your example.
What I sometimes have to do when working with tomcat and eclipse is either
have a running tomcat (windows service) and then export my eclipse application to that tomcat
stop the running tomcat on that port from windows services and start the tomcat from inside eclipse when running the program.
For some reason eclipse seems to have problems with an already running tomcat.
I have a JNLP downloader application deployed on remote user machines that downloads files.
I need to get some error feedback mailed to me. Not so much exceptions, just things getting stuck, or stalled or in infinite loops.
Currently I have a basic handler:
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class javaerrorlog {
private static Logger l = Logger.getLogger("");
public static void main(String args[]) throws Exception{
FileHandler handler = new FileHandler("log.txt");
l.addHandler(handler);
l.setLevel(Level.ALL);
l.info("Error logs");
try {
} catch (Error ex) {
l.log(Level.INFO, "", ex);
}
l.fine("");
}
}
Also, should I prompt for the client's permission to send error reporting data?
If you just need notifications you could use something like SMTPHandler. If you need it more fancy you could use JMS with an MDB.
I am writing a utility to start and stop windows services. The program will be distributed across many computers with differing levels of user privileges so I don't want to use the command line. I've tried using JNA,
import com.sun.jna.platform.win32.W32Service;
import com.sun.jna.platform.win32.W32ServiceManager;
import com.sun.jna.platform.win32.Winsvc;
/**
*
* #author
*/
public class WindowsServices {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try
{
// TODO code application logic here
W32ServiceManager serviceManager = new W32ServiceManager();
W32Service service = serviceManager.openService("uvnc_service", Winsvc.SERVICE_ACCEPT_STOP);
service.stopService();
service.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
When I run the program I get the following error
com.sun.jna.platform.win32.Win32Exception: The handle is invalid.
at com.sun.jna.platform.win32.W32ServiceManager.openService(W32ServiceManager.java:77)
at windowsservices.WindowsServices.main(WindowsServices.java:26)
Any suggestions would be most helpful.
Thanks for the suggestion the author of the question found the error.
import com.sun.jna.platform.win32.W32Service;
import com.sun.jna.platform.win32.W32ServiceManager;
import com.sun.jna.platform.win32.Winsvc;
/**
*
* #author
*/
public class WindowsServices {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try
{
W32ServiceManager serviceManager = new W32ServiceManager();
serviceManager.open(Winsvc.SC_MANAGER_ALL_ACCESS);
W32Service service = serviceManager.openService("uvnc_service", Winsvc.SC_MANAGER_ALL_ACCESS);
service.startService();
service.close();
} catch (Exception ex)
{
ex.printStackTrace();
}
}
}
The error was that the code didn't open the Service Control Manager. I was looking on MSDN and found the process that I needed to follow. I also chanced the permission value, that might also of caused a failure.
We use Runtime.getRuntime().exec(command) and then execute the command
cmd /c net start
to start services and
cmd /c net stop
to stop services.
Of course you have to know the service names (and in our case it is DB2 we are after). But this has worked for us.