How to read a Binary Document from Couchbase - JavaSDK API - java

I am trying to insert and retrieve small files in couchbase, insertion is successful but when I try to fetch the content and write it to a file am getting below error.
BinaryDocument responsefromDB = bucket.get("KESAVAN", BinaryDocument.class);
try {
FileOutputStream ostream = new FileOutputStream("C:\\Satz\\Test - Copy\\Output.txt");
ostream.write(responsefromDB.content().array());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Error :
Exception in thread "main" java.lang.UnsupportedOperationException: direct buffer
at com.couchbase.client.deps.io.netty.buffer.PooledUnsafeDirectByteBuf.array(PooledUnsafeDirectByteBuf.java:363)
at com.couchbase.client.deps.io.netty.buffer.SlicedByteBuf.array(SlicedByteBuf.java:97)
at com.couchbase.client.deps.io.netty.buffer.CompositeByteBuf.array(CompositeByteBuf.java:463)
at com.util.task.CouchbaseClient.main(CouchbaseClient.java:52)

You can only access the array() if hasArray() returns true. Otherwise the Netty buffer itself is backed by native memory. In this case you will need to use one of its getBytes(...) methods to copy the content to an array.
Don't forget to release() the buffer after obtaining it (in the finally block of your try catch for instance).
You seem to be outputing the content into a text file, so is BinaryDocument really what you're after? Maybe StringDocument would be a better, less hurdle, fit? (see http://docs.couchbase.com/developer/java-2.1/documents-basics.html).
Note that if you still have a compelling reason to use BinaryDocument and want the output as a String, you can use ByteBuf.toString(Charset) for this instead of getBytes.

Related

Creating a ZipFile, needs to be initialised but initialisation needs exceptions handled

So I need to add a new method to a program, it requires me accessing this zip folder. The first method downloads from a website and returns a File object.
So now in my method, I'm wanting to change this to be a ZipFile object. At the minute I just want to take in the File, create a ZipFile object using that File, then return it.
So everything is fine, but when I create the ZipFile object, it says an unhandled IOException is there. But if I put the try/catch around it I cannot return the ZipFile. So I create it first and then do the try catch but tells me that the ZipFile is not initialised. Any idea on what I'm missing in my thinking here or how I can sort this?
My code looks like;
ZipFile zipTestData;
try {
zipTestData = new ZipFile(testData)
}catch (IOException io)
log.debug(io.toString());
}catch(Exception e) {
log.debug(e.toString());
}
return zipTestData;
You should not 'swallow' an exception. If an exception occurs, you probably should pass it on for the caller to handle. Otherwise, how would the caller know the operation failed?
You may also use the approach you described, if the caller is prepared to handle the result correctly, like so:
ZipFile zipTestData = null;
try {
zipTestData = new ZipFile(testData)
} catch (IOException io)
log.debug(io.toString());
} catch(Exception e) {
log.debug(e.toString());
}
return zipTestData;
This will return null to the caller instead of a ZipFile if the zip cannot be created for whatever reason.
Although, in that specific case, you could just as well write
try {
return new ZipFile(testData)
} catch (IOException io)
log.debug(io.toString());
} catch(Exception e) {
log.debug(e.toString());
}
return null;
The reason for the error you get is that local variables are not initialized by default upon declaration. So when you declare a local variable (ZipFile zipTestData;) it is not assigned any value. Then, if at run time an exception is thrown at new ZipFile(testData), the variable will not get assigned and the return would try to return the value of that unassigned variable. In Java, that's forbidden.
probably you should initialize the
ZipFile zipTestData = null;
Without stacktrace this is what I could figure out

Read a large file in android (~15MB) from external memory in android

I want to load a model file that will be present in the user's external storage. Size of the model file can be upto 20MB or so. It contains x,y,z info separated by '\n'. When i try to load a small file by my method it runs fine. But for a large file the application asks for a force quit.
File dir = Environment.getExternalStorageDirectory();
File file = new File(dir,"model_Cube.txt");
BufferedReader reader = null;
List<Float> list = new ArrayList<Float>();
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
list.add(Float.parseFloat(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
triangleCoords = new float[list.size()];
for (int i = 0; i < list.size(); i++) {
Float f = list.get(i);
triangleCoords[i] = (float) (f.floatValue()/10.0); // Or whatever default you want.
}
The problem here is not in your code works, it is actually a problem with threading.
This is happening because the device sees that you are doing a large process in the main user interface thread. Look into Asynchronous Tasks. http://developer.android.com/reference/android/os/AsyncTask.html
This is how Android handles multi-threading in applications. Performing large file loads or calculations in the main thread may cause the app to become unresponsive and the operating system will think that it has crashed.
Splitting this functionality into a separate thread will avoid the issue.
Here is a decent tutorial with a sample implementation of an Asynchronous Task.
http://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/
You should use AsyncTask (http://developer.android.com/reference/android/os/AsyncTask.html) or separate Thread (http://developer.android.com/reference/java/lang/Thread.html) for reading this file. Now you are reading this file in main thread (UI thread) and while it reading, UI not responding.
Also, please note that may be better to use SQLite instead of such big files.

Android-Writing to a file results in random characters

Argargarg.
I am trying to get information from a user input, then to write it to a system file. I get the input, and I call getBytes on it. It logs to the file something along the lines of "null" and random numbers after that. I tried getting it to a string, no luck there, it was a random chain of symbols
Here is the specific code:
TextView note_input=(TextView) findViewById(R.id.note_input);
FileOutputStream fos=null;
String newNote=note_input.getText().toString();
Log.w("Debug",newNote);
try {
fos=openFileOutput("currentNote",Context.MODE_APPEND);
} catch (FileNotFoundException e) {
//IT_SHOUD_NOT_EXIST
}
try {
Log.w("Debug",newNote.getBytes().toString());
fos.write(newNote.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I appreciate any help!
String.getBytes returns array of bytes, and when you try to do toString() you are actually writing it's pointer to string. You already have String change this line
Log.w("Debug",newNote.getBytes().toString());
into
Log.w("Debug",newNote);
and you will have proper Log output, and File should be written properly already.
Hope this helps and enjoy your work
Just a shot in the dark, but I notice you're calling getBytes() without specifying the character encoding. Unless your output file is the same character encoding as the system default encoding, you could easily get gibberish on the output.

Anyway to perform follow up actions in catch block from try block

I have a need to save a xml file in a directory .....if it is not well formed.
Just to analyze it for the reason for the failure.
How do i save the xml request in a directory in catch block?
i tried doing it..but the variables created in the try block seems undefined in catch block. I am a newbie...sorry if its a basic question. any solutions?
try {
Create a well formed xml request
open a http connection and post it
}
//catching all exceptions here
catch (Exception e) {
e.printStackTrace();
}
The {} braces are scoping the variables that are inside your try block, so they're not available outside of that scope. You could do something like this:
String xml = null;
try {
xml = ...; //Create a well formed xml request
//open a http connection and post it
} catch (Exception e) {
if (xml != null) {
// write XML to file
}
}
If you define your variable outside/before the try block, you can use it inside the catch. Really though, you should consider why you are using try/catch error handling as flow control.
You have to declare the variable outside of the try block, then it would work
XmlDocument xml = null;
try {
xml = Create a well formed xml request
open a http connection and post it
}
catch (Exception e) {
xml.save();
}
As you said, any variable declared inside the try block is not available in the catch block, so you have to place it outside
if you create a new element in an inner block it is unreachable out of it.
So if you create something in try block it is just visible on it. You cannot reach that out of the block.
So for your problem you should create xml request out of try block.
Something like this;
Create a well formed xml request
try {
open a http connection and post it
}
//catching all exceptions here
catch (Exception e) {
e.printStackTrace();
}

Re-reading a file after EOF using NIO (Java)

I'm using MemoryMapped buffer to read a file. Initially I'm getting the channel size and using the same size I"m mapping the file on memory and here the initial position is 0 as I want to map the file from the beginning. Now another 400KB of data is added to that file, now I want to map that 400kb alone. But something is wrong in my code, I'm not able to figure it out and I'm getting this
260java.io.IOException: Channel not open for writing - cannot extend file to required size
at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:812)
at trailreader.main(trailreader.java:55
So here's my code
BufferedWriter bw;
FileInputStream fileinput = null;
try {
fileinput = new FileInputStream("simple.csv");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileChannel channel = fileinput.getChannel();
MappedByteBuffer ByteBuffer;
try {
ByteBuffer = fileinput.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* Add some 400 bytes to simple.csv. outside of this program...
*/
//following line throw exception.
try {
ByteBuffer = fileinput.getChannel().map(FileChannel.MapMode.READ_ONLY, channel.size(), 400);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So in my code I'm trying to reread the additional data that has been added but its not working, I know the prob is channel.size(), but I'm not able to rectify it.
channel.size() is always the current end of file. You are attempting to map 400 bytes past it. It isn't there. You need something like:
ByteBuffer = fileinput.getChannel().map(FileChannel.MapMode.READ_ONLY, channel.size()-400, 400);

Categories

Resources