Append line of text to Azure Block Blob from Android - android

I want to append a line of text to an existing Azure cloud block blob from an Android device.
In VB.Net I would AcquireLease, getBlockBlobReference, DownloadToFile, add the line on the local files system, UploadToFile, ReleaseLease . Simple and secure, if a bit long-winded.
In Android, it looks a little more tricky. At the moment, my best solution is this:
CloudBlockBlob blob1=container.getBlockBlobReference(chosenOne+".txt");
String proposedLeaseId1 = UUID.randomUUID().toString();
OperationContext operationContext1 = new OperationContext();
blob1.acquireLease(15, proposedLeaseId1, null /*access condition*/,null/* BlobRequestOptions */, operationContext1);
AccessCondition condition = new AccessCondition();
condition.setLeaseID(proposedLeaseId1);
BlobInputStream blobIn = blob1.openInputStream();
blob1.downloadAttributes();
long blobLengthToUse = blob1.getProperties().getLength();
byte[] result = new byte[(int) blobLengthToUse];
blob1.downloadToByteArray(result,0);
blobIn.close();
CloudBlockBlob blob1 = container.getBlockBlobReference(chosenOne+".txt");
String proposedLeaseId1 = UUID.randomUUID().toString();
OperationContext operationContext1 = new OperationContext();
blob1.acquireLease(15, proposedLeaseId1, null /*access condition*/,null/* BlobRequestOptions */, operationContext1);
AccessCondition condition = new AccessCondition();
condition.setLeaseID(proposedLeaseId1);
BlobInputStream blobIn = blob1.openInputStream();
blob1.downloadAttributes();
long blobLengthToUse = blob1.getProperties().getLength();
byte[] result = new byte[(int) blobLengthToUse];
blob1.downloadToByteArray(result,0);
blobIn.close();
blob1.deleteIfExists(DeleteSnapshotsOption.NONE,condition, null, operationContext1);
BlobOutputStream blobOut = blob1.openOutputStream();
//this is a byte by byte write ...
//which is fine ... but no use if you want to replace ...
/*int next = blobIn.read();
while (next != -1) {
blobOut.write(next);
next = blobIn.read();
}*/
blobOut.write(result);
String strTemp="This is just a test string";
blobOut.write(strTemp.getBytes());
blobOut.close();
Apart from being extremely long-winded, I am concerned that as soon as I delete the blob, the lease will go and that I may hit integrity issues. I would appreciate any help in making this code simpler and more secure. I know that Microsoft are planning to introduce append blobs in 3Q 2015, but I want to implement this now.

You can call PutBlock to upload the appended content (the maximum size of each block is 4MB, so please split the appended content into blocks if required), and then call PutBlockList on this blob by passing in the previously committed blocks plus and newly appended blocks.

Related

How to send document to apps script kotlin android

Currently Iam sending string and image file as string. to sheet via Apps script (sheet extension). Now I need to send a document files like (.zip, .glb, .obj, .arp, etc) I need to send these type of files to google sheet. so now I need to make user selected files as .zip. so now I need to send that .zip file to google sheet. but I couldnt do that.
private fun startUploading() {
try {
val map: HashMap<String, String> = HashMap()
map["instagramLink"] = binding.creatorInstaID.text.toString()
map["tutorialLink"] = binding.youTubeLink.text.toString()
map["detailDescription"] = binding.detailDescription.text.toString()
map["coverImage"] = userImage!!
mainViewModel.saveProduct(map)
}
catch (e:Exception){
Toast.makeText(context, "Fill all the details", Toast.LENGTH_SHORT).show()
}
}
Here userImage is the user selected image which is converted as string.
other values are string values it can be sent to google sheet easily.
now how can i send a custom file types to google sheet. as like this.
The only workaround I found is converting the encode the file to base64. Then add the string of base64 to the Google Sheet. I made a sample file with a Zip file store in Google Drive. You might need to adjust the code as needed.
Also, remember that character limit of a Google Cell is 50,000, so I added an if statement in case the encode file has more than 50,000 characters and split the string in an array of 45000 characters.
Note: The same sample code can be use on any type of files.
function encode64() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1")
// get the file from Google Drive using the ID
let file = DriveApp.getFileById("Drive_Zip_File_ID");
//convert the zip file to blob
let file_in_blop = file.getBlob();
//convert the blop to bytes
let file_in_bytes = file_in_blop.getBytes();
//encode the bytes to base64
let encoded = Utilities.base64Encode(file_in_bytes);
//get the length of charactes from the base 64 encode
let length_string = encoded.length
//split the string to array in chunks less than 45000 characters
if (length_string > 50000){
const result = encoded.match(/.{1,45000}/g) ?? [];
for (let i = 0; i < result.length; i++) {
sheet.getRange(i+2,2).setValue(result[i]);
}
}else(sheet.getRange("B2").setValue(result));
}

How to read/write a string encoded with android.util.Base64

I would like to store some strings in a simple .txt file and then read them, but when I want to encode them using Base64 it doesn't work anymore: it writes well but the reading doesn't work. ^^
The write method:
private void write() throws IOException {
String fileName = "/mnt/sdcard/test.txt";
File myFile = new File(fileName);
BufferedWriter bW = new BufferedWriter(new FileWriter(myFile, true));
// Write the string to the file
String test = "http://google.fr";
test = Base64.encodeToString(test.getBytes(), Base64.DEFAULT);
bW.write("here it comes");
bW.write(";");
bW.write(test);
bW.write(";");
bW.write("done");
bW.write("\r\n");
// save and close
bW.flush();
bW.close();
}
The read method :
private void read() throws IOException {
String fileName = "/mnt/sdcard/test.txt";
File myFile = new File(fileName);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader inBuff = new BufferedReader(new InputStreamReader(fIn));
String line = inBuff.readLine();
int i = 0;
ArrayList<List<String>> matrice_full = new ArrayList<List<String>>();
while (line != null) {
matrice_full.add(new ArrayList<String>());
String[] tokens = line.split(";");
String decode = tokens[1];
decode = new String(Base64.decode(decode, Base64.DEFAULT));
matrice_full.get(i).add(tokens[0]);
matrice_full.get(i).add(tokens[1]);
matrice_full.get(i).add(tokens[2]);
line = inBuff.readLine();
i++;
}
inBuff.close();
}
Any ideas why?
You have a couple of errors in your code.
First a couple of notes on your code:
When posting here, attaching a SSCCE helps others to debug your code. This is not a SSCEE because it doesn't compile. It lacks several defined variables, so one must guess what you really mean. Also you have pasted close-comment token in your code: */ but there is no one start-comment token.
Catching and just suppressing exceptions (like in catch-block in read method) is really bad idea unless you really know what you're doing. What it does most of the time is hide the potential problems from you. At least write the stacktrace of an exception is a catch block.
Why don't you just debug it, check what exactly outputs to the destination file? You should learn how to do that because that will speed up your development process, especially for larger projects with hard-to-catch problems.
Back to the solution:
Run the program. It throws an exception:
02-01 17:18:58.171: E/AndroidRuntime(24417): Caused by: java.lang.ArrayIndexOutOfBoundsException
caused by line here:
matrice_full.get(i).add(tokens[2]);
inspecting the variable tokens reveals that it has 2 elements, not 3.
So lets open the file generated by the write method. Doing that shows this output:
here it comes;aHR0cDovL2dvb2dsZS5mcg==
;done
here it comes;aHR0cDovL2dvb2dsZS5mcg==
;done
here it comes;aHR0cDovL2dvb2dsZS5mcg==
;done
Note line breaking here. This is because the Base64.encodeToString() appends additional newline at the end of the encoded string. To generate a one single line, without extra newlines, add Base64.NO_WRAP as the second parameter like this:
test = Base64.encodeToString(test.getBytes(), Base64.NO_WRAP);
Note here, you must delete file that was created earlier as it has improper line breaking.
Run the code again. It now creates a file with the proper contents:
here it comes;aHR0cDovL2dvb2dsZS5mcg==;done
here it comes;aHR0cDovL2dvb2dsZS5mcg==;done
Printing the output of matrice_full now gives:
[
[here it comes, aHR0cDovL2dvb2dsZS5mcg==, done],
[here it comes, aHR0cDovL2dvb2dsZS5mcg==, done]
]
Note that you're not doing anything with the value in decode variable in your code, hence the second element is the Base64 representation of that value which is read from the file.

Which is better solution get server response data?

We usually get data from server response in android development.
/*
* get server response inputStream
*/
InputStream responseInputStream;
Solution1: get response string by multiple read.
/*
* get server response string
*/
StringBuffer responseString = new StringBuffer();
responseInputStream = new InputStreamReader(conn.getInputStream(),"UTF-8");
char[] charBuffer = new char[bufferSize];
int _postion = 0;
while ((_postion=responseInputStream.read(charBuffer)) > -1) {
responseString.append(charBuffer,0,_postion);
}
responseInputStream.close();
Solution2: get response only one read.
String responseString = null;
int content_length=1024;
// we can get content length from response header, here assign 1024 for simple.
responseInputStream = new InputStreamReader(conn.getInputStream(),"UTF-8");
char[] charBuffer = new char[content_length];
int _postion = 0;
int position = responseInputStream.read(charBuffer)
if(position>-1){
responseString = new String(charBuffer,0,position );
}
responseInputStream.close();
Which solution has better performance? why?
Notes: server response json format data that less than 1M bytes.
Why you're reinventing a wheel? ;)
If you're using HttpClient then just use EntityUtils.toString(...).
I guess you're using HttpURLConnection. Then look at EntityUtils.toString(...) from Apache HttpClient - source code. Your first approach is similar to it.
BTW, the second code is worse because:
new String(charBuffer,0,position ) runs garbage collector
In both and even in EntityUtils:
int content_length = 1024; in most cases 8192 is default for socket buffer, so your code might run while loop 8 times more often than it could.
I would recommend the second method IF you do not want to display the amount of data downloaded/transferred . As the object is read as a whole and since the size of your JSON string is comparable to 1M, it will take some time to download. At that time you can, atmost, put up a text for the user saying downloading... You cannot notify the user the amount downloaded.
But if you want to display the amount of data downloaded, use the first method that you gave. Where the you read the data from the server in parts. You can update the UI, with the amount downloaded. For eg 25 % downloaded...
char[] charBuffer = new char[bufferSize];
int _postion = 0;
int i=0;
while ((_postion=responseInputStream.read(charBuffer)) > -1) {
//((i*buffer_size)/content_length) * 100 % completed..
i++;
}
So, I would say the seconds method is better.
BTW Did you consider this?
ObjectInputStream in = new InputStreamReader(conn.getInputStream(),"UTF-8");
if(resposeCode==200)
{
String from_server=(String) in.readObject();
}
Reading the input String as an object. Any object whoe class implements serializable can be passed using ObjectOutputStream and received using ObjectInputStream()
I Think First one is good
Because, in First that will reading your response in char to char method .
Where , Second that will try to read whole response object or as key Filed of Object.
So ,As i think and as per my knowledge First is Better to camper with second.If anyone want to edit then it will truly appreciated.

Android String Parsing

I am writing an android app that recieves data over bluetooth. The bytes comming in can be of any size example: 00023>024935928598235>9284>
As you can see each set is seperated by ">". The data comes in extremely fast. I would like some ideas for an implementation. See my problem is that I need to read the data into a byte array that can and then convert it to a string and split them according to the delimeter of ">".
so in the above example:
00023
024935928598235
9284
If i set byte[] data = new byte[8] then when reading the incomming data it might get 00023>02 which is not what i want. I'm not sure how to implement something like this. Any ideas?
Here's one approach. You'll have to implement the readDataFromBluetooth() and somehow set dataAvailable, but this should get you on the right track.
byte[] data = new byte[1024];
List<String> chunks = new LinkedList<String>();
StringBuilder chunk = new StringBuilder();
while (dataAvailable) {
data = readDataFromBluetooth();
for (byte b : data) {
if (b == '<') {
chunks.add(chunk.toString());
chunk.setLength(0);
} else {
chunk.append(b);
}
}
}
if (chunk.length() > 0)
chunks.add(chunk.toString());
I would recommend using a buffered stream, but maybe a bit bigger that 8 bytes, as you suggest, and the read one and one character from the beginning of the stream, accumulating the string. When you encounter a ">", send the value you have accumulated off to a queue for a background thread processing. Use standard producer/consumer implementation techniques (e.g. the Monitor pattern) to communicate via the queue.

Why are foreign characters not read using inputStream?

I have a text file which contains data I need to preload into a SQLite database. I saved in in res/raw.
I read the whole file using readTxtFromRaw(), then I use the StringTokenizer class to process the file line by line.
However the String returned by readTxtFromRaw does not show foreign characters that are in the file. I need these as some of the text is Spanish or French. Am I missing something?
Code:
String fileCont = new String(readTxtFromRaw(R.raw.wordstext));
StringTokenizer myToken = new StringTokenizer(fileCont , "\t\n\r\f");
The readTxtFromRaw method is:
private String readTxtFromRaw(Integer rawResource) throws IOException
{
InputStream inputStream = mCtx.getResources().openRawResource(rawResource);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
return byteArrayOutputStream.toString();
}
The file was created using Eclipse, and all characters appear fine in Eclipse.
Could this have something to do with Eclipse itself? I set a breakpoint and checked out myToken in the Watch window. I tried to manually replace the weird character for the correct one (for example í, or é), and it would not let me.
Have you checked the several encodings?
what's the encoding of your source file?
what's the encoding of your output stream?
the byteArrayOutputStream.toString() converts according to the platform's default character encoding. So I guess it will strip the foreign characters or convert them in a way that they are not displayed in your output.
Have you already tried to use byteArrayOutputStream.toString(String enc)? Try "UTF-8" or "iso-8859-1" or "UTF-16" for the encoding.

Categories

Resources