Unzipping .zip folder with Zipme Library in Codename One - codenameone

This is as a followup to the question that I asked here:
What is the correct way to display a HTML file downloaded and saved in the file system using codename one?
I am successful to display a html file from a folder using webview. The trick is to add the "file://" when setting the url as shown below:
browser.setURL("file://"+str_homePath+str_filePath);
If this is not by your design then I can file an RFE. Nonetheless, next I hit an Unzipping challenge which I think might be related to the "file://" issue above.
When unzipping a .zip file using the Zipme cn1lib, everything extracts OK on simulator but fails on device. I had to root a phone in order to see what exactly is going on. I found that some files are not extracted.
Checking on the DDMS confirmed my findings. Every so often I see this error: W/System.err: java.io.FileNotFoundException: (No such file or directory)
Then, when I try to display the index file (which should fail because of the above missing files), I get this error:
I/System.out: showKeyboard false
I/System.out: showKeyboard false
D/WebView: loadUrl=file:///data/user/0/ke.co.imedia.samplefilepath/files/17/rte.html
W/cr_media: Requires BLUETOOTH permission
E/libEGL: validate_display:99 error 3008 (EGL_BAD_DISPLAY)
Below is the code I am using to unzip:
try
{
System.out.println("Finding FILE TO UNZIP: ");
InputStream zipFile = Storage.getInstance().createInputStream("folderName"+".zip");
//InputStream zipFile = FileSystemStorage.getInstance().openInputStream(fs.getAppHomePath()+"folderName"+".zip");
fs.mkdir(fs.getAppHomePath()+"folderName");
System.out.println("ZIPPED FILE FOUND: ");
Unzip(zipFile, "/"+ "folderName");
System.out.println("UNZIPPED SUCCESFULLY");
}
catch (IOException ex)
{
Log.p(ex.getMessage(), 0);
ex.printStackTrace();
}
catch (Exception ex)
{
ex.printStackTrace();
}
The above codes calls the following method as copied from the link below, with some edits that I hoped would allow extracting to a folder by checking whether the next entry during the unzipping process is a directory or not.
https://github.com/codenameone/ZipSupport
public void Unzip(InputStream is_zipFile, String str_dirDest)
{
InputStream is;
try
{
is = is_zipFile;
ZipInputStream zipStream = new ZipInputStream(is);
ZipEntry entry;
// create a buffer to improve copy performance later.
byte[] buffer = new byte[2048];
System.out.println("TRYING TO UZIP: ");
while ((entry = zipStream.getNextEntry()) != null)
{
FileSystemStorage fs = FileSystemStorage.getInstance();
String str_name = entry.getName();
String dir;
String str_outdir = FileSystemStorage.getInstance().getAppHomePath();
//FileOutputStream fileoutputstream;
File newFile = new File(str_outdir, str_name);
boolean overwrite = false;
if (str_outdir.length() > 0)
{
str_outdir = str_outdir + "/" + str_dirDest;
}
//extractFile(zin, outdir, name);
String outpath = str_outdir + "/" + entry.getName();
OutputStream output = null;
try
{
if (entry.isDirectory())
{
fs.mkdir(str_outdir + "/" + str_name);
entry = zipStream.getNextEntry();
continue;
}
else
{
File file = new File(str_outdir + File.separator + str_name);
File parent = file.getParentFile();
if (!parent.exists())
{
parent.mkdirs();
}
}
System.out.println("UNZIPPING:- " + str_name);
output = FileSystemStorage.getInstance().openOutputStream(outpath);
int len = 0;
while ((len = zipStream.read(buffer)) > 0)
{
output.write(buffer, 0, len);
}
}
catch (Exception e)
{
e.printStackTrace();
//Dialog.show("Unzipping Error!", ""+e, "Ok", null);
}
finally
{
if (output != null)
{
output.close();
}
}
}
} catch (IOException ex) {
Log.p(ex.getMessage(), 0);
}
}

Related

How to protect my SQLite db by intentionally corrupting it, then fix it through code?

This is my first app on Android with Java and SQLite.
ISSUE:
I have a local SQLIte db on my app. I was very surprised to see how easy it is to get access to the db once you have installed the app (no need to be a programmer nor a hacker).
I tried adding SQLCipher to my app but it only worked for newer Android versions 11 & 12 and didn't work for Android 9 for example and it did make my app's size much bigger.
After researching more I found a better solution for my case which doesn"t involve crypting the db with SQLCipher but rather it consists of corrupting the first bytes of the db file then after each launch of the app the code will decorrupt the file and use the fixed file instead. This insures that anyone who decompiles the apk will only get access to a corrupt db file and will have to put more effort to fix it which is my goal.
I came across this solution in a reply [here][1] but I don't know how to implement it as I am new to Android and SQLite programming. Any help is much appreciated on how to actually do it.
These are the steps as mentioned by the user: farhad.kargaran which need more explanation as I don't get how to do it:
1- corrupt the db file (convert it to byte array and change some values)
2- copy it in asset folder
3- in first run fix corrupted file from asset and copy it in database
folder.
Change first 200 byte values like this:
int index = 0;
for(int i=0;i<100;i++)
{
byte tmp = b[index];
b[index] = b[index + 1];
b[index + 1] = tmp;
index += 2;
}
As only the first 200 bytes were replaced, the same code is used for fixing first 200 byte values.
Here is my code for the SQLiteOpenHelper if needed:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = DatabaseHelper.class.getSimpleName();
public static String DB_PATH;
public static String DB_NAME;
public SQLiteDatabase database;
public final Context context;
public SQLiteDatabase getDb() {
return database;
}
public DatabaseHelper(Context context, String databaseName, int db_version) {
super(context, databaseName, null, db_version);
this.context = context;
DB_PATH = getReadableDatabase().getPath();
DB_NAME = databaseName;
openDataBase();
// prepare if need to upgrade
int cur_version = database.getVersion();
if (cur_version == 0) database.setVersion(1);
Log.d(TAG, "DB version : " + db_version);
if (cur_version < db_version) {
try {
copyDataBase();
Log.d(TAG, "Upgrade DB from v." + cur_version + " to v." + db_version);
database.setVersion(db_version);
} catch (IOException e) {
Log.d(TAG, "Upgrade error");
throw new Error("Error upgrade database!");
}
}
}
public void createDataBase() {
boolean dbExist = checkDataBase();
if (!dbExist) {
this.getReadableDatabase();
this.close();
try {
copyDataBase();
} catch (IOException e) {
Log.e(TAG, "Copying error");
throw new Error("Error copying database!");
}
} else {
Log.i(this.getClass().toString(), "Database already exists");
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDb = null;
try {
String path = DB_PATH + DB_NAME;
checkDb = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLException e) {
Log.e(TAG, "Error while checking db");
}
if (checkDb != null) {
checkDb.close();
}
return checkDb != null;
}
private void copyDataBase() throws IOException {
InputStream externalDbStream = context.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream localDbStream = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = externalDbStream.read(buffer)) > 0) {
localDbStream.write(buffer, 0, bytesRead);
}
localDbStream.close();
externalDbStream.close();
}
public SQLiteDatabase openDataBase() throws SQLException {
String path = DB_PATH + DB_NAME;
if (database == null) {
createDataBase();
database = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READWRITE);
}
return database;
}
#Override
public synchronized void close() {
if (database != null) {
database.close();
}
super.close();
}
Much appreciated.
[1]: https://stackoverflow.com/a/63637685/18684673
As part of the copyDatabase, correct and then write the corrupted data, then copy the rest.
Could be done various ways
e.g.
long buffersRead = 0; //<<<<< ADDED for detecting first buffer
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = externalDbStream.read(buffer)) > 0) {
if (bufferesRead++ < 1) {
//correct the first 200 bytes here before writing ....
}
localDbStream.write(buffer, 0, bytesRead);
}

Saving and retrieving files in Codenameone

I have an app with data files (some images and xml files) i have packed them up in a zip file.
I open the file with zipme and save the files. I used this code for that
private void save1( ) {
InputStream is;
FileChooser.showOpenDialog(".zip", new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e != null && e.getSource() != null) {
String file = (String)e.getSource();
FileSystemStorage fs = FileSystemStorage.getInstance();
try {
InputStream is = fs.openInputStream(file);
ZipInputStream zipStream = new ZipInputStream(is);
ZipEntry entry;
// create a buffer to improve copy performance later.
byte[] buffer = new byte[2048];
while ((entry = zipStream.getNextEntry()) != null) {
String s = entry.getName();
String outdir = FileSystemStorage.getInstance().getAppHomePath();
if (outdir.length() > 0) {
outdir = outdir ;
}
String outpath = outdir + "/" + entry.getName();
OutputStream output = null;
try {
output = FileSystemStorage.getInstance().openOutputStream(outpath);
int len = 0;
while ((len = zipStream.read(buffer)) > 0) {
output.write(buffer, 0, len);
}
} finally {
// we must always close the output file
if (output != null) {
output.close();
}
}
} } catch (IOException ex) {
Log.p(ex.getMessage(), 0); } } }});}
i see in netbeans that in the simulator the files are saved to
users/.cn1
So this works on the desktop
To fetch the image i use
String outdir = FileSystemStorage.getInstance().getAppHomePath();
Image uur1 = EncodedImage.create(outdir + "/West.jpg");
i also tried without outdir but also no luck.
What do i wrong.
This should work without the extra slash:
Image uur1 = EncodedImage.create(outdir + "West.jpg");.
Notice that this code is case sensitive so make sure the file has the right casing. Is this failing on the simulator, if so place a breakpoint on the loading code and make sure the file is physically there
The answer i found on my question is:
1 No extra slash as Shai Among suggested:
2 Make a inputstream for enecodedimage.create() instead of only a string with the path to the file
Without the second part the app doesn't run correctly in the simulation and on the device
FileSystemStorage fs = FileSystemStorage.getInstance();
String outdir = FileSystemStorage.getInstance().getAppHomePath();
String outpath = outdir + West.jpg;
InputStream isk = fs.openInputStream(outpath);
Image uur = EncodedImage.create(isk);

How to save locally and retrieve files using Codename One and CN1 Filechooser?

I have studied the Files, Storage and Networking instructions on the Codename One website. I am trying to
save files selected by the Codename One filechooser to the device (simulator, Android, iPhone)
retrieve the files saved locally in whatever device they got saved on.
Here is the code I used:
final Button getFileChooser = new Button("Get file chooser");
getFileChooser.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (FileChooser.isAvailable()) {
FileChooser.showOpenDialog(".pdf, .jpg, .jpeg, .png", e2-> {
String file = (String)e2.getSource();
if (file == null) {
hi.add("No file was selected");
hi.revalidate();
} else {
String extension = null;
if (file.lastIndexOf(".") > 0) {
extension = file.substring(file.lastIndexOf(".")+1);
ToastBar.showMessage("1: " + file, FontImage.MATERIAL_CHECK);
rawFilename.setText("raw: " + file);
//java.util.List<String> filepathParsed = StringUtil.tokenize(file, "[/.]");
StringBuilder hi = new StringBuilder(file);
if (file.startsWith("file://"))
hi.delete(0, 7);
int lastIndexPeriod = hi.toString().lastIndexOf(".");
Log.p(hi.toString());
String ext = hi.toString().substring(lastIndexPeriod);
String hmore = hi.toString().substring(0, lastIndexPeriod -1);
String hi2 = hmore +/* "/file" +*/ ext;/*hi;*/
Log.p("hi2 = " + hi2);
secondFilename.setText("2nd: " + hi2);
//secondFilename.setText((String)evt.getSource());
try {
saveFileToDevice(file, ext);
} catch (URISyntaxException e) {
e.getMessage();
}
//sendFileViaEmail(hi2, file);
} else {
ToastBar.showMessage("2: " + file + " " + extension, FontImage.MATERIAL_CHECK);
}
}
hi.revalidate();
});
}
}
});
protected void saveFileToDevice(String hi, String ext) throws URISyntaxException{
URI uri = new URI(hi);
String path = uri.getPath();
Log.p("uri path: " + uri.getPath() + " ; scheme: " + uri.getScheme());
/*if (path.contains("..jpg")) {
int indexLastPeriodBeforeExt = path.lastIndexOf(".");
path = path.substring(0, indexLastPeriodBeforeExt) + path.substring(indexLastPeriodBeforeExt+ 1);
Log.p("new path: " + path);
}*/
if (Display.getInstance().getPlatformName().equals("and"))
path = "file://" +path;
String home = FileSystemStorage.getInstance().getAppHomePath();
char sep = FileSystemStorage.getInstance().getFileSystemSeparator();
String userDir = home + sep + "myapp";
/*if (hi.startsWith("file://")) {
hi = hi.substring(7);
}*/
int index = hi.lastIndexOf("/");
hi = hi.substring(index + 1);
Log.p("hi after substring 7: " + hi);
FileSystemStorage.getInstance().mkdir(userDir);
String fPath = userDir + sep + hi ;
/* if (hi.contains("..jpg")) {
int indexLastPeriodBeforeExt = hi.lastIndexOf(".");
hi = hi.substring(0, indexLastPeriodBeforeExt) + hi.substring(indexLastPeriodBeforeExt+ 1);
Log.p("new hi: " + hi);
}*/
Log.p("does it exist? " + FileSystemStorage.getInstance().exists(userDir));
String imageFile = userDir + sep + hi;
String[] roots = FileSystemStorage.getInstance().getRoots();
if (roots.length > 0) {
for (int i = 0; i < roots.length; i++)
Log.p("roots" + i + " " + roots[i]);
}
try {
String[] files = FileSystemStorage.getInstance().listFiles(userDir);
for (int i = 0; i < files.length; i++) {
Log.p(i + " " + files[i]);
//secondName = files[files.length-1];
Log.p("secondname: " + secondName);
}
sendFileViaEmail(imageFile, ".jpg");
} catch (IOException e) {
e.getMessage();
}
}
protected void sendFileViaEmail(String hi2, String file) {
Message m = new Message("Test message");
//m.getAttachments().put(file, "image/jpeg");
m.setAttachment(hi2);
m.setAttachmentMimeType(Message.MIME_IMAGE_JPG);
//m.setMimeType(Message.MIME_IMAGE_JPG);
//m.getAttachments().put(imageAttachmentUri, "image/png");
Display.getInstance().sendMessage(new String[] {"myemail#example.com"}, "test message cn1", m);
}
I added the getFileChooser button to my Form after importing the cn1-filechooser library to my project and refreshed libs. The filechooser works -- I tried it on the simulator, Android device and iPhone.
My issue is here:
String file retrieves what looks like a URI. I tried to convert the URI to a File and when I run the following code to see that the files are stored I see them in my logs, although in a funny order, which I'm ok with.
String[] files = FileSystemStorage.getInstance().listFiles(userDir);
for (int i = 0; i < files.length; i++) {
Log.p(i + " " + files[i]);
//secondName = files[files.length-1];
Log.p("secondname: " + secondName);
}
How do retrieve a valid, uncorrupted version of this file from FileSystemStorage? Am I storing it wrong? Whenever I run the method to send the file via email, it opens Outlook (on my Desktop) but no files is attached? (I assume that the file is invalid/corrupted when trying to retrieve it from FileSytemStorage -- please help.) I hardcoded .jpg as MIME-type but only as a test; my goal is to be able to save/restore .pdf, .png, .jpg, and.jpeg files.
Thanks!
**EDIT: ** This seems to show that the file was actually saved to my app's storage. How do I stream the content of the file be copied/uploaded or emailed from my app?
Mobile phones don't allow that. They don't have a file system like desktops have. So file chooser really launches a tool to help you pick a file from a different app, this file is then copied to your local app sandbox where you can get access to the content of the app.
Naturally this won't work for save as it would mean you could potentially corrupt a file within another application so you are restricted from writing to the directories of other applications installed or even knowing which applications are installed and where...
To transfer a file to a different app you have the share intent which you can use via the share button or the low level API's in display. This allows you to send an image to whatsapp or similar functionality that makes sense in a mobile phone.

using file upload ADF

Mine is adf 11.1.1.6 application
My requirement is to provide user a dialog, though which user would select the file in his local machine and upload the same in some destination folder.
I have an inputfile and button.
InputStream inputstream; //global variable in the bean
File file //global variable in the bean
on vcl of input file:
file = (UploadedFile)valueChangeEvent.getNewValue();
try {
inputstream = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
on the click of button:
File destFile=new File("c:\\abc\\upload\\test.txt");
try {
if(!destFile.exists()){
destFile.createNewFile();
}
OutputStream output = new FileOutputStream("c:\\abc\\upload\\test.txt");
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = inputstream.read(buf)) > 0) { /// inputstream captured on vcl
output.write(buf, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
I noted that the test.txt was created of size 0kb but without any content it.
What is wrong here?

"File system error (1003)" opening BlackBerry file connection

I tried the example from "J2ME/Blackberry - how to read/write text file?". I want only the read functionality, the file I want to read is in CSV format as a .txt file placed in the /res/test.txt.
But I am having an issue with the FileConnection. I get the following error:
File system error (1003)
Any suggestions or advice on a better approach or as to how I can get this working?
public class FileDemo extends MainScreen {
public FileDemo() {
setTitle("My Page");
String str = readTextFile("file:///test.txt");
System.out.println("Contents of the file::::::: " + str);
}
public String readTextFile(String fName) {
String result = null;
FileConnection fconn = null;
DataInputStream is = null;
try {
fconn = (FileConnection) Connector.openInputStream(fName);
is = fconn.openDataInputStream();
byte[] data = IOUtilities.streamToBytes(is);
result = new String(data);
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (null != is)
is.close();
if (null != fconn)
fconn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
return result;
}
}
try this
InputStream is = getClass().getResourceAsStream("/test.txt");
StringBuffer buff = new StringBuffer();
int ch;
try {
while ((ch = is.read()) != -1)
buff.append((char) ch);
} catch (Exception e) {
Log.Error(e, "Exception ");
}
String str = (buff.toString());
Same problem I also faced in my project. First check your simulator memory card is inserted or not. From simulator,
go to Options(Settings)-->Device-->Storage and Check the Memory card Storage.
If the memory card is not inserted, than it will show Media Card is not currently inserted in the device. So, you need to insert the memory card. From simulator menu bar, choose simulate-->Change SD Card...
You can add the SD card here. Than you try.
I think, This suggestion will help someone.

Resources