Protocol between parse.com and mobile app - json

*What is the protocol between parse.com backend and mobile app when using Android/IOS SDK?
For example in the following code how parseobject is returned? Over http as json(Rest), via socket , rpc etc..?
ParseQuery<ParseObject> query = ParseQuery.getQuery("GameScore");
query.fromLocalDatastore();
query.getInBackground("xWMyZ4YEGZ", new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
// object will be your game score
} else {
// something went wrong
}
}
});
*If it is not rest what is the pros of method over REST?

It does use the Parse REST API, which sends JSON data over HTTPS.
The client SDKs provide a nice, native, helpful experience. For the platforms we don't support first-party, the REST API is available directly.

Related

Dynamic parameter as part of request URI with Apache HttpCore

I am looking for existing solutions to match dynamic parameters with HttpCore. What I have in mind is something similar to constraints in ruby on rails, or dynamic parameters with sails (see here for example).
My objective is to define a REST API where I could easily match requests like GET /objects/<object_id>.
To give a little bit of context, I have an application that creates an HttpServer using the following code
server = ServerBootstrap.bootstrap()
.setListenerPort(port)
.setServerInfo("MyAppServer/1.1")
.setSocketConfig(socketConfig)
.registerHandler("*", new HttpHandler(this))
.create();
And the HttpHandler class that matches the requested URI and dispatches it to the corresponding backend method:
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ROOT);
// Parameters are ignored for the example
String path = request.getRequestLine().getUri();
if(method.equals("POST") && path.equals("/object/add") {
if(request instanceof HttpEntityEnclosingRequest) {
addObject(((HttpEntityEnclosingRequest)request).getEntity())
}
[...]
For sure I can replace path.equals("/object/add") by something more sophisticated with RegEx to match these dynamic parameters, but before doing so I'd like to know if I am not reinventing the wheel, or if there is an existing lib/class I didn't see in the docs that could help me.
Using HttpCore is a requirement (it is already integrated in the application I am working on), I know some other libraries provide high-level routing mechanisms that support these dynamic parameters, but I can't really afford switching the entire server code to another library.
I am currently using httpcore 4.4.10, but I can upgrade to a newer version of this might help me.
At present HttpCore does not have a fully featured request routing layer. (The reasons for that are more political than technical).
Consider using a custom HttpRequestHandlerMapper to implement your application specific request routing logic.
final HttpServer server = ServerBootstrap.bootstrap()
.setListenerPort(port)
.setServerInfo("Test/1.1")
.setSocketConfig(socketConfig)
.setSslContext(sslContext)
.setHandlerMapper(new HttpRequestHandlerMapper() {
#Override
public HttpRequestHandler lookup(HttpRequest request) {
try {
URI uri = new URI(request.getRequestLine().getUri());
String path = uri.getPath();
// do request routing based on the request path
return new HttpFileHandler(docRoot);
} catch (URISyntaxException e) {
// Provide a more reasonable error handler here
return null;
}
}
})
.setExceptionLogger(new StdErrorExceptionLogger())
.create();

Xamarin Forms: ModernHttpClient errorhandling in PCL

My app connects to an api which requires an HTTPS-connection.
ModernHttpClients (NativeMessageHandler) works fine until an exception is thrown...
When there is no wifi available, an UnknownHostException is thrown on Android. Is it possible to make a catch that works on both Android and iOS? UnknownHostException is in the Java.Net library which can't be used in the iOS project.
You can use Xam.Plugin.Connectivity NuGet Package to Check Network Connectivity In Xamarin.Forms using following code
if (CrossConnectivity.Current.IsConnected) {
// your logic...
} else {
// write your code if there is no Internet available
}
OR
Refer http://www.c-sharpcorner.com/blogs/how-to-check-network-connectivity-in-xamarinforms
You can use the ConnectivityPlugin in your shared Xamarin Forms code to check for an internet connection before doing your request.
Personally I'm using a cross platform interface to handle network errors. You can for instance have something like (using MvvmCross in this example):
try
{
var client = new HttpClient();
var result = await client.GetAsync("http://some-url.com");
}
catch (Exception e)
{
var platformErrorChecker = Mvx.Resolve<IPlatformNetworkError>();
if (platformErrorChecker.IsNetworkError(e))
{
// Handle network error
}
else
{
// Other exception, just throw
throw;
}
}
And a service defined as:
public interface IPlatformNetworkError
{
bool IsNetworkError(Exception e);
}
Which you implement on each platform specifically, or only where needed. This is a simple example of course, you can have each platform provide more information about their specific network errors.

Should a server always send a JSON object as an http response?

I'm working on a node.js server using express and a android native app, using Retrofit 1.9.
For a login API that returns only a true/false answer to the client, should JSON still be used?
As I see it, the server has only to send a status code response:
if(isLegal) {
res.sendStatus(200);
dbConnector.updateUser(token);
}
else{
console.log('Token is not legal');
res.sendStatus(403);
}
But the Retrofit framework tries to convert the response to JSON, which makes me think I must send a JSON object with the answer, though it seems weird.
My retrofit restClient:
public class RestClient {
private static final String URL = SessionDetails.getInstance().serverAddress;
private retrofit.RestAdapter restAdapter;
private ServerAPI serverAPI;
public RestClient() {
restAdapter = new retrofit.RestAdapter.Builder()
.setEndpoint(URL)
.setLogLevel(retrofit.RestAdapter.LogLevel.FULL)
.build();
serverAPI = restAdapter.create(ServerAPI.class);
}
public ServerAPI getService() {
return serverAPI;
}
}
And usage:
restClient.getService().login(token.getToken(), token.getUserId(), new Callback<Void>() {
#Override
public void success(Void aVoid, Response response) {
Log.d("Chooser", "Successful login on server.");
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
Log.d("Chooser", "Login failed on server.");
}
});
Using it as it is results with the following error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING
There are many topics on this issue but no certain answer about the correct (or better) method to use.
Any ideas about the best implementation in these cases?
Sending an empty body with your HTTP response is perfectly legal and some clients may care only about the response status but some clients may expect to get a response so sending a body never hurts and sometimes may be useful.
You can include a JSON response in addition to the HTTP response status:
// Express 4.x:
res.status(403).json({error: 'Token is not legal'});
// Express 3.x:
res.json(403, {error: 'Token is not legal'});
Such an error message can be very useful for the client development. You can get 403 for many reasons, illegal token, expired token, a legal not expired token but for the wrong user that doesn't have some privilege - adding a specific error message in addition to the HTTP response code can tell the client what exactly went wrong and allows the client-side code to show a better error message to the user.
Also, note that true and false are also valid JSON.

Why use JSNI and overlay types to represent the JSON object returned from the server in GWT project?

I was reading the link: http://www.gwtproject.org/doc/latest/tutorial/JSON.html and found that the JSNI and overlay types are used to decode the JSON data from the server side.
// Send request to server and catch any errors.
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
displayError("Couldn't retrieve JSON");
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
updateTable(JsonUtils.<JsArray<StockData>>safeEval(response.getText()));
} else {
displayError("Couldn't retrieve JSON (" + response.getStatusText()
+ ")");
}
}
});
} catch (RequestException e) {
displayError("Couldn't retrieve JSON");
}
Why does it use the JsonUtils.>safeEval(response.getText()) to decode the JSON data? Does it have to do so? Is this the only way to receive the JSON data when using GWT?
No this is not the only way. However, JsonUtils.safeEval will either make use of the browser's built-in (i.e. native, so assumed to be the fastest way to do it) JSON.parse() (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse for more details), which will turn a JSON string into a JavaScript Object.
In turn, overlay types let you write Java code which directly maps to a JavaScript object, making it very simple and easy to talk about the underlying JS data, from your normal Java code.
Of course there are other options as well, off the top of my head, you can use JSONObject class in the com.google.gwt.json.client package - this still does the JSON.parse() call, but then exposes data through a map- and list-like structure for your Java code. Additionally, AutoBeans make it possible to declare interfaces that describe the structure of the data, and read from the JSON string (or a JavaScript object) into those interfaces - it lets your code behave more like Java with built-in collections and such, at the cost of some performance to translate back and forth.

NServiceBus without input queue

Is it possible to use NServiceBus in an application without having any input queues?
Reason is, I have an ASP.NET MVC application that sends messages to other applications when something happens (e.g. a new user registers). The web application never recieves any responses or other messages and therefore I would like not to bog the app. with the msmq peeking which throws an exception every second.
That is supported, just remove the msmstranport config section and all should be fine. This works against 2.0.1281.0 (net4) version of NServiceBus with no app.config present
using NServiceBus;
namespace SendOnlyEndpoint.Custom
{
public class Program
{
static void Main(string[] args)
{
var bus = Configure.With()
.DefaultBuilder()
.XmlSerializer()
.MsmqTransport()
.UnicastBus()
.CreateBus()
.Start();
bus.Send("SendOnlyDestination",new TestMessage());
}
}
public class TestMessage : IMessage
{
}
}
More info on send only endpoints here
I would try not configuring an input queue. Bus.Send will use an internal outbound queue to send messages.