using file upload ADF - file

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?

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

"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.

Save to file open by openfiledialog (C# 2008)

What I am trying to do is most likely very simple but afters spending hours I still cant figure out how to do it correctly. I am able to open a text file using the openfiledialog but cannot figure out to save back to that same file. I would like to also be able to check and see if the file is in use before writing to it. Here is my code for the open and save buttons:
public void openToolStripMenuItem_Click(object sender, EventArgs e)
{
//This if statement checks if the user has saved any changes to the list boxes
if (MessageBox.Show(
"Have you saved your work?\nOpening a new file will clear out all list boxes.",
"Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
//Clears out the listboxes
this.itemListBox.Items.Clear();
this.priceListBox.Items.Clear();
this.qtyListBox.Items.Clear();
//This will open the file dialog windows to allow the user to chose a file
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "Harv's Hardware";
fileDialog.InitialDirectory = Directory.GetCurrentDirectory();
//File Filter
fileDialog.Filter = "txt files (*.txt)|*.txt";
fileDialog.FilterIndex = 2;
fileDialog.RestoreDirectory = true;
//This if statement executes is the user hits OK
if (fileDialog.ShowDialog() == DialogResult.OK)
{
//StreamReader readFile = File.OpenText(fileDialog.FileName);
currentFile = new StreamWriter(OpenFileDialog.FileName);
String inputString = null;
while ((inputString = readFile.ReadLine()) != null)
{
this.itemListBox.Items.Add(inputString);
inputString = readFile.ReadLine();
this.priceListBox.Items.Add(inputString);
inputString = readFile.ReadLine();
this.qtyListBox.Items.Add(inputString);
}
}
}
}
and save button
//Closes and open files
//Creates a new saveDialog
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.ShowDialog();
//Listens to the user input
StreamWriter writeFile = File.CreateText(saveDialog.FileName);
int indexInteger = 0;
//Writes the actual File
while (indexInteger < priceListBox.Items.Count)
{
writeFile.WriteLine(itemListBox.Text);
writeFile.WriteLine(itemListBox.Text);
writeFile.WriteLine(qtyListBox.Text);
indexInteger++;
}
}
Thanks for any help!
Use SaveFileDialog instead of OpenFileDialog and can use FileStream to write to the file.
To check if file is in use or not, this is what I do..
public bool IsFileInUse(String file)
{
bool retVal = false;
try
{
using (Stream stream = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
//file is not locked
}
}
catch
{
retVal = true;
}
return retVal;
}

Resources