I am trying a thrift client-server hello world call.
The server is written in java and the client is in javascript.
Client.html is as follows:
<html>
<script src="thrift.js" type="text/javascript"> </script>
<script src="helloWorld.js" type="text/javascript" ></script>
<script src="callServer.js" type="text/javascript" ></script>
<body>
Test The thrift call....
<button onclick="getInfo();">Click me</button>
</body>
</html>
Above thrift.js is thrift javascript library version 8.0 and helloWorld.js is the generated js file from the following thrift idl.
service helloWorld{
string getWorld();
}
callServer.js
/*callServer.js*/
function getInfo() {
alert("reached callServer.js");
var url = "http://localhost:8080/myWebProj/HelloWorldServlet";
var transport = new Thrift.Transport(url);
var protocol = new Thrift.Protocol(transport);
var client = new helloWorldClient(protocol);
alert(client.getWorld());
}
At the server side
I have a servlet mapped in web.xml and one implementation class
public class HelloWorldServlet extends TServlet{
private static final long serialVersionUID = -3425847860067398133L;
public HelloWorldServlet() {
super(new HelloWorld.Processor(new Hworld()),
new TJSONProtocol.Factory());
}
}
public class Hworld implements HelloWorld.Iface{
#Override
public String getWorld() throws TException {
// TODO Auto-generated method stub
System.out.println(" in hello World .... ");
return "Hello World";
}
}
The sysout in above code is printed successfully when I try to hit the server.But at the client side I get NS_ERROR_FAILURE. I guess I am doing something wrong.Please help me.In case any other info is required plz post it as comment.
Related
This is the webpage I am trying to access:
http://ssbmapp.byethost18.com/demo.php
But, regardless of how I attempt to access it in my android studio project, I get this for the body of the page:
<html>
<body>
<script type="text/javascript" src="/aes.js" ></script>
<script>
function toNumbers(d) {
var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("f816ad55200eac766df3e7c7ba7c6897");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";location.href="http://ssbmapp.byethost18.com/demo.php?ckattempt=1";
</script>
<noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript>
</body>
</html>
Here is the code in my project:
#Override
protected Void doInBackground(Void... params) {
try {
String json = Jsoup.connect("http://ssbmapp.byethost18.com/demo.php").ignoreContentType(true).execute().body();
Log.d("smash", json);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
It looks like the original PHP page does not produce the JSON object immediately. Instead, it produces a javascript code that eventually makes another HTTP request and gets the JSON. If you use a Web HTTP request/response sniffer such as http://web-sniffer.net/ you will see that the site response is exactly the same as the one your code is printing.
I am sending a ajax request from a client such as:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
url: "http://192.168.1.74:8888",
type: "POST",
data: ({username: 'Bobby'})
});
})
</script>
</head>
<body>
</body>
</html>
My Http Server is written in Java utilizing vertx is like so:
public class Main extends AbstractVerticle {
#Override
public void start() throws Exception {
vertx.createHttpServer().requestHandler(new Handler<HttpServerRequest>() {
#Override
public void handle(HttpServerRequest request) {
System.out.println(request.getParam("username"));
}
}).listen(8888);
}
}
Every time I run the client, the server writes to console so the request is sent, but the server says the value is null. What am I doing wrong? How do I read the POST parameter being sent from the client?
UPDATE:
I found the problem, but no solution. If I change the ajax to GET from POST then it will appear. How do I make it so it works for POST and not for GET? SO the opposite of what is occurring now?
Cheers
I encountered the problem while working on my project. I was using Dojo on the client side. I manged to solve this by making adjustments both on the client side and the server side.
Client:
var json = JSON.stringify({
"username": "Bobby"
});
request.post("yoururl", {
data: json,
headers: {
"Content-Type": "application/javascript"
}
});
On the server side, apparently, what was required was calling the method BodyHandler.create() before handling the code.
router.route(HttpMethod.POST, "yoururl").handler(BodyHandler.create());
router.route(HttpMethod.POST, "yoururl").handler(routingContext ->
{
String sectionType = routingContext.request().getParam("sectionId");
JsonObject j = routingContext.getBodyAsJson();
});
I hope this would solved your problem.
When doing a POST request the data is in the body.
On the server side you need to register a body handler for your router in order to be able to easily get the body from the request. You can do that like this:
final Router router = Router.router(vertex);
// Adding a BodyHandler for routes
router.route().handler(BodyHandler.create());
router.post("/your/endpoint").handler(routingContext -> {
System.out.println(routingContext.getBodyAsString());
});
Another option is to add another callback handler like this:
final Router router = Router.router(vertex);
router.post("/your/endpoint").handler(routingContext -> {
routingContext.request().bodyHandler(body -> {
System.out.println(body.toString());
});
});
data: {"username": 'Bobby'} will fix your issue, and remove the () also you can try to change you ajax request in jquery as follow
var datavar = {username:"someusername"}; //Array
$.ajax({
url : "AJAX_POST_URL",
type: "POST",
data : datavar,
success: function(data, textStatus, jqXHR)
{
alert("success") ;
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("fail") ;
}
});
I'm trying to send a file using websocket connection to my server:
I've implemented the websocket server side using java Spring
the client side is in javaScript
for some reason each time i send a binary message from client side using "blob" or "arraybuffer. the server recognise the message as text message not as binary.
what am i missing here?
Client Side
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chat</title>
</head>
<body>
<h2>File Upload</h2>
Select file
<input type="file" id="filename" />
<br><br><br>
<input type="button" value="Connect" onclick="WebSocketTest()" />
<br><br><br>
<input type="button" value="Upload" onclick="sendFile()" />
<script>
"use strict"
var ws;
function WebSocketTest()
{
if ("WebSocket" in window)
{
console.log("WebSocket is supported by your Browser!");
// Let us open a web socket
ws = new WebSocket("ws://xx.xx.xx.xx:yyyy/service/audioHandler");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send(JSON.stringify({userName:'xxxx',password:'sgdfgdfgdfgdfgdf'}));
console.log("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
console.log("Message is received...");
};
ws.onclose = function()
{
// websocket is closed.
console.log("Connection is closed...");
};
}
else
{
// The browser doesn't support WebSocket
console.log("WebSocket NOT supported by your Browser!");
}
}
function sendFile() {
var file = document.getElementById('filename').files[0];
ws.binaryType = "arraybuffer";
//ws.send('filename:'+file.name);
var reader = new FileReader();
var rawData = new ArrayBuffer();
console.log(file.name);
reader.loadend = function() {
}
reader.onload = function(e) {
rawData = e.target.result;
ws.send(rawData);
console.log("the File has been transferred.")
//ws.send('end');
}
reader.readAsArrayBuffer(file);
}
</script>
</body>
</html>
Server Side
public class WebSocketController extends BinaryWebSocketHandler {
#Autowired
private ApplicationContext applicationContext;
#Autowired
private CallScopeStore callScopeStore;
private static Logger logger = Logger.getLogger(AudioHandler.class);
private static final String STOP_MESSAGE = "stop";
#Override
protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
try {
//do something....
} catch (Exception e) {
logger.error(e, e);
throw new RuntimeException(e);
}
}
#Override
protected void handleTextMessage(final WebSocketSession session, TextMessage message) {
try {
//do something....
}
} catch (Exception e) {
logger.error(e, e);
throw new RuntimeException(e);
}
}
}
You have to send the file as a blob.
ws = new WebSocket("ws://xx.xx.xx.xx:yyyy/service/audioHandler");
ws.binaryData = "blob";
ws.send(message); // Blob object
Probably you can find an error as you mention: "CloseStatus[code=1009, reason=No async message support and buffer too small. Buffer size: [8,192], Message size: [7,816,684]]". That happens because your WebSocket Engine need to be configured to allow binary message with the size you want. For example, in your WebSocketConfig:
#Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
container.setMaxTextMessageBufferSize(500000);
container.setMaxBinaryMessageBufferSize(500000);
return container;
}
As you can see, you can set the maximun size allowed for your text and binary messages, just specify a size bigger than 7,816,684 (the file you was trying to send). By default, your buffer size is [8,192] so if you send a file with a smaller size than your buffer size, there shouldn't be problems. For more information, you can check websocket spring documentation.
#Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
container.setMaxTextMessageBufferSize(500000);
container.setMaxBinaryMessageBufferSize(500000);
return container;
}
WebSocketMessageBroker invalid. #robert08
#Configuration
#EnableWebSocketMessageBroker
public class MyWebSocketMessageBrokerConfigurer implements WebSocketMessageBrokerConfigurer {
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/portfolio").setAllowedOrigins("*");
}
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.setPathMatcher(new AntPathMatcher("."));
config.setApplicationDestinationPrefixes("/app");
config.enableSimpleBroker("/topic", "/queue");
}
#Override
public void configureWebSocketTransport(WebSocketTransportRegistration webSocketTransportRegistration) {
webSocketTransportRegistration
.setMessageSizeLimit(1024 * 1024)
.setSendBufferSizeLimit(1024 * 1024 );
}
}
I am trying to design a Java Servlet for the first time.
This is my final target behavior.
Servlet receives a request.
Servlet makes a HTTP Request to another server (Lets call it MServer).
MServer can asynchronously send replies to my Servlets request within the next 20-25 mins.
I want to send this data back to the user (who made the request to the servlet in step 1) as soon as the Servlet receives this data.
Any idea how I might do this?
As of now I have just made a "Hello World" Java Servlet. Also code to communicate with MServer is ready. But I dont know how can I achieve this asynchronous behavior.
Any help would be greatly appreciated.
I think you should use an asynchronous servlet. I assume there is an MServer facade that looks like this:
interface MServer {
void getStuff(Observer observer);
}
interface Observer {
void onNewStuff(String stuff);
void onThatWasAllStuff();
}
class MServerSingleton {
MServer getInstance() {
// Code that returns an MServer.
}
}
Then you can implement your servlet something like this:
public class TheServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, final HttpServletResponse resp) {
resp.setContentType("text/plain");
final AsyncContext context = req.startAsync();
MServerSingleton.getInstance().getStuff(new Observer() {
void onNewStuff(String stuff) {
try {
resp.getWriter().write(stuff + "\n\n");
resp.getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
void onThatWasAllStuff() {
context.complete();
}
});
}
}
You will likely need to adjust timeouts for this to work.
You might want to consider using Server Sent Events.
Here is a sample hope it helps. It assumes that you have a browser as a client and implements jQuery Ajax call. It checks every 5 seconds if your long running call from Mserver is done and data is available for client to use. I hope it helps you :)
Your servlet code:
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data = Mserver.getInstance().getData();
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println(data);
}
}
Sample Mserver code:
public class Mserver {
private String data;
private static final Mserver mserver = new Mserver();
public static Mserver getInstance() {
return mserver;
}
private Mserver() {
new Thread() {
#Override
public void run() {
computeData();
}
}.start();
}
// Computing data by making multiple server calls etc..
private void computeData() {
try {
System.out.println("Waiting for 20 seconds simulating long running call");
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
data = "Computed Data is ready now.";
}
public String getData() {
return data;
}
}
Html page using jQuery Ajax calls:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="js/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
setInterval(function() {
$.ajax({
type:"get",
url: "checkDataFromMserver",
async: false,
success: function (data) {
$("#response").html(data);
}
});
}, 5000);
});
</script>
</head>
<body>
Getting data using jQuery Ajax
<div id="response"></div>
</body>
</html>
I tested it and it works. The client keeps polling every 5 seconds to check if data is ready. And after 20 seconds it gets it's data from Mserver.
Hope you find it useful!
You will probably have to implement a continuous check on the client's side and a queue on the server side. In other words the client will be contacting the servlet every 1-2 minutes to check for new messages addressed to him. The servlet should also have a method to get the data asynchronously and then store the recieved data in the queue. Implementing such queue can be done in many ways, for example by storing the responses from MServer in a database table.
I would like to call my webservice methods from pure java script code. and that code should work on mozilla browser.
This is my webservice code:
package com.example.core;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
#WebService
public class Area {
#WebMethod
public double square(#WebParam(name="side") double side)
{
return side * side;
}
#WebMethod
public double rectangle(#WebParam(name="length") double length,#WebParam(name="breadth") double breadth)
{
return length * breadth;
}
public static void main(String[] args) {
Area area = new Area();
String url = "http://localhost:8090/area"; // end point of webservice.
System.out.println(url+"?wsdl");
Endpoint.publish(url, area); // publishing the webservice
}
}
Here is my HTML file:
<html>
<head>
<meta content="utf-8" http-equiv="encoding">
<meta content="text/xml;charset=utf-8" http-equiv="Content-Type">
<script language="javascript">
function call()
{
var side = sideid.value;
var side1 = sideid1.value;
var req = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://core.codon.com/\"><soapenv:Body><web:rectangle><length>" + side+ "</length><breadth>" + side1+ "</breadth></web:rectangle></soapenv:Body></soapenv:Envelope>";
//var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
//var reqXML = xmlDoc.loadXML(req);
var xmlDoc=document.implementation.createDocument("", "", null);
xmlDoc.async=false;
xmlDoc.onload = req;
//var reqXML = xmlDoc.load(req);
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
var response = xmlhttp.responseXML;
alert(response.selectSingleNode(".//return").text);
alert("======"+response);
}
}
var soapaction = "http://core.example.com/rectangle";
xmlhttp.open("POST","http://localhost:8090/area?wsdl",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlhttp.setRequestHeader("SOAPAction", soapaction);
xmlhttp.send(req);
}
</script>
</head>
<body>
Side Length: <input type="text" id="sideid"></input>
Length: <input type="text" id="sideid1"></input>
<button onclick="call();">area of square</button>
</body>
</html>
with the above code am getting response as null. The same code working on IE but not in mozilla...
my webservice side am getting the following error
com.sun.xml.internal.ws.transport.http.server.WSHttpHandler handleExchange
WARNING: Cannot handle HTTP method: OPTIONS
Please Help me out..Thanks in advance
I would take SOAP UI, generate web service client, generate example requests, so I don't need to create SOAP envelopes from scratch. Then I would use jQuery to generate AJAX requests with the help of generated SOAP envelopes.
Another approach would be to make use of http://cxf.apache.org/docs/javascript-clients.html - you will have complete JavaScript generated that way.
You are running webservice as stand alone app on port say 'x' and the client might be on another port say 'y'
When you do a post call through y onto x the method will always be changed to options automatically. Internet standards wont allow 'posting' between different servers, I guess.
You will have to find another workaround.