RPC call to external server - google-app-engine

I am a new bie on GWT, I wrote an application on abc.com, I have another application i.e. xyz.com, xyz.com?id=1 provides me a data in json format, I was thinking to find a way that how to get that json file in abc.com via RPC call, because I have seen tutorials in which RPC calls are used to get data from its server. any help will be appreciated.
EDIT
I am trying to implement this in this StockWatcher tutorial
I changed my code slightly change to this
private static final String JSON_URL = "http://localhost/stockPrices.php?q=";
AND
private void refreshWatchList() {
if (stocks.size() == 0) {
return;
}
String url = JSON_URL;
// Append watch list stock symbols to query URL.
Iterator iter = stocks.iterator();
while (iter.hasNext()) {
url += iter.next();
if (iter.hasNext()) {
url += "+";
}
}
url = URL.encode(url);
MyJSONUtility.makeJSONRequest(url, new JSONHandler() {
#Override
public void handleJSON(JavaScriptObject obj) {
if (obj == null) {
displayError("Couldn't retrieve JSON");
return;
}
updateTable(asArrayOfStockData(obj));
}
});
}
before when I was requesting my url via RequestBuilder it was giving me an exception Couldn't retrieve JSON but now JSON is fetched and status code is 200 as I saw that in firebug but it is not updating on table. Kindly help me regarding this.

First, you need to understand the Same Origin Policy which explains how browsers implement a security model where JavaScript code running on a web page may not interact with any resource not originating from the same web site.
While GWT's HTTP client and RPC call can only fetch data from the same site where your application was loaded, you can get data from another server if it returns json in the right format. You must be interacting with a JSON service that can invoke user defined callback functions with the JSON data as argument.
Second, see How to Fetch JSON DATA

Related

Download file from api in ReactJs

I have ASP.NET Core MVC back-end api. One controller returns File from server. Is there a way to make request to api route by [href] attribute of <a> tag? Looks like it tries to call React route but not make a request to server.
Also I made AJAX call to that controller and got back file as a string (screenshot is attached). Why is it a string, shouldn.t it be a byte array? How to build back file from that string? (it's a .pdf file). I have an empty PDF if use JavaScript new File([], 'name', {options}).
ASP.NET Core controller returns PDF this way:
return PhysicalFile(Path.GetFullPath(relativePath), "application/pdf", reportName);
In React I receive it as a string this way:
let stringPDFBinary = await ReportService.getReport(id, reportFileName)
I just need to download file from api by any way.
So, the answer is here: PDF is blank when downloading using javascript
The same problem. Let it be one more topic, easier to find for others. The AJAX response is encoded string. In request config set 'responseType = 'arraybuffer'' somehow and receiving pdf will not be blank. Solved.
I Just copied and pasted from the code source. The problem seems to be the same that i had:
Asp net controller:
[HttpGet]
[Route("File")]
[AllowAnonymous]
public IActionResult GetFile(string key)
{
var file = (FileCacheValue)_fileCache.Cache[key.Replace(" ", "+")];
if (file == null)
return NotFound();
Response.Headers["content-disposition"] = $"inline;filename={file.Name}.pdf";
return File(file.Data, "application/pdf");
}
In this case comes from a cache system. The data is a byte array.
Front-end React:
const onClick = () =>
{
window.open(pdfByteArray, '_blank', 'fullscreen=yes');
}
Exactly what i have. I just put the data on a new window and open the pdf.
The Ajax part is straight forward, get the value from the response and set it on a variable

Spring React and Sessions.. how to keep session

I have set up my spring to maintain a HTTP session on an object like so:
#Component
#SessionScope
public class Basket { .. }
controller:
#PostMapping(path="/basket/addItem/{user}", consumes = "application/json", produces = "application/json")
public Basket createBasket(#PathVariable String user, #RequestBody Item item) {
System.out.println("POSTING..................................");
return basketService.addItem(user, item);
}
now when i use a REST client, in firefox i can see that the session bean is created and maintained for the duration - multiple calls. I can append to the object. If i try another client, it gets its own session with its own bean. great..
spring logs the following:
Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [269] milliseconds.
However im trying to create a basic front end in react, when react makes a request using axios it gets a new bean every time, which means that the session must be ending after each call. IS that correct? or im not tying it to the react application...
Maybe the approach im taking is not correct, maybe i should use a a different approach, Im trying to learn about spring boot, so its a basic project... and right now i want to maintain user session for a cart. so subsequent calls i can append to the object...
by adding the following to my controller it all began to work.
#CrossOrigin(origins = { "http://localhost:3000" }, allowedHeaders = "*", allowCredentials = "true")

Connecting asp.net core web api to asp.net-mvc5 project

I am trying to connect asp.net core web api(thats already connected to my local sqlserver and working fine) to my asp.net-mvc5 web app so when the controller is called it fetches the data from database using API
Now, this is how I'm trying to connect the api in my asp.net mvc project, shown below is homeController:
namespace AptitudeTest.Controllers
{
public class HomeController : Controller
{
string Baseurl = "http://localhost:51448";
public async Task<ActionResult> Index()
{
List<Teacher> teacher = new List<Teacher>();
//Teacher t1 = new Teacher();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource GetAllEmployees using HttpClient
HttpResponseMessage Res = await client.GetAsync("api/Admin/Get");
//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var EmpResponse = Res.Content.ReadAsStringAsync().Result;
//Deserializing the response recieved from web api and storing into the Employee list
teacher = JsonConvert.DeserializeObject<List<Teacher>>(EmpResponse);
}
//returning the employee list to view
return View(teacher);
}
}
I expect it to return me teachers as json objects but this is the error im getting:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[AptitudeTest.Teacher]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[AptitudeTest.Models.Teacher]'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List1[AptitudeTest.Teacher]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[AptitudeTest.Models.Teacher]'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
The error you are getting is:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[AptitudeTest.Teacher]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[AptitudeTest.Models.Teacher]'.
which means your view expects different model object as input while the passed object is of different type. It looks like that you have in view defined model as:
IEnumerable<Teacher>
while you are returning a List<Teacher>. Either change in view it to List<Teacher> like:
#model List<Teacher>
or return an IEnumerable<Teacher> object from the controller action.
for that you can write the following:
IEnumerable<Teacher> teachers = teacher;
return View(teachers );
Either way you should be able to resolve the error and keep moving.
EDIT:
didn't noticed that there are two different classes in different namespace, one is AptitudeTest.Teacher and other is AptitudeTest.Models.Teacher. the class which we have defined the view should be same which is passed from the action method. Right now there are two classes each in different namespace.

Return a response and file via servicestack

I am working on a project where we have a database and a separate file system both stored on the same server and are accessed through service stack requests and responses.
The database contains the relevant metadata for a given file in the file system and as such we would like to be able to retrieve and store these files and documents simultaneously to prevent orphaned data.
Is is possible to return both a stream of data (file) and a response DTO in the same response? Similar to how JsonServiceClient.PostFileWithRequest allows for both a file and request DTO to be passed to the server. If it is possibly how would it be handled on both the server and client sides?
In my research so far most applications appear to just return either a response document or a stream and mostly through the use of HttpResult.
Thanks in advance!
There's no support for MIME Multipart/mixed responses which is primarily for Email and rarely supported and used for HTTP. The easiest way to send additional metadata with your File download response is to use HTTP Headers, e.g:
return new HttpResult(fileInfo) {
Headers = {
{"X-key", "value"}
}
};
Another option would be to embed the contents of the file inside a DTO:
class FileResponseWithMetadata
{
public byte[] Data { get; set; }
public string Key { get; set; }
}
For returning multiple files you'd need to zip the files using a library like DotNetZip and return that instead.

Returning multiple items with Servlet

Good day, I'm working on a Servlet that must return a PDF file and the message log for the processing done with that file.
So far I'm passing a boolean which I evaluate and return either the log or the file, depending on the user selection, as follows:
//If user Checked the Download PDF
if (isDownload) {
byte[] oContent = lel;
response.setContentType("application/pdf");
response.addHeader("Content-disposition", "attachment;filename=test.pdf");
out = response.getOutputStream();
out.write(oContent);
} //If user Unchecked Download PDF and only wants to see logs
else {
System.out.println("idCompany: "+company);
System.out.println("code: "+code);
System.out.println("date: "+dateValid);
System.out.println("account: "+acct);
System.out.println("documentType: "+type);
String result = readFile("/home/gianksp/Desktop/Documentos/Logs/log.txt");
System.setOut(System.out);
// Get the printwriter object from response to write the required json object to the output stream
PrintWriter outl = response.getWriter();
// Assuming your json object is **jsonObject**, perform the following, it will return your json object
outl.print(result);
outl.flush();
}
Is there an efficient way to return both items at the same time?
Thank you very much
HTTP protocol doesn't allow you to send more than one HTTP response per one HTTP request. With this restriction in mind you can think of the following alternatives:
Let client fire two HTTP requests, for example by specifyingonclick event handler, or, if you returned HTML page in the first response, you could fire another request on window.load or page.ready;
Provide your for an opportunity of choosing what he'd like to download and act in a servlet accordingly: if he chose PDF - return PDF; if he chose text - return text and if he chose both - pack them in an archive and return it.
Note that the first variant is both clumsy and not user friendly and as far as I'm concerned should be avoided at all costs. A page where user controls what he gets is a much better alternative.
You could wrap them in a DTO object or place them in the session to reference from a JSP.

Resources