Codename One - Json in Dropbox 2 - java

I am using firebase to send Json thru my CN1 app. This is my code and it's working fine, but I want to send the stuff to Dropbox instead and I just can't make it work. (I already got my token, key and secret from their site)
Could you please tell me what I need to change in order to be able to upload my stuff into Dropbox?
#Override
protected void onPrincipal_ButtonJsonAction(Component c, ActionEvent event) {
final String data = Result.fromContent(hashtableWithInfo).toString();
String firebase = "https://fire-game-258.firebaseio.com/example.json";
ConnectionRequest request = new ConnectionRequest() {
#Override
protected void buildRequestBody(OutputStream os) throws IOException {
os.write(data.getBytes("UTF-8"));
}
};
request.setUrl(firebase);
request.setPost(true);
request.setHttpMethod("POST");
request.setContentType("application/json");
NetworkManager.getInstance().addToQueueAndWait(request);
}
Many many many thanks.

Firebase and Dropbox are completely different API's and need to go thru completely different processes. Saving a file to dropbox requires an OAuth process for the specific user whereas firebase is a global API.
I would recommend you look at parse which more closely resembles firebase and already has standardized builtin mappings in Java: https://github.com/sidiabale/parse4cn1/

Related

How do I retrieve video custom labels through the RestFB API using Java?

I'm creating a java application that pulls data from facebook videos using RestFB. How can I retrieve the custom labels from each video?
Although I'm able to pull the normal data from each video, there doesn't seem to be any RestFB function that gets custom labels.
I've tried creating my own function by copying the RestFB source code for getting the title and then changing it according to the data I need, but that doesn't seem to work.
The custom labels field is missing atm in RestFB, so you can wait until a new version is released or write a custom video type like this:
public class CustomLabelsVideo extends Video {
#Facebook("custom_labels")
private List<String> customLabels = new ArrayList<>();
public List<String> getCustomLabels() {
return customLabels;
}
public void setCustomLabels(List<String> customLabels) {
this.customLabels = customLabels;
}
}
You need to use this type in the fetchObject method, and don't forget to add the custom_labels string to the fields you fetch.

Google Drive REST Api download file by its fileId

Hello guys I run into a problem. In my application I am storing fileId's of files which user selected before in GoogleDrive file picker. Also I am storing a local copy of that files in device. After each start I want to refresh local files, so I want to download them from drive. But it is not cleare for me, how should i do this.
I saw this documentation, but I can't understand where to get driveService, which used in this code
driveService.files().get(fileId)
.executeMediaAndDownloadTo(outputStream);
I don't know what driveService is in this code. (Which class instance) and how do I get it
Help me please, thank you.
P.S.
Sorry for my bad english
you should check the documentation under resumable Media Downloads it might give you some clues.
class CustomProgressListener implements MediaHttpDownloaderProgressListener {
public void progressChanged(MediaHttpDownloader downloader) {
switch (downloader.getDownloadState()) {
case MEDIA_IN_PROGRESS:
System.out.println(downloader.getProgress());
break;
case MEDIA_COMPLETE:
System.out.println("Download is complete!");
}
}
}
OutputStream out = new FileOutputStream("/tmp/driveFile.jpg");
DriveFiles.Get request = drive.files().get(fileId);
request.getMediaHttpDownloader().setProgressListener(new CustomProgressListener());
request.executeMediaAndDownloadTo(out);
BaseClientService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample",
});
You should check this stack answer, maybe it will help you understand it:
How do you create a new Google Drive Service in C# using OAuth

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

remote FileChooser using OtrosVFSBrowser

I'm trying to do a remote filechooser. I read a lot of information but I don't get it.
The best site I've seen is (https://code.google.com/p/otrosvfsbrowser/) because is exactly what I want but I don't fine more information. Are Someone of you using this tool? where are any example code?
I already use JSCH library to transfer via SFTP, but I want a tool to choose the remote path.
I'm starting in Java. sorry for my English.
You can check example code on Usage page
You can just create dialog and register action on approve:
JOtrosVfsBrowserDialog jOtrosVfsBrowserDialog = new JOtrosVfsBrowserDialog();
Action a = new AbstractAction("Select file") {
#Override
public void actionPerformed(ActionEvent actionEvent) {
if (JOtrosVfsBrowserDialog.ReturnValue.Approve.equals(jOtrosVfsBrowserDialog.showOpenDialog(TestDialog.this,"title"))){
String friendlyUrl = jOtrosVfsBrowserDialog.getSelectedFile().getName().getFriendlyURI();
}
}
};

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

Categories