How to play .wav file from URL in web browser embed - Java - java

I want to play a .wav sound file in embed default media player in IE. Sound file is on some HTTP location. I am unable to sound it in that player.
Following is the code.
URL url = new URL("http://www.concidel.com/upload/myfile.wav");
URLConnection urlc = url.openConnection();
InputStream is = (InputStream)urlc.getInputStream();
fileBytes = new byte[is.available()];
while (is.read(fileBytes,0,fileBytes.length)!=-1){}
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
out.write(fileBytes);
Here is embed code of HTML.
<embed src="CallStatesTreeAction.do?ivrCallId=${requestScope.vo.callId}&agentId=${requestScope.vo.agentId}" type="application/x-mplayer2" autostart="0" playcount="1" style="width: 40%; height: 45" />
If I write in FileOutputStream then it plays well
If I replace my code of getting file from URL to my local hard disk. then it also works fine.
I don't know why I am unable to play file from HTTP. And why it plays well from local hard disk.
Please help.

Make sure you set the correct response type. IE is very picky in that regard.
[EDIT] Your copy loop is broken. Try this code:
URL url = new URL("http://www.concidel.com/upload/myfile.wav");
URLConnection urlc = url.openConnection();
InputStream is = (InputStream)urlc.getInputStream();
fileBytes = new byte[is.available()];
int len;
while ( (len = is.read(fileBytes,0,fileBytes.length)) !=-1){
response.getOutputStream.write(fileBytes, 0, len);
}
The problem with your code is: If the data isn't fetched in a single call to is.read(), it's not appended to fileBytes but instead the first bytes are overwritten.
Also, the output stream which you get from the response is already buffered.

Related

how to get file from this url , using java code?

To use google translate api I figured out this url
http://translate.google.com/translate_a/t?client=t&text=revenge&hl=en&sl=en&tl=hi&ie=UTF-8&oe=UTF-8&multires=1&otf=1&ssel=3&tsel=3&sc=1
If you click on it you will get a file in json format with accurate translation.
To retrieve this file using java program I wrote following code.
String word = "revenge";
System.setProperty("http.proxyHost", "172.30.0.16");
System.setProperty("http.proxyPort", "3128");
URL url = new URL("http://translate.google.com/translate_a/t?client=t&text="+word+"&hl=en&sl=en&tl=hi&ie=UTF-8&oe=UTF-8&multires=1&otf=1&ssel=3&tsel=3&sc=1");
url.openConnection();
InputStream reader = url.openStream();
FileOutputStream writer = new FileOutputStream("t");
byte[] buffer = new byte[153600];
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) > 0)
{
writer.write(buffer, 0, bytesRead);
buffer = new byte[153600];
}
writer.close();
reader.close();
But it shows following error
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://translate.google.com/translate_a/t?client=t&text=Moon&hl=en&sl=en&tl=hi&ie=UTF-8&oe=UTF-8&multires=1&otf=1&ssel=3&tsel=3&sc=1
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1403)
at java.net.URL.openStream(URL.java:1029)
at smsMain.main(smsMain.java:20
Hope to get some help. Because we are getting file manually but using program it is forbidden.
From Google Translate home page:
Google Translate API is available as a paid service. See the Pricing
and FAQ pages for details.
So getting an error is not really surprising.

Trouble at downloading sqlite database

My app needs to download a database from a link, heres the code I use to download the database adn save it on the sd card:
public void DownloadBD() {
try {
URL url = new URL(
"http://mylink/dbHandler.axd?SqliteDbVersion=0");
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot, "DirLaguna.db");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
fileOutput.close();
location = file.getAbsolutePath();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Everything seems to work fine, but at the moment I want to query the database (I'm using raw querys) an error appears saying that the tables don't exist.
After that, I tried debugging the application, and after that I get the error saying that the database is corrupted. I think that the downloading process is what is making the database corrupt.
Any help will be apreciated, if I'm missing some code to share please tell me so!
Thanks in advance!
1) The database you are downloading is sqlite database?
2) If yes, then you need to copy that in your application before you start using it.
The process will be something like you download the database in your Sd Card and as soon as its completed start copying it into your application so as it becomes part of your application, like this: http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
Make this happen in background by separate thread and then you are good to go and use it. Let me know if you face any problem or issue or I didn't provided you info what you meant.
Thanks
I suggest that first - you verify if the file is indeed a proper SQLite Database by moving it to your local machine filesystem and viewing it in a SQLite viewer application.
Several SQLite Database viewers are available. This post lists several of them : What are good open source GUI SQLite database managers?
This additional post discusses readymade database usage in Android : Ship an application with a database You can get several pointers from there.

Downloading a text file

I am trying to download a text file in Android, i know how to load image file, how different is text file downloading from it?
Moerover how to retrive contents from the downloaded file?
You are asking a few things, this should give you an idea of how to get a remote file using urlconnection and associated classes
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
URLConnection conn = u.openConnection();
fs = conn.getContentLength();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH_op = Environment.getExternalStorageDirectory()
+"//"+ filename;
f = new FileOutputStream(new File(PATH_op));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 ) {
f.write(buffer,0, len1);
completed += len1;
}
f.close();`enter code here`
There will be no difference in downloading the text file or image or XML. every thing is same. but the usage after getting the stream depends on the type of the content.
If its a Image we will decode the stream to convert it to an image.
If its a Text we need to read the content character by character until the whole content got read or got -1 as the character which denotes the end of the file.
When coming to the XML file file we will directly pass the input stream object to Parser.

java program download file is corrupt. Why?

I have created a java program that downloads a file from a URL part by part into several files, then reads the bytes from those files into the full downloaded object. It works by separating sections of the file to be downloaded into threads. Every time my program downloads a file it gets all of the bytes and the file size is correct, but sometimes with an image the picture is distorted. Other times the image is perfect. What would cause this?
code that individual threads use to download file parts:
URL xyz = new URL(urlStr);
URLConnection connection= xyz.openConnection();
// set the download range
connection.setRequestProperty("Range", "bytes="+fileOffset+"-");
connection.setDoInput(true);
connection.setDoOutput(true);
// set input stream and output stream
in = new BufferedInputStream(connection.getInputStream());
fos = new FileOutputStream("part_"+this.partNumber);
out = new BufferedOutputStream(fos, this.downloadFileSize);
// create buffer to read bytes from file into
byte[] contentBytes = new byte[downloadFileSize];
// read contents into buffer
in.read(contentBytes, 0, this.downloadFileSize);
out.write(contentBytes, 0, this.downloadFileSize);
code that puts file together:
int partSize=0;
//Create output stream
OutputStream saveAs = new FileOutputStream(fileName);
for(int i=0; i<filePieces;i++)
{
File file=new File("part_"+(i+1));
partSize=(int)file.length();
byte fileBuffer[]=new byte [partSize];
//Create input stream
InputStream is = new FileInputStream(file);
is.read(fileBuffer);
saveAs.write(fileBuffer);
is.close();
}
Without further details and sample code you're forcing any answers to be guesses. Here are mine:
You're using Readers and Writers when you should use Input- / OutputStreams.
You've messed up the synchronization somehow. Favour classes from the java.util.concurrent package over home grown synchronized solutions.

Parsing PDF files hosted in web servers

I have used iText to parse pdf files. It works well on local files but I want to parse pdf files which are hosted in web servers like this one:
"http://protege.stanford.edu/publications/ontology_development/ontology101.pdf"
but I don't know how??? Could you please answer me how to do this task using iText or other libraries... thx
You need to download the bytes of the PDF file. You can do this with:
URL url = new URL("http://.....");
URLConnection conn = url.getConnection();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { ..error.. }
if ( ! conn.getContentType().equals("application/pdf")) { ..error.. }
InputStream byteStream = conn.getInputStream();
try {
... // give bytes from byteStream to iText
} finally { byteStream.close(); }
Use the URLConnection class:
URL reqURL = new URL("http://www.mysite.edu/mydoc.pdf" );
URLConnection urlCon = reqURL.openConnection();
Then you can use the URLConnection method to retrieve the content. Easiest way:
InputStream is = urlCon.getInputStream();
byte[] b = new byte[1024]; //size of a buffer, can be any
int len;
while((len = is.read(b)) != -1){
//Store the content in preferred way
}
is.close();
Nothing to it. You can pass a URL directly into PdfReader, and let it handle the streaming for you:
URL url = new URL("http://protege.stanford.edu/publications/ontology_development/ontology101.pdf" );
PdfReader reader = new PDFReader( url );
The JavaDoc is your friend.

Categories