Saving and retrieving files in Codenameone - 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);

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);
}

Unzipping .zip folder with Zipme Library in Codename One

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);
}
}

Groovy File.getText() - Do I have to close something?

If I use the File.getText() method in groovy
newFile().text or newFile().getText()
do I have to execute some closure statements to close the used file reader or will the method do it by itself?
It will do it by itself.
Calling new File( 'a.txt' ).text will call ResourceGroovyMethods.getText( File )
public static String getText(File file, String charset) throws IOException {
return IOGroovyMethods.getText(newReader(file, charset));
}
Which as you can see calls IOGroovyMethods.getText( BufferedReader ):
public static String getText(BufferedReader reader) throws IOException {
StringBuilder answer = new StringBuilder();
// reading the content of the file within a char buffer
// allow to keep the correct line endings
char[] charBuffer = new char[8192];
int nbCharRead /* = 0*/;
try {
while ((nbCharRead = reader.read(charBuffer)) != -1) {
// appends buffer
answer.append(charBuffer, 0, nbCharRead);
}
Reader temp = reader;
reader = null;
temp.close();
} finally {
closeWithWarning(reader);
}
return answer.toString();
}
Which as you can see, closes the Reader when done

How to detect and separate concatenated files?

I am trying to find a method to separate two files that have been concatenated together using
copy /b file1+file2 file3.
I know the mime type and file type of at least one of the two files.
With the following csharp code you can do the split based on the fact that the zip file has the signature of 4 bytes that indicates the local file header. This code will break if the EXE has the same 4 bytes some where. If you want to conquer that you have to dig through the PE/COFF header to add up all section sizes
And NO, it is not very efficient to copy a stream byte by byte...
using(var fs = new FileStream(#"exeandzip.screwed", FileMode.Open))
{
var lfh = new byte[] { 0x50, 0x4b, 0x03, 0x04 }; /* zip local file header signature */
var match = 0;
var splitAt = 0;
var keep = new Queue<int>();
var b = fs.ReadByte();
using(var exe = new FileStream(
#"exeandzip.screwed.exe",
FileMode.Create))
{
while((b != -1) && (match<lfh.Length))
{ splitAt++;
if (b==lfh[match])
{
match++;
keep.Enqueue(b);
}
else
{
while(keep.Count>0)
{
exe.WriteByte((byte) keep.Dequeue());
}
exe.WriteByte((byte)b);
match=0;
}
b = fs.ReadByte();
}
}
if (match==lfh.Length && b!=-1)
{
keep.Enqueue(b);
splitAt = splitAt-lfh.Length;
Console.WriteLine(splitAt);
using(var zip = new FileStream(
#"exeandzip.screwed.zip",
FileMode.Create))
{
while(keep.Count>0)
{
zip.WriteByte((byte) keep.Dequeue());
}
b = fs.ReadByte();
while(b != -1)
{
zip.WriteByte((byte)b);
b = fs.ReadByte();
}
}
}
}
Or u can use foremost -i <input file> -o <output directory>
I've even split the apple webarchive format file in this way

"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