Cannot insert object in Parse.com with parse4j API in JAVA - java

I am using Parse.com for communicating with iOS application and Web Browser. I have registered in parse.com and created an application. Now I have an iOS application ready to insert an object in that application which is working fine. Now comes the backend part, I am using JAVA for web application. Now,
https://parse.com/docs/api_libraries
According to this link, I can see the API/ Libraries I can use in JAVA is
Almonds
mobile-parse-api
Parse4j
ParseFacade
Among this 4, I have selected Parse4j to build web application with.
I am using Eclipse, I have installed GWT plugin, created a web application. Now I am adding this parse4j.jar file to that project, Added it to the build path also. And then I try to write this code
try {
Parse.initialize("my app id", "my rest app id");
ParseObject gameScore = new ParseObject("GameScore");
gameScore.put("score", 1337);
gameScore.put("playerName", "Sean Plott");
gameScore.put("cheatMode", false);
gameScore.save();
return "OK";
} catch(IllegalArgumentException e){
e.printStackTrace();
return "KO";
}
catch(ParseException e){
e.printStackTrace();
return "KO";
}
It doesn't insert the object to parse cloud. Please help why isn't working? Am I missing anything to write?

As far as I see, the code is correct. However, if Parse4j does not save the entry
this means that you write wrong the attribute name or class name. Just check the names
and class name then reply back.
Regards.

One way to validate is the do a Query, get the object and print all the attributes / data types. Then store these as static class level constants and use them throughout your class for setting values in new objects to persist.
If the get query doesn't work (without any filters), which means your class name is incorrect.
Good Luck!

Related

Should I Save token securely in Memory or sqlite? or Please suggest

I started to learn Android few days back and so far I am done with implementing Login Activity, Main Activity which extends abstract Base Activity.
Nav Bar item when clicked opens xml from Fragments.
I have a question about the token that I receive after successful login. This token is being used with each request to get data after successful login. Should I save the token in sqlite database securely or I should make a public property in Main Activity? Main Activity will always remain in memory as this will open fragments.
I can suggest 3 options:
1) you can save the token to the file, something like this:
public static void saveToken(Context ctx, String fileName, Object token) {
if (token == null) {
ctx.deleteFile(fileName);
} else {
ObjectOutputStream out = null;
try {
FileOutputStream fout = ctx.openFileOutput(fileName, 0);
out = new ObjectOutputStream(fout);
out.writeObject(token);
fout.getFD().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Make sure object token implements java.io.Serializable interface.
Usage before API level 24:
saveToken(appContext, someFileName, someTokenObject);
Usage with API level 24 and higher:
saveToken(appContext.createDeviceProtectedStorageContext(), someFileName, someTokenObject);
2) Use SQLCipher library for encrypted database.
3) You can encrypt your token using keystore system https://developer.android.com/training/articles/keystore.html
Use SharedPreferences and make sure you are using Context.MODE_PRIVATE this way only your app can access the data. SharedPreferences is a persistent store
e.g.
SharedPreferences prefs = context.getPreferences(Context.MODE_PRIVATE);
prefs.edit().putString("token", token).apply();
token = prefs.getString("token");
Why not to use SQLite:
SQLite is a database and is targeted at tabular data, a single token does not fit this use case.
Why not store in the main activity:
The main activity will not be around for the lifetime of the application install, it can be cleaned up by the OS at any time. It is not a persistent data store.
Should I save the token in sqlite database securely or I should make a public property in Main Activity? Main Activity will always remain in memory as this will open fragments.
The Official Android documentation already answers your question in the section on called "Best practices for security and privacy". It gives the following statement:
If you have access to user data and can avoid storing or transmitting it, don't store or transmit the data
In other words, if you can avoid persisting then don't persist it.
You mentioned "public property" in your question which makes me wonder if the concept of visibility modifiers is not yet clear. The Java public and private modifiers are for controlling access to the members of your class. They have nothing to do with security as per this answer here.
If you do persist the token in memory, as a public field or otherwise, you may reduce your exposure slightly by storing the token in a char[] rather than a String. That also is detailed in this canonical answer.
Finally, if you do have to store the token, the sqlite database is not the correct place to do it. Instead, you should use the provided KeyStore which will make for more difficult extraction of the token in the case that the device is compromised. The link to the documentation above is complete with code examples. If this proves too difficult to use, there are some wrappers around it including Scytale.
1) Store the token value within the base application singleton (where your application must be an instance of BaseApplication)
public class BaseApplication extends Application {
// token
private String token = null;
public String getToken() {return this.token;}
public void setToken(String token) {this.token = token;}
}
With the implementation above you will be able to set and get the token value from any activity/fragment. However the value is not persistent and it will be lost once the application ends.
Remark: If you are using the token for REST api access then you can store the token in the background service instance using a similar solution as above.
2) Use SharedPreferences - this is recommended way in case you want to store the token's value between application's runs.
Please see the answer from #Ryan.
You can use SharedPreferences to store token.it is available over application.
You can store it in Shared Preference as this one is token.
Now coming to the part of Security You can obviously use encryption for the shared preference.
There are already lots of open items available you can use below library for example
https://github.com/ophio/secure-preferences
Regarding keys that are in your java file to encrypt, You need to be sure you are applying proguard before you upload it to playstore.
In that manner now your token is fully secure with shared preferences.
In order to save it in sqlite than by decoding or root access your db file can also be accessed same as preferences. Regarding clear data from setting I think it will delete your sqlite data as well. Not sure about this though.
I hope it will help you out.
Better to use Sqlite or Realm. And store in Application memory and not in external memory. As for data residing in application memory we don't need to worry much about security. Saving in MainActivity is not a good solution, as once application closes, this will get cleared.
Storing in Shared Preference is also an option. But if user clears the cache from setting's this value will also get cleared. Realm Android Reference Link

Generating java POCOs and populating them by reading json file, all dynamically

I am new to Android app development and I am stuck at a point where in my app I need to dynamically create class, define its attributes and populate them all dynamically.
This dynamic thing is required because the json file changes every time, a click event is fired and I need to populate a recyclerView, getting header and respective values from that json file.
I have come across few solutions like using javassist library and using hashmap (though I didn't get this one).
Okey I found it.
You want to parse the JSONObject at runtime and get its keys. And you don't know what structure the JSONObject would have.
Just use this Json helper class JSON HELPER
To convert JSONObject use JsonHelper.toMap(JSONObject object) given there.
//Now to get the keys
for ( String key : hashMapObject.keySet() ) {
System.out.println( key );
}
//Here hashMapObject is generated from `JsonHelper.toMap` method.
Just use Retrofit library and everything will get handled automatically and very easily Retrofit
Just follow these steps to use Retrofit
First Download and Integrate Retrofit to your android project.
//In your Gradle file. Add this line.
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
Now suppose you want to implement a Get request from a URL lets say
https://api.github.com/users/{user}/repos.
To get all the repository listed on GitHub. Here {user} will be username
So your base URL here is https://api.github.com and path for
Get Is /users/{user}/repos
Now create an interface.
public interface GitHubService {
#GET("/users/{user}/repos")
Call<List<Repo>> listRepos(#Path("user") String user);
}
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com").build();
GitHubService service = retrofit.create(GitHubService.class);
//Each Call from the created GitHubService can make a synchronous or asynchronous HTTP request to the remote webserver.
Call<List<Repo>> repos = service.listRepos("robinskumar73");

Using Telegram API for Java Desktop App?

I am not that new to Java Programming, but I have never worked with external libraries etc. Now I want to develop a desktop client for the "Telegram" open-source messaging platform, and I'm stuck when it comes to API-Usage.
There is pretty much documentation about the Telegram API, found at https://core.telegram.org/api, and I've already downloaded mtproto, telegram-api and tl-core from github, and compiled my own library jar from source by using gradle. As well, I've already written a small application, where the user clicks a button and is promted to enter his phone number, I'm using the Java-swing-Libraries and an ActionListener for this.
The phone number entered by the user should now be checked if it is already registered, the auth.checkPhone method seems to be capable for that. But how can I refer to it within my eclipse project? I don't see any method "checkPhone" in any of the classes! What should I do?
Please help me, I can't help myself and I am desperately stuck in my project. Even a small hint would help.
Thanks in Advance,
Lukas
Essentially you will have to fill out the blanks in the code given on GitHub in the ex3ndr/telegram-api repository. If you've got the library Jar file you built and the tl-api-v12.jarfile on your Eclipse project's Java build path, then look at the RPC Calls section of the README and
First you need to set up an AppInfo object with your API credentials, then you will also have to create some new classes that implement the AbsApiState and ApiCallback interfaces. Once these are available, you can create the TelegramApi object and make an RPC call to the Telegram service as follows; in this case using the suggested auth.checkPhone method:
// TODO set up AbsApiState, AppInfo and ApiCallback objects
TelegramApi api = new TelegramApi(state, appInfo, apiCallback);
// Create request
String phoneNumber = "1234567890";
TLRequestAuthCheckPhone checkPhone = new TLRequestAuthCheckPhone(phoneNumber);
// Call service synchronously
TLCheckedPhone checkedPhone = api.doRpcCall(checkPhone);
boolean invited = checkedPhone.getPhoneInvited();
boolean registered = checkedPhone.getPhoneRegistered();
// TODO process response further
The TelegramApi object represents your connection to the remote service, which is a request response style of API. RPC calls are made via the doRpcCall method, which takes a request object from the org.telegram.api.requests package (the TLRequestAuthCheckPhone type in the example) filled in with the appropriate parameters. A response object (TLCheckedPhone above) is then returned with the result when it is available.
In the case of an asynchronous call the method returns immediately, and the onResult callback method is executed when the result is available:
// Call service aynchronously
api.doRpcCall(checkPhone, new RpcCallbackEx<TLCheckedPhone>() {
public void onConfirmed() { }
public void onResult(TLCheckedPhone result) {
boolean invited = checkedPhone.getPhoneInvited();
boolean registered = checkedPhone.getPhoneRegistered();
// TODO process response further
}
public void onError(int errorCode, String message) { }
});
Or just look at this API https://github.com/pengrad/java-telegram-bot-api
It is really simple to use

html5 local database access with selenium

I been asked to make a selenium test that checks the local database of html5 and verify that the information in there matches what's being displayed on the screen. This is for a mobile application that can be used on chrome I have everything working as far as selenium working with chrome.Now I am just stuck on trying to find a method that can be used for with selenium that will access the local database storage. There's a interface in selenium html5 packages that DatabaseStorage however I can not figure out how that works or how to use it. The test cases are being written in Java. Thank you all for any help you can provide on this.
I have tried to create a new object of the database storage. which dident work i tried creating a new object of result set also tried doing implements database storage. in the API for database storage it says it a interface but it dose not list a constructor. i not sure how to access a method when there's no constructor for the interface.
// Database Storage
private ResultSet executeQuery(String statement, String... param) {
String databaseName = "'HTML5', '1.0',"
+" 'Offline document storage', 100*1024";
return ((DatabaseStorage) driver).executeSQL(databaseName, statement, (Object[]) param);
}
see Selenium's HTML5 test for more details.

Google Calendar

I'm developing one web application project using java for education industry.In this Admin have all rights to access the google services of other users like A,B,C..... for this is use OAuth.Then i tried Admin want to share user A's calendar to user B using OAuth.But i got stuck in this step. Is it possible Plz Help me
Thanks
Regards
Sharun
I believe you want to use Access Control Lists (ACLs), see the docs. The Java example code at this URL for the task you mention is pretty simple:
AclEntry entry = new AclEntry();
entry.setScope(new AclScope(AclScope.Type.USER, "jdoe#gmail.com"));
entry.setRole(CalendarAclRole.READ);
URL aclUrl =
new URL("http://www.google.com/calendar/feeds/jo#gmail.com/acl/full");
AclEntry insertedEntry = service.insert(aclUrl, entry);
and what it does is, and I quote:
This code allows jdoe#gmail.com to
have read-only access to
jo#gmail.com's calendar.
There's more where this came from (e.g., upgrading a user's role in an ACL above the read-only access granted in this example), and I think it's a good idea to read the whole page.

Categories