GWT: unable to access xml - http

I'm trying to access a XML file from client side in GWT. But it looks like the sendRequest method is not getting fired at all.
I'm able to see the xml in the browser. Do I need to do any thing in the server side?
Any help is appreciated.
Here's my code
String xmlurl = "http://localhost:8888/test.xml";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(xmlurl));
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
System.out.println(exception);
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
System.out.println(response.getText());
} else {
System.out.println(response.getStatusCode());
}
}
});
} catch (RequestException e) {
System.out.println("exception"+e);
}
I tried the following code too, but have the same problem. The developer tool shows response status as 200 and correct response text. Only, its not working in the code.
String xmlurl = "http://127.0.0.1:8888/test.xml";
httpGetFile(xmlurl, new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
xmlData = "Error";
}
public void onSuccess(String xmlText) {
xmlData = xmlText;
}
});
public static void httpGetFile(final String url, final AsyncCallback<String> callback) {
final RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, url);
rb.setCallback(new RequestCallback() {
public void onResponseReceived(Request request, Response response) {
try {
System.out.println("dafadfdf");
final int responseCode = response.getStatusCode() / 100;
if (url.startsWith("file:/") || (responseCode == 2)) {
callback.onSuccess(response.getText());
} else {
callback.onFailure(new IllegalStateException("HttpError#" + response.getStatusCode() + " - " + response.getStatusText()));
}
} catch (Throwable e) {
callback.onFailure(e);
}
}
public void onError(Request request, Throwable exception) {
callback.onFailure(exception);
}
});
try {
rb.send();
} catch (RequestException e) {
callback.onFailure(e);
}
}

Always Use logging instead of System.out.print statements https://developers.google.com/web-toolkit/doc/latest/DevGuideLogging
Step 1 - Add logging statements to failure, success and try catch statements. Clean up the exception.
Step 2 - "Parsing the XML" should be done inside the "onSuccess" method of the rb callback.

You do not need a RequestBuilder at all to access an XML file. You can use an ExternalTextResource for this:
https://developers.google.com/web-toolkit/doc/latest/DevGuideClientBundle#TextResource

Related

Send Data to HTML Template through Spring AOP?

I'd like to wrap all the controller methods using Spring AOP for Error Handling.
But, How to send e.getMessage() in catch block to ${errorMessage} in error.html properly?
Thanks for the response!
#Pointcut("within(com.test.mvc.controller.*) && #within(org.springframework.stereotype.Controller)")
public void controllerLayer() {
}
#Pointcut("execution(public String *(..))")
public void publicMethod() {
}
#Pointcut("controllerLayer() && publicMethod()")
public void controllerPublicMethod() {
}
#Around("controllerPublicMethod()")
public String processRequest(ProceedingJoinPoint joinPoint) {
try {
return (String) joinPoint.proceed();
} catch (Throwable e) {
LOGGER.info("{}", e.getMessage());
return "error.html";
}
}
<body>
<h1>Something went wrong!</h1>
<h3 th:text="'Error Message: ' + ${errorMessage}"></h3>
</body>
Following aspect can set the request attribute to display errorMessage.
#Around("controllerPublicMethod()")
public Object processRequest(ProceedingJoinPoint joinPoint) {
Object object=null;
try {
object = joinPoint.proceed();
} catch (Throwable e) {
RequestContextHolder.getRequestAttributes().setAttribute("errorMessage",e.getMessage(),0); // scope 0 - request , 1 - session
return "error.html";
}
return object;
}
I recommend you please explore the possibilities of #ControllerAdvice

Circuit Breaker with gRPC

In a REST service adding a circuit breaker with hystrix, I could do the following:
#HystrixCommand(fallbackMethod = "getBackupResult")
#GetMapping(value = "/result")
public ResponseEntity<ResultDto> getResult(#RequestParam("request") String someRequest) {
ResultDto resultDto = service.parserRequest(someRequest);
return new ResponseEntity<>(resultDto, HttpStatus.OK);
}
public ResponseEntity<ResultDto> getBackupResult(#RequestParam("request") String someRequest) {
ResultDto resultDto = new ResultDto();
return new ResponseEntity<>(resultDto, HttpStatus.OK);
}
Is there something similar I can do for the gRPC call?
public void parseRequest(ParseRequest request, StreamObserver<ParseResponse> responseObserver) {
try {
ParseResponse parseResponse = service.parseRequest(request.getSomeRequest());
responseObserver.onNext(parseResponse);
responseObserver.onCompleted();
} catch (Exception e) {
logger.error("Failed to execute parse request.", e);
responseObserver.onError(new StatusException(Status.INTERNAL));
}
}
I solved my problem by implementing the circuit-breaker on my client. I used the sentinel library
To react on exceptions ratio for example I added this rule:
private static final String KEY = "callGRPC";
private void callGRPC(List<String> userAgents) {
initDegradeRule();
ManagedChannel channel = ManagedChannelBuilder.forAddress(grpcHost, grpcPort).usePlaintext()
.build();
for (String userAgent : userAgents) {
Entry entry = null;
try {
entry = SphU.entry(KEY);
UserAgentServiceGrpc.UserAgentServiceBlockingStub stub
= UserAgentServiceGrpc.newBlockingStub(channel);
UserAgentParseRequest request = UserAgentRequest.newBuilder().setUserAgent(userAgent).build();
UserAgentResponse userAgentResponse = stub.getUserAgentDetails(request);
} catch (BlockException e) {
logger.error("Circuit-breaker is on and the call has been blocked");
} catch (Throwable t) {
logger.error("Exception was thrown", t);
} finally {
if (entry != null) {
entry.exit();
}
}
}
channel.shutdown();
}
private void initDegradeRule() {
List<DegradeRule> rules = new ArrayList<DegradeRule>();
DegradeRule rule = new DegradeRule();
rule.setResource(KEY);
rule.setCount(0.5);
rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);
rule.setTimeWindow(60);
rules.add(rule);
DegradeRuleManager.loadRules(rules);
}

Android Retrofit 2.0: no response to HTTP call

I am an Android developer, I am working with Retrofit. The first day I had a response but the second day the response did not come, why I will working after I can uninstall and install the app then only it will work why, how to I resolve it please help me...
private void HomeWorks() {
HomeWorkApi homeWorkApi =
MissReportServer.getClient().create(HomeWorkApi.class);
Call<VrrittamResponse<ArrayList<HomeWork>>> call =
homeWorkApi.getHomeWork(access_token);
call.enqueue(new Callback<VrrittamResponse<ArrayList<HomeWork>>>() {
#Override
public void onResponse(Call<VrrittamResponse<ArrayList<HomeWork>>> call, Response<VrrittamResponse<ArrayList<HomeWork>>> response) {
try {
ArrayList<HomeWork> homeWork = response.body().getContent();
if (homeWork != null && !homeWork.isEmpty()) {
recyclerView.setAdapter(new HomeWorkAdapter(homeWork,
R.layout.list_item_homework, getActivity()));
}
else {
ExceptionHandle.alertDialogNotShow(getActivity());
}
}
catch (Exception ex){
ExceptionHandle.alertDialogNotShow(getActivity());
}
}
#Override
public void onFailure(Call<VrrittamResponse<ArrayList<HomeWork>>> call, Throwable t) {
Log.e("TAG",t.getMessage());
ExceptionHandle.alertDialogShow(getActivity());
}
});
}

Why cant change textbox text in client function SignalR

I just start testing signalr and I am trying to add text to a rich text box after I got a response from my HUB class , but it doesn't work (no text is shown in my richtextbox) I don't know why...(the code run with no errors)
//server
public class ConnectByHub : Hub
{
public void testFunc(mas) {
string ans = mas + " got it";
Clients.All.testFunc(ans);
} }
//Client
private async void connectToServer()
{
Connection = new HubConnection(LocalClient);
HubProxy = Connection.CreateHubProxy("ConnectByHub");
try
{
await Connection.Start();
}
catch (Exception ex)
{
return;
}
string msg = "Hello friend!";
HubProxy.Invoke("testFunc", (msg)).Wait();
// Option one - doesn't work
HubProxy.On<string>("testFunc", (param) => Invoke((Action)(() => { MsgTxtBox.Text = "something happened"; })));
//Option two - doesn't work
HubProxy.On<string>("testFunc", (param) => this.Invoke((Action)(() => { MsgTxtBox.AppendText("Something happend " + Environment.NewLine); })));
}
I think part of the problem is trying to send a message from the same Async method (connectToServer) in which your listener is running.
I mostly used the same code from the question but moved a couple things around:
Moved HubProxy.Invoke() out of the Async method and called it from a button_click event
Called string.format() on the parameter
SERVER:
public class ConnectByHub : Hub
{
public void Send(string message)
{
Clients.All.testFunc(message);
}
}
CLIENT:
// Added button event
private void button1_Click(object sender, EventArgs e)
{
string msg = "Hello friend!";
HubProxy.Invoke("Send", msg).Wait();
}
private async void ConnectToServerAsync()
{
Connection = new HubConnection(LocalClient);
HubProxy = Connection.CreateHubProxy("ConnectByHub");
// Put the parmater in string.format()
HubProxy.On<string>("testFunc", (param) => this.Invoke((Action)(() => MsgTxtBox.AppendText(string.Format("{0}", param)))));
try
{
await Connection.Start();
}
catch (Exception ex)
{
richTextBox1.AppendText(string.Format("Unable to Connect to server ({0})", ServerURI));
return;
}
}

text/event-stream render in grails from scratch(without plugin)

To use push method , we use the famous JS object EventSource :
This is the client part which is easy to develop it :
var eventSource = new EventSource("controller/action");
eventSource.onmessage = function(event) {
document.getElementById('foo').innerHTML = event.data;
};
However , i get difficulty to configure push method in server part(Grails) .
When , i peek in JEE app developped by Servlets , i can see that the server part is as following :
http://viralpatel.net/blogs/html5-server-sent-events-java-servlets-example/
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//content type must be set to text/event-stream
response.setContentType("text/event-stream");
//encoding must be set to UTF-8
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
for(int i=0; i<10; i++) {
writer.write("data: "+ System.currentTimeMillis() +"\n\n");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
writer.close();
}
}
To convert this servlet to action controller :
def push(){
render(contentType:'text/event-stream',characterEncoding:'UTF-8'){
[dt:"data: "+ System.currentTimeMillis() +"\n\n"]
}
}
and in client part :
var eventSource = new EventSource(baseURL+"external/push");
eventSource.onmessage=function(e){
console.log(e.data.dt);
}
Unfortunately, i don't get any result at console .
I'm not sure if the render method will handle 'text/event-stream' correctly, but you have direct access to the response object in the action:
def push() {
//content type must be set to text/event-stream
response.setContentType("text/event-stream");
//encoding must be set to UTF-8
response.setCharacterEncoding("UTF-8");
for(int i=0; i<10; i++) {
response.outputStream.write("data: "+ System.currentTimeMillis() +"\n\n");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
response.outputStream.flush()
}
def push = {
response.setContentType("text/event-stream");
for(def i=0;i<10;i++) {
render("data $i: ${System.currentTimeMillis()}\n");
sleep(1000)
}
}

Resources