WritableByteChannel into BLOB - spring

I have to extend an existing source code. I have this method:
public final int copyStreams(InputStream in, OutputStream out, long sizeLimit) throws IOException
{
int byteCount = 0;
IOException error = null;
long totalBytesRead = 0;
try
{
byte[] buffer = new byte[BYTE_BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) != -1)
{
// We are able to abort the copy immediately upon limit violation.
totalBytesRead += bytesRead;
if (sizeLimit > 0 && totalBytesRead > sizeLimit)
{
StringBuilder msg = new StringBuilder();
msg.append("Content size violation, limit = ")
.append(sizeLimit);
throw new ContentLimitViolationException(msg.toString());
}
out.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
out.flush();
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
error = e;
logger.error("Failed to close output stream: " + this, e);
}
try
{
out.close();
}
catch (IOException e)
{
error = e;
logger.error("Failed to close output stream: " + this, e);
}
}
if (error != null)
{
throw error;
}
return byteCount;
}
and this is my main class:
public static void main (String[] arg)
{
InputStream in = new FileInputStream("pathToMyFile");
ContentLimitProvider contentLimitProvider = getContentLimitProvider();
final long sizeLimit = contentLimitProvider.getSizeLimit();
int byteCount = sizeLimitedStreamCopier.copyStreams(in, out, sizeLimit);
return byteCount;
}
and this is the method I'm forced to use to build my outputStream
public OutputStream getContentOutputStream() throws ContentIOException
{
try
{
WritableByteChannel channel = getWritableChannel();
OutputStream is = new BufferedOutputStream(Channels.newOutputStream(channel));
// done
return is;
}
catch (Throwable e)
{
throw new ContentIOException("Failed to open stream onto channel: \n" +
" writer: " + this,
e);
}
}
How can I develop a getWritableChannel() method in order to write into a BLOB field inside a Database DataTable (RBDMS). I'd like to use Spring if it is necessary.

Related

NullException on Bitmap ,bitmaps is getting null value

I'm trying to get multiple images from the gallery, show it in >Recyclerview, and sending it to server but showing this error >Here's my code to write the images to file,the error is at the >initialization of inputstream
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("Data any THING", String.valueOf(data));
if (requestCode == ImagePicker.IMAGE_PICKER_REQUEST_CODE && resultCode == RESULT_OK) {
List<String> mPaths = data.getStringArrayListExtra(ImagePicker.EXTRA_IMAGE_PATH);
Log.d("mPaths MainActivity", String.valueOf(mPaths));
for (int i = 0; i < mPaths.size(); i++) {
files.add(new File(mPaths.get(i)));
}
if (inputStream==null) {
for (int i = 0; i < files.size(); i++) {
try {
inputStream = getContentResolver().openInputStream(Uri.fromFile( files.get(i)));
Toast.makeText(this, "Inputstream"+String.valueOf(inputStream), Toast.LENGTH_SHORT).show();
bitmaps = BitmapFactory.decodeStream(inputStream);
Log.e("File", String.valueOf(files));
Log.e("stream", String.valueOf(inputStream));
editText.setText(String.valueOf(files)+String.valueOf(inputStream));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Log.d("DATASSSSSSSSSSSTTTT", String.valueOf(data.getData()));
Log.e("IMages From Stream", String.valueOf(bitmaps));
Log.d("Images from Steam", String.valueOf(bitmaps));
recyclerAdapter.fileMOthod(files);
if (bitmaps != null) {
resizeIMagestoAdapter();
imageResize(bitmaps);
} else {
}
}
}
}
}
The files array has only indices 0 to files.size()-1, but your i variable goes from 0 to files.size() in the loop:
for (int i = 0; i < files.size()+1; i++)
Therefore, files.get(i) fails with the IndexOutOfBoundsException.
Index: 2, Size: 2 means that the size of files is 2 (it has only indices 0 and 1), but you are trying to access index 2.

Adding Object[] method to main()

I am trying to pass this method through my main() function but The loadMap already has the bufferreader so I am trying to use that rather than creating my own new buffer reader. How can I do this?
public static void main(String args[]) {
//throw exceptions here if args is empty
filename = args[0];
System.out.println(MapIO.loadMap(filename)[0]);
System.out.println(MapIO.loadMap(filename)[1]);
if (args.length < 1) {
System.err.println("Usage:\n" +"java CrawlGui mapname");
System.exit(1);
}
List<String> names=new LinkedList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(new
File(filename)))) {
String line;
while ((line = reader.readLine()) != null)
names.add(line);
System.out.println(names);
} catch (IOException e) {
e.printStackTrace();
}
MapIO.loadMap(filename);
launch(args);
}
/** Read information from a file created with saveMap
* #param filename Filename to read from
* #return null if unsucessful. If successful, an array of two Objects.
[0] being the Player object (if found) and
[1] being the start room.
* #detail. Do not add the player to the room they appear in, the caller
will be responsible for placing the player in the start room.
*/
public static Object[] loadMap(String filename) {
Player player = null;
try {
BufferedReader bf = new BufferedReader(
new FileReader(filename));
String line = bf.readLine();
int idcap = Integer.parseInt(line);
Room[] rooms = new Room[idcap];
for (int i = 0; i < idcap; ++i) {
line = bf.readLine();
if (line == null) {
return null;
}
rooms[i] = new Room(line);
}
for (int i = 0; i < idcap; ++i) { // for each room set up exits
line = bf.readLine();
int exitcount=Integer.parseInt(line);
for (int j=0; j < exitcount; ++j) {
line = bf.readLine();
if (line == null) {
return null;
}
int pos = line.indexOf(' ');
if (pos < 0) {
return null;
}
int target = Integer.parseInt(line.substring(0,pos));
String exname = line.substring(pos+1);
try {
rooms[i].addExit(exname, rooms[target]);
} catch (ExitExistsException e) {
return null;
} catch (NullRoomException e) {
return null;
}
}
}
for (int i = 0;i<idcap;++i) {
line = bf.readLine();
int itemcount = Integer.parseInt(line);
for (int j = 0; j < itemcount; ++j) {
line = bf.readLine();
if (line == null) {
return null;
}
Thing t = decodeThing(line, rooms[0]);
if (t == null) {
return null;
}
if (t instanceof Player) { // we don't add
player = (Player)t; // players to rooms
} else {
rooms[i].enter(t);
}
}
}
Object[] res = new Object[2];
res[0] = player;
res[1] = rooms[0];
return res;
} catch (IOException ex) {
return null;
} catch (IndexOutOfBoundsException ex) {
return null;
} catch (NumberFormatException nfe) {
return null;
}
}
You shouldn't do anything in main() other than call launch(). Move all the other startup code to your start() method. You can get the content of the args array using getParameters().getRaw():
#Override
public void start(Stage primaryStage) {
//throw exceptions here if args is empty
filename = getParameters().getRaw().get(0);
System.out.println(MapIO.loadMap(filename)[0]);
System.out.println(MapIO.loadMap(filename)[1]);
if (args.length < 1) {
System.err.println("Usage:\n" +"java CrawlGui mapname");
System.exit(1);
}
List<String> names=new LinkedList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(new
File(filename)))) {
String line;
while ((line = reader.readLine()) != null)
names.add(line);
System.out.println(names);
} catch (IOException e) {
e.printStackTrace();
}
Object[] whateverThisThingIs = MapIO.loadMap(filename);
// Now you have access to everything you need, at the point where you need it.
// existing start() code goes here...
}
public static void main(String args[]) {
launch(args);
}

Null pointer Exception while reversing a Queue using stack

I was practicing on how to implement queue using arrays. I have easily implemented how to enqueue and dequeue the elements in queue. But I have encountered an exception while implementing reverse of queue using stacks
public class QueueImpl {
private int capacity;
int queueArr[];
int front = 0;
int rear = -1;
int currentSize = 0;
QueueImpl(int queueSize){
this.capacity=queueSize;
queueArr=new int[this.capacity];
}
public void enqueue(int data){
if(isQueueFull()){
System.out.println("Overflow");
return;
}
else{
rear=rear+1;
if(rear==capacity-1)
{
rear=0;
}
queueArr[rear]=data;
currentSize++;
System.out.println("Element " + data+ " is pushed to Queue !");
}
}
public int dequeue(){
if(isQueueEmpty()){
System.out.println("UnderFlow");
}
else{
front=front+1;
if(front == capacity-1){
System.out.println("Pop operation done ! removed: "+queueArr[front-1]);
front = 0;
} else {
System.out.println("Pop operation done ! removed: "+queueArr[front-1]);
}
currentSize--;
}
return queueArr[front-1];
}
private boolean isQueueEmpty() {
boolean status=false;
if(currentSize==0){
status=true;
}
return status;
}
private boolean isQueueFull() {
boolean status=false;
if(currentSize==capacity){
status=true;
}
return status;
}
public static void main(String arg[]) {
QueueImpl queueImpl=new QueueImpl(5);
queueImpl.enqueue(5);
queueImpl.enqueue(2);
queueImpl.enqueue(9);
queueImpl.enqueue(1);
// queueImpl.dequeue();
queueImpl.printQueue(queueImpl);
queueImpl.reverse(queueImpl);
}
private void printQueue(QueueImpl queueImpl) {
System.out.println(queueImpl.toString());
}
#Override
public String toString() {
return "Queue [front=" + front + ", rear=" + rear + ", size=" + currentSize
+ ", queue=" + Arrays.toString(queueArr) + "]";
}
private QueueImpl reverse(QueueImpl queueImpl) throws ArrayIndexOutOfBoundsException {
int i=0;
Stack<Integer> stack=new Stack<Integer>();
while(!queueImpl.isQueueEmpty()){
stack.push(queueImpl.dequeue());
}
while(!stack.isEmpty()){
stack.get(i);
i++;
}
while(!stack.isEmpty()){
queueImpl.enqueue(stack.pop());
}
return queueImpl;
}
}
The error log is -
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at com.tcs.QueueUsingAraay.QueueImpl.dequeue(QueueImpl.java:51)
at com.tcs.QueueUsingAraay.QueueImpl.reverse(QueueImpl.java:93)
at com.tcs.QueueUsingAraay.QueueImpl.main(QueueImpl.java:78)
There was a problem in your dequeue method:
1. you were making front=0 and were trying to access front-1 which was -1
as a result the exception was thrown.
Removed stack.get as it was not required.
Corrected working code.
public class QueueImpl {
private int capacity;
int queueArr[];
int front = 0;
int rear = -1;
int currentSize = 0;
QueueImpl(int queueSize) {
this.capacity = queueSize;
queueArr = new int[this.capacity];
}
public void enqueue(int data) {
if (isQueueFull()) {
System.out.println("Overflow");
return;
} else {
rear = rear + 1;
if (rear == capacity - 1) {
rear = 0;
}
queueArr[rear] = data;
currentSize++;
System.out.println("Element " + data + " is pushed to Queue !");
}
}
public int dequeue() {
int element=-1;
if (isQueueEmpty()) {
System.out.println("UnderFlow");
} else {
element = queueArr[front];
front=front+1;
if (front == capacity - 1) {
System.out.println("Pop operation done ! removed: "
+ queueArr[front - 1]);
front = 0;
} else {
System.out.println("Pop operation done ! removed: "
+ queueArr[front - 1]);
}
currentSize--;
}
return element;
}
private boolean isQueueEmpty() {
boolean status = false;
if (currentSize == 0) {
status = true;
}
return status;
}
private boolean isQueueFull() {
boolean status = false;
if (currentSize == capacity) {
status = true;
}
return status;
}
public static void main(String arg[]) {
QueueImpl queueImpl = new QueueImpl(5);
queueImpl.enqueue(5);
queueImpl.enqueue(2);
queueImpl.enqueue(9);
queueImpl.enqueue(1);
queueImpl.printQueue(queueImpl);
queueImpl.reverse(queueImpl);
queueImpl.printQueue(queueImpl);
}
private void printQueue(QueueImpl queueImpl) {
System.out.println(queueImpl.toString());
}
#Override
public String toString() {
return "Queue [front=" + front + ", rear=" + rear + ", size="
+ currentSize + ", queue=" + Arrays.toString(queueArr) + "]";
}
private QueueImpl reverse(QueueImpl queueImpl)
throws ArrayIndexOutOfBoundsException {
Stack<Integer> stack = new Stack<Integer>();
while (!queueImpl.isQueueEmpty()) {
stack.push(queueImpl.dequeue());
}
while (!stack.isEmpty()) {
queueImpl.enqueue(stack.pop());
}
return queueImpl;
}
}

I wonder why logcat says "NO SUCH A FILE OR DIRECTORY(2)"

I wanna play audio on Android with ffmpeg.
But when I run this project, error has occurred
what should I do?
java SIDE
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.SystemClock;
public class FFmpegBasic extends Activity
{
private AudioTrack track;
private FileOutputStream os;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
createEngine();
int bufSize = AudioTrack.getMinBufferSize(44100,
AudioFormat.CHANNEL_CONFIGURATION_STEREO,
AudioFormat.ENCODING_PCM_16BIT);
track = new AudioTrack(AudioManager.STREAM_MUSIC,
44100,
AudioFormat.CHANNEL_CONFIGURATION_STEREO,
AudioFormat.ENCODING_PCM_16BIT,
bufSize,
AudioTrack.MODE_STREAM);
byte[] bytes = new byte[bufSize];
try {
os = new FileOutputStream("/sdcard/a.out",false);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String result = "/mnt/sdcard/Wildlife.mp3";
loadFile(result,bytes);
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void playSound(byte[] buf, int size) {
if(track.getPlayState()!=AudioTrack.PLAYSTATE_PLAYING)
track.play();
track.write(buf, 0, size);
try {
os.write(buf,0,size);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private native void createEngine();
private native void loadFile(String file, byte[] array);
/** Load jni .so on initialization*/
static {
System.loadLibrary("avutil");
System.loadLibrary("avcore");
System.loadLibrary("avcodec");
System.loadLibrary("avformat");
System.loadLibrary("avdevice");
System.loadLibrary("swscale");
System.loadLibrary("avfilter");
System.loadLibrary("ffmpeg");
System.loadLibrary("basicplayer");
}
}
c SIDE
#include <assert.h>
#include <jni.h>
#include <string.h>
#include <android/log.h>
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "avcodec.h"
#include "avformat.h"
void Java_net_jbong_FFmpegBasic_FFmpegBasic_createEngine(JNIEnv* env, jclass clazz)
{
//avcodec_init();
av_register_all();
}
void Java_net_jbong_FFmpegBasic_FFmpegBasic_loadFile(JNIEnv* env, jobject obj, jstring file, jbyteArray array)
{
AVFormatContext *gFormatCtx = NULL;
AVCodecContext *gAudioCodecCtx = NULL;
AVCodec *gAudioCodec = NULL;
int gAudioStreamIdx = -1;
char *gAudioBuffer = NULL;
int i, outsize = 0;
AVPacket packet;
const char *str;
str = (*env)->GetStringUTFChars(env, file, NULL);
jclass cls = (*env)->GetObjectClass(env, obj);
jmethodID play = (*env)->GetMethodID(env, cls, "playSound", "([BI)V");
if (gFormatCtx != NULL)
return -1;
if (av_open_input_file(&gFormatCtx,str,NULL,0,NULL)!=0)
return -2;
if (av_find_stream_info(gFormatCtx) < 0)
return -3;
for(i=0; i<gFormatCtx->nb_streams; i++)
{
if(gFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
{
gAudioStreamIdx = i;
break;
}
}
if (gAudioStreamIdx == -1)
return -4;
gAudioCodecCtx = gFormatCtx->streams[gAudioStreamIdx]->codec;
gAudioCodec = avcodec_find_decoder(gAudioCodecCtx->codec_id);
if (gAudioCodec == NULL)
return -5;
if (avcodec_open(gAudioCodecCtx, gAudioCodec)<0)
return -6;
gAudioBuffer = (char *)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE *2);
int decode = 0;
while (av_read_frame(gFormatCtx, &packet) >= 0)
{
if (gFormatCtx-> streams[packet.stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
{
int data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE * 8;
gAudioBuffer = (char *)av_malloc(data_size);
int size=packet.size;
while(size > 0)
{
int len = avcodec_decode_audio3(gAudioCodecCtx,
(short *) gAudioBuffer, &data_size, &packet);
if (data_size > 0)
{
jbyte *bytes = (*env)->GetByteArrayElements(env, array, NULL);
memcpy(bytes + decode, (int16_t *)gAudioBuffer, size);
(*env)->ReleaseByteArrayElements(env, array, bytes, 0);
(*env)->CallVoidMethod(env, obj, play, array, data_size);
decode += size;
size -= len;
}
}
}
av_free_packet(&packet);
}
av_close_input_file(gFormatCtx);
return 0;
}
Why my android logcat show me this message ?
"error opening trace file: No such file or directory (2)"
What's you playback url? you can check your ffmpeg protocal if support? ffmpeg -protocol

Blackberry Listfield with Live Image

I want to display a listfield with live image in all rows of the listfield
check out this
also use the following code for displaying live images:
public static String getImageFromUrl(String url) {
//Image img = null;
String imageData = null;
try
{
imageData = getDataFromUrl(url);
//img = Image.createImage(imageData.getBytes(), 0,imageData.length() );
}
catch(Exception e1) {
e1.printStackTrace();
}
return imageData;
}
public static String getDataFromUrl(String url)
throws IOException {
StringBuffer b = new StringBuffer();
InputStream is = null;
HttpConnection c = null;
long len = 0 ;
int ch = 0;
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
if (connDesc != null)
{
//HttpConnection httpConn;
c = (HttpConnection)connDesc.getConnection();
}
// c = (HttpConnection)Connector.open(url);
is = c.openInputStream();
len = c.getLength();
if( len != -1) {
// Read exactly Content-Length bytes
for(int i =0 ; i < len ; i++ )
if((ch = is.read()) != -1) {
b.append((char) ch);
}
} else {
//Read until the connection is closed.
while ((ch = is.read()) != -1) {
len = is.available() ;
b.append((char)ch);
}
}
is.close();
c.close();
return b.toString();
}
Hope this will help you.

Resources