I'm developing a RESTful web-service using Jersey. I am using maven to manage my dependencies and eclipse export method to create the jar.
When running the jar on my Ubuntu pc, everything is working fine, but when I'm executing the same jar on a remote Openshift server I'm experiencing this weird thing:
The server start and running, executing a GET request returns the expected answer.
Executing a POST method return a 500 server error, when on my local machine it returns the expected result.
Diving into this problem I have realised the following facts:
The last line the program is printing is validate.fullmessage: ... and the correct String message representation of the JSONObject. The "1" line is not printed to the log. No exception is thrown or written to the log as well!
public static boolean validate(String fullMessage) {
...
try {
System.out.println("validate.fullmessage: " + fullMessage);
JSONObject jsonMessage = new JSONObject(fullMessage);
System.out.println("1");
...
} catch (Exception e) {
System.out.println("validation exception");
e.printStackTrace();
}
...
}
Moreover, whenever I return 200 ok or server error I'm writing it to the log, but no error is written to the log. It seems like the server return 500 server error with no reason and not from my code...
RESTHandler:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Path("/createPlayer")
public Response createUser(String strPlayer) {
System.out.println("createPlayer. strPlayer: " + strPlayer);
Response r;
System.out.println("validating");
if (!ValidateHandler.validate(strPlayer)) {
System.out.println("validation failed!");
r = Response.serverError().build();
}
...
System.out.println("finished");
return r;
}
The "finished" is also not written to the log.
Can anyone help me figure out this weird behaviour?
Ok. So after temporarily changing the Exception handling to catch all Throwables (this way catching RuntimeErrors also, not only Exceptions), the problem turned out to be java versioning issue.
On the remote machine you are using a different version of java, probably older than the one which was used to compile one of your libraries.
The easy solution (if this is available) is upgrading your remote server java version to the one that is used on your computer locally.
If that is not an option, then you need to analyze the error and find and downgrade the library which is incompatible with your outdated server java version.
Related
I have a simple Java application, basically a server implemented using com.sun.net.HttpServer API, that reads a file and simply sends back the texts after some processing. The server part simply looks like this:
server = HttpServer.create(new InetSocketAddress(serverPort), 0);
logger.info("EventRetriever REST server listening to port: " + serverPort);
server.createContext("/getEvents", new MedatadaHandler());
server.setExecutor(null);
server.start();
// ...
#Override
public void handle(HttpExchange he) throws IOException {
//...
String response = requestEvents();
he.sendResponseHeaders(200, response.length());
OutputStream os = he.getResponseBody();
os.write(response.toString().getBytes());
os.close();
}
//...
public String requestEvents(){
//...
// this printing on the console looks fine though:
logger.info(jsonString);
return jsonString;
}
I run my jar file with java -jar myApp.jar on a command line or simply on my IDE. I'm witnessing some weird behaviors, sometimes just hanging, when it requires sending texts containing special characters, such as the music symbol ♪. When I call the IP:PORT/getEvent via a browser, the behavior is so weird:
If I run it on a Windows Powershell or Command Prompt, the symbol appears as ? on the console, and what I get from the browser is also shown as ?. But when I run the program on a linux server or my Eclipse IDE, it is shown correctly on the console (as ♪), but on the browser, I get the following error, although the status is 200 OK. I see on the console the java application keep looping printing the line every few seconds (as if it is trying to send the data, but can't maybe something is blocking it!). But I don't get any exception or errors on the app (I log all possible errors).
I'm very confused for this behavior. What's going on?!
First, why what I get is dependent on the environment I run my Java app?! If Windows Command Prompt/Powershell shows the character as ?, I expect it just showing it locally like that. Why should I see it also as ? on my browser?! Java app must be independent of the environment.
And second, what is going on with that error on the Linux/Eclipse envrionment when requesting a line that has this character?
The issue as could be predicted, was related to getBytes() and UTF-8 String representations. Did the following and it was all good then:
he.sendResponseHeaders(200, response.getBytes("UTF-8").length);
OutputStream os = he.getResponseBody();
os.write(response.getBytes("UTF-8"));
We are building a websocket webapp for a school project and would like to store the incoming information to MySQL. Currently we are using netbeans and the Server Endpoint is written in Java. The info sent from the client side is a JSON obj. We can decode it but dont't know how to insert it into the table
Problems we are facing
1.We are used to programming Java application and using mysql JDBC but this time we cannot find the library to add, like we use to do.
2.We have tried AJAX but since the PHP is on a different server we cant do it, and I can't find the option to add a PHP file to the current project in netbeans. -- Currently I'm trying to learn how to do AJAX with JSP
3.We think we need to spin a thread so that the reply doesn't have to wait for the insert to complete but when we try to spin a thread the Endpoint no longer works, so we commented it out
4.We are trying to keep third party Frame works to a minimum
Below is the code to our Server Endpoint
public void onMessage(String message, Session session) {
// Create JsonObject from message
JsonObject jsonObject = new Message(message).getJObject();
// Decode JsonObject
message = Decoder(jsonObject);
for (Session peer : peers) {
try {
if (!peer.equals(session)) {
peer.getBasicRemote().sendText(message);
}
} catch (IOException ex) {
Logger.getLogger(ServerEndpoint.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
This is our current decoder. We wanted to spin a thread from this function, I don't know if that is a good idea or not
public String Decoder(JsonObject jObject) {
String message;
message = jObject.getString("msg");
return message;
}
Since Netbeans use Glassfish, I downloaded the MySQL JDBC and put it in the lib folder as I would if I was running Tomcat. Then I go into the Admin console and added the JDBC Connector then added the JDBC Resource. Next restart the server then redeploy the app.
I have the following code that is executed in java as the clientendpoint of a websocket
protected void dequeue() throws InterruptedException, IOException
{
ByteBuffer bbuf;
System.out.println("start");
while((bbuf = messageQueue.take()).get(0) != 0)
{
bbuf.position(bbuf.limit());
if(bbuf.get(0)== 0)
System.out.println("here");
bbuf.flip();
for(Session session : sessionList)
{
//Thread.sleep(10000);
if(!session.isOpen())
break;
session.getBasicRemote().sendBinary(bbuf);
}
}
System.out.println("end");
}
The code works fine when the Thread.sleep() that is commented out is put back into the code. However when the Thread.sleep() is not included in the code the writes to the websocket sometimes work and other times the #onClose is called after the first message is written and the following reason is given,
CloseReason: code [1002], reason [The client frame set the reserved bits to [7] which was not supported by this endpoint]
In which the [7] will sometimes be a 1,2,etc. I have not been able to find anything really to why this would be happening, does anyone happen to have any insight into what is happening? As of note, I am using tomcat 7.0.53 to host the ServerSide of the websocket and uses HTTPS instead of HTTP.
This is due to the following bug in tomcat, https://issues.apache.org/bugzilla/show_bug.cgi?id=57318#c1 updating to apache tomcat 7.0.57 will fix the issue. Updating to an apache tomcat version greater then 7.0.53 may fix the issue but has not been tested yet.
I'm working on an old project and, due to the short time to deploy new release, I cannot migrate the upload of content using CMIS so, I need to use old WebServiceFactory code to create binary into Alfresco.
But, with the new release of Alfresco (5.0.a) I'm not able to obtain the authorization using:
WebServiceFactory.setEndpointAddress("http://localhost:8080/alfresco/api");
AuthenticationUtils.startSession(userName, password);
This is the error I'm getting:
Caused by: (404)Not Found
at org.apache.axis.transport.http.HTTPSender.readFromSocket(HTTPSender.java:744)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:144)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
Any clue? Do you know if there a really (really really) fast way to create folder and update binary from Java classes?
thanks,
Andrea
Go grab the File Loader example from this code, edit the pom.xml to the latest version of everything, point it at your server, run, enjoy.
The problem is related only to the start of the first session, in our case, because the WebServiceFactory try to load the file "alfresco/webserviceclient.properties" by default.
We've resolved the issue with this workaround:
public static void startSession(String endpoint, String username, String password)
throws Exception {
try {
if (_log.isDebugEnabled()) {
_log.debug("Connecting to: " + endpoint);
}
/** fix for http 404 error during start first session
* needs to init {#link WebServiceFactory#loadedProperties} field to true and nothing else
*/
WebServiceFactory.getEndpointAddress();
/** fix for http 404 error during start first session*/
WebServiceFactory.setEndpointAddress(endpoint);
AuthenticationUtils.startSession(username, password);
if (_log.isDebugEnabled()) {
_log.debug("Start session with ticket: " + AuthenticationUtils.getTicket());
}
}
catch (Exception e) {
_log.error("Can not initiate session with Alfresco server.");
throw e;
}
}
I want to edit the RMI hello world example to work with client and server on different machines, but i'm stuck with the unmarshalling return error.
If i run client and server in the same project on Netbeans they work fine but when i split them i edited the try statement on the client side to be:
try {
Registry registry = LocateRegistry.getRegistry("localhost");
String[] c = registry.list();
System.out.println(c[0].toString());
Remote lookup = Naming.lookup("HelloServer");
} catch (Exception e) {
System.out.println("HelloClient exception: " + e.getMessage());
}
without Remote lookup = Naming.lookup("HelloServer");, the print command gives "HelloServer" which is correct, but when i create the remote object I'm getting this error:
HelloClient exception: error unmarshalling return; nested exception is:
java.lang.ClassNotFoundException: rmimain.Hello
I've tested the policy and it's working fine, any help would be much appreciated.
Your client doesn't have the rmimain.Hello class on its CLASSPATH.