j2me netbeans - parallel data transfer (outline idea required) - netbeans

I am new to j2me Mobile Applications. I have a college project to be done within a month. I need some basic idea of how it can be done. I am using Netbeans 6.8 j2me platform.
I have to create source, destination and many intermediate nodes(mobile phones). A file has to be sent(am using Bluetooth) from source to destination via several intermediate nodes. The file can be split into chunks and can also be sub-divided at any level.
http://imageshack.us/photo/my-images/692/parallelism.jpg/
This is how it should work:
Initially, the source sends simple objects of a Class(present in all nodes) to destination via several paths. Every node will be updating the object by including its Bluetooth address and passes it to the next node. When it reaches the destination, the same object is sent back to the source. The source identifies some of the optimal paths and uses them for file transfer.
The source splits the file and send them to the nearest nodes. The intermediate nodes can also split and send the divided parts.
When all the parts reach the destination, they are joined and the file is reconstructed.
I created separate netbeans project for source, destination and intermediate node.
Splitting : I did splitting successfully by converting the file into byte array and creating files using File connection & outputstream
public void splitfiles(int len)
{
String url="file:///root1/testfile.jpg";
// int len = 102400;
byte buffer[] = new byte[size];
int count = 0;
try
{
FileConnection fconi = (FileConnection)Connector.open(url,Connector.READ);
InputStream fis = fconi.openInputStream();
while (true)
{
int i = fis.read(buffer, 0, len); //creating byte array of size "len" bytes
if (i == -1)
break;
++count;
String filename ="file:///root1/testfile.part" + count;
FileConnection fcono = (FileConnection)Connector.open(filename,Connector.READ_WRITE);
if (!fcono.exists())
fcono.create();
OutputStream fos = fcono.openOutputStream();
fos.write(buffer, 0, i); //creating files out of byte array "buffer"
fos.close();
fcono.close();
}
}
catch(Exception e)
{ }
}
Please tell me how to rejoin the files.(I rejoined them using java class "RandomAcessFile" which is not present in j2me).
I tried in the following way
while(number of chunks)
{
read a single file in inputstream (files are read one after the other)
copy it to a byte array and flush inputstream
write it to ouputstream
}
copy outputstream to a file
flush outputstream
Please give me some idea about
how to rejoin the chunks in j2me
How to pass object of a class via bluetooth

Related

Why is my Sphinx4 Recognition poor?

I am learning how to use Sphinx4 using the Maven plug-in for Eclipse.
I took the transcribe demo found on GitHub and altered it to process a file of my own. The audio file is 16bit, mono, 16khz. It is approximately 13 seconds long. I noticed that it sounds like it is in slow motion.
The words spoken in the file are, "also make sure it's easy for you to access the recording files so you could upload it if asked".
I am attempting to transcribe the file and my results are horrendous. My attempts at finding forum posts or links that thoroughly explain how to improve the results, or what I am not doing correctly have lead me no where.
I am looking to strengthen the accuracy of the transcription, but would like to avoid having to train a model myself due to the variance in the type of data that my current project will have to deal with. Is this not possible, and is the code I am using off?
CODE
(NOTE: Audio file available at https://instaud.io/8qv)
public class App {
public static void main(String[] args) throws Exception {
System.out.println("Loading models...");
Configuration configuration = new Configuration();
// Load model from the jar
configuration
.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
// You can also load model from folder
// configuration.setAcousticModelPath("file:en-us");
configuration
.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");
configuration
.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.dmp");
StreamSpeechRecognizer recognizer = new StreamSpeechRecognizer(
configuration);
FileInputStream stream = new FileInputStream(new File("/home/tmscanlan/workspace/example/vocaroo_test_revised.wav"));
// stream.skip(44); I commented this out due to the short length of my file
// Simple recognition with generic model
recognizer.startRecognition(stream);
SpeechResult result;
while ((result = recognizer.getResult()) != null) {
// I added the following print statements to get more information
System.out.println("\ngetWords() before loop: " + result.getWords());
System.out.format("Hypothesis: %s\n", result.getHypothesis());
System.out.print("\nThe getResult(): " + result.getResult()
+ "\nThe getLattice(): " + result.getLattice());
System.out.println("List of recognized words and their times:");
for (WordResult r : result.getWords()) {
System.out.println(r);
}
System.out.println("Best 3 hypothesis:");
for (String s : result.getNbest(3))
System.out.println(s);
}
recognizer.stopRecognition();
// Live adaptation to speaker with speaker profiles
stream = new FileInputStream(new File("/home/tmscanlan/workspace/example/warren_test_smaller.wav"));
// stream.skip(44); I commented this out due to the short length of my file
// Stats class is used to collect speaker-specific data
Stats stats = recognizer.createStats(1);
recognizer.startRecognition(stream);
while ((result = recognizer.getResult()) != null) {
stats.collect(result);
}
recognizer.stopRecognition();
// Transform represents the speech profile
Transform transform = stats.createTransform();
recognizer.setTransform(transform);
// Decode again with updated transform
stream = new FileInputStream(new File("/home/tmscanlan/workspace/example/warren_test_smaller.wav"));
// stream.skip(44); I commented this out due to the short length of my file
recognizer.startRecognition(stream);
while ((result = recognizer.getResult()) != null) {
System.out.format("Hypothesis: %s\n", result.getHypothesis());
}
recognizer.stopRecognition();
System.out.println("...Printing is done..");
}
}
Here is the output (a photo album I took): http://imgur.com/a/Ou9oH
As Nikolay says, the audio sounds odd, probably because you haven't resampled it in the right way.
To downsample the audio from the original 22050 Hz to the desired 16kHz, you can run the following command:
sox Vocaroo.wav -r 16000 Vocaroo16.wav
The Vocaroo16.wav will sounds much better and it will (probably) give you better ASR results.

how to zip all files with asp.net 3.5

i 'm .net developer. i want to Zip all files and make a one zip file with this technique.
ZipFile multipleFilesAsZipFile = new ZipFile();
Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".zip");
Response.ContentType = "application/zip";
for (int i = 0; i < filename.Length; i++)
{
string filePath = Server.MapPath("~/PostFiles/" + filename[i]);
multipleFilesAsZipFile.AddFile(filePath, string.Empty);
}
multipleFilesAsZipFile.Save(Response.OutputStream);
how ever for making this Zip i use third party library Ionic.
all files are ziped successfully but not extracted to client desktop. is there problem with my code. or this library that i'm using has been expired.
Is there free full version .net compatible library to zip all files.
Use SharpZipLib:
Nuget Package
Install-Package SharpZipLib
OR Download here
http://www.icsharpcode.net/OpenSource/SharpZipLib/
Snippet from examples:
private void CompressFolder(string path, ZipOutputStream zipStream, int folderOffset) {
string[] files = Directory.GetFiles(path);
foreach (string filename in files) {
FileInfo fi = new FileInfo(filename);
string entryName = filename.Substring(folderOffset); // Makes the name in zip based on the folder
entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction
ZipEntry newEntry = new ZipEntry(entryName);
newEntry.DateTime = fi.LastWriteTime; // Note the zip format stores 2 second granularity
// Specifying the AESKeySize triggers AES encryption. Allowable values are 0 (off), 128 or 256.
// A password on the ZipOutputStream is required if using AES.
// newEntry.AESKeySize = 256;
// To permit the zip to be unpacked by built-in extractor in WinXP and Server2003, WinZip 8, Java, and other older code,
// you need to do one of the following: Specify UseZip64.Off, or set the Size.
// If the file may be bigger than 4GB, or you do not need WinXP built-in compatibility, you do not need either,
// but the zip will be in Zip64 format which not all utilities can understand.
// zipStream.UseZip64 = UseZip64.Off;
newEntry.Size = fi.Length;
zipStream.PutNextEntry(newEntry);
// Zip the file in buffered chunks
// the "using" will close the stream even if an exception occurs
byte[ ] buffer = new byte[4096];
using (FileStream streamReader = File.OpenRead(filename)) {
StreamUtils.Copy(streamReader, zipStream, buffer);
}
zipStream.CloseEntry();
}
string[ ] folders = Directory.GetDirectories(path);
foreach (string folder in folders) {
CompressFolder(folder, zipStream, folderOffset);
}
}
Taken from : https://github.com/icsharpcode/SharpZipLib/wiki/Zip-Samples
Works awesome!

Android-java Fil transfer over TCP byte missing

sending side- It is in android and it is part of AsyncTask, doInBackground. Basically, it will send file name, size, and image data to serverside.
InetAddress serverIP = InetAddress.getByName(IP);
Socket client = new Socket(serverIP,SERVER_PORT);
System.out.println("Connected to Server\n");
System.out.println(imgFile.length());
//sending name of the file
PrintWriter name = new PrintWriter(new OutputStreamWriter(client.getOutputStream()),true);
name.println(fileName);
name.flush();
//sending size of the file
name.println(imgFile.length());
name.flush();
//sending body
DataInputStream imgBodyIn = new DataInputStream(new FileInputStream(imgFile));
DataOutputStream imgBodyOut = new DataOutputStream(client.getOutputStream());
byte[] buffer = new byte[BUFFER_SIZE];
int len;
long filesize = imgFile.length();
while(filesize >=0&& (len=imgBodyIn.read(buffer,0,(int)Math.min(buffer.length,filesize)))>0){
imgBodyOut.write(buffer,0,len);
filesize-=len;
}
name.close();
imgBodyIn.close();
imgBodyOut.flush();
imgBodyOut.close();
client.close();
Receiving side
//receiving name
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String name = in.readLine();
System.out.println("Name of the File : " + name+".JPG");
//receiveing size info
String size = in.readLine();
System.out.println("Size of the File :"+size +"bytes");
//storing file
File f = new File("/home/ubuntu", name+".JPG");
FileOutputStream output = new FileOutputStream(f);
int len=0;
long received=0;
byte[] buf = new byte[BUFFER];
while(received<=Long.parseLong(size)&&(len=sock.getInputStream().read(buf))>0)
{
output.write(buf,0,len);
received +=len;
System.out.print("Receiving.."+received +"/"+size+"\r");
}
output.flush();
output.close();
in.close();
System.out.println("\n"+name+".JPG received");
System.out.println("Size received :"+f.length()+"bytes");
when I tried to send a file, correct size info and name are transferred. However, I could not receive full file; some bytes are missing. Buffer size I am using is 1024.
Sample run :
Waiting for client to connect..
Client Accepted
Name of the File : P1011474.JPG
Size of the File :714438bytes
Receiving..712997/714438
P1011474.JPG received
Size received :712997bytes
socket closed
Most likely it's the BufferedReader on the receiving side, which contains an internal buffer to improve performance when reading from the stream. See Javadoc:
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
So it won't just read the two lines, but might as well read ahead after your two lines. Therefore a part of the binary image you appended might be buffered as well. When you then try to read the binary data directly from the InputStream wrapped with DataInputStream, you won't receive the bytes which were already buffered in the BufferedReader instance.
I would suggest, that you don't use a PrintWriter but instead write the file name and length directly using methods from DataOutputStream, e.g.:
out.writeUTF(fileName);
out.writeLong(imgFile.length());
On the receiving side use the read* methods of DataInputStream, instead of the BufferedReader. If you want to buffer, wrap the socket InputStream in a BufferedInputStream:
DataInputStream dis = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String fileName = dis.readUTF();
long fileLength = dis.readLong();
// now read file contents from stream
And by the way, you don't have to do:
imgBodyIn.read(buffer,0,(int)Math.min(buffer.length,filesize))
when reading in the image from a file, just do:
imgBodyIn.read(buffer, 0, buffer.length)
The end of stream/file is recognized and read() will return the length of bytes read, so you don't need to do Math.min().

Upload Servlet with custom file keys

I have built a Server that you can upload files to and download, using Eclipse, servlet and jsp, it's all very new to me. (more info).
Currently the upload system works with the file's name. I want to programmatically assign each file a random key. And with that key the user can download the file. That means saving the data in a config file or something like : test.txt(file) fdjrke432(filekey). And when the user inputs the filekey the servlet will pass the file for download.
I have tried using a random string generator and renameTo(), for this. But it doesn't work the first time, only when I upload the same file again does it work. And this system is flawed, the user will receive the file "fdjrke432" instead of test.txt, their content is the same but you can see the problem.
Any thoughts, suggestions or solutions for my problem?
Well Sebek, I'm glad you asked!! This is quite an interesting one, there is no MAGIC way to do this. The answer is indeed to rename the file you uploaded. But I suggest adding the random string before the name of the file; like : fdjrke432test.txt.
Try this:
filekey= RenameRandom();
File renamedUploadFile = new File(uploadFolder + File.separator+ filekey+ fileName);
item.write(renamedUploadFile);
//remember to give the user the filekey
with
public String RenameRandom()
{
final int LENGTH = 8;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random()*26)+97));
}
System.out.println(sb.toString());
return sb.toString();
}
To delete or download the file from the server you will need to locate it, the user will input the key, you just need to search the upload folder for a file that begins with that key:
filekey= request.getParameter("filekey");
File f = new File(getServletContext().getRealPath("") + File.separator+"data");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(filekey);
}
});
String newfilename = matchingFiles[0].getName();
// now delete or download newfilename

Custom clipboard data format accross RDC (.NET)

I'm trying to copy a custom object from a RDC window into host (my local) machine. It fails.
Here's the code that i'm using to 1) copy and 2) paste:
1) Remote (client running on Windows XP accessed via RDC):
//copy entry
IDataObject ido = new DataObject();
XmlSerializer x = new XmlSerializer(typeof(EntryForClipboard));
StringWriter sw = new StringWriter();
x.Serialize(sw, new EntryForClipboard(entry));
ido.SetData(typeof(EntryForClipboard).FullName, sw.ToString());
Clipboard.SetDataObject(ido, true);
2) Local (client running on local Windows XP x64 workstation):
//paste entry
IDataObject ido = Clipboard.GetDataObject();
DataFormats.Format cdf = DataFormats.GetFormat(typeof(EntryForClipboard).FullName);
if (ido.GetDataPresent(cdf.Name)) //<- this always returns false
{
//can never get here!
XmlSerializer x = new XmlSerializer(typeof(EntryForClipboard));
string xml = (string)ido.GetData(cdf.Name);
StringReader sr = new StringReader(xml);
EntryForClipboard data = (EntryForClipboard)x.Deserialize(sr);
}
It works perfectly on the same machine though.
Any hints?
There are a couple of things you could look into:
Are you sure the serialization of the object truely converts it into XML? Perhaps the outputted XML have references to your memory space? Try looking at the text of the XML to see.
If you really have a serialized XML version of the object, why not store the value as plain-vanilla text and not using typeof(EntryForClipboard) ? Something like:
XmlSerializer x = new XmlSerializer(typeof(EntryForClipboard));
StringWriter sw = new StringWriter();
x.Serialize(sw, new EntryForClipboard(entry));
Clipboard.SetText(sw.ToString(), TextDataFormat.UnicodeText);
And then, all you'd have to do in the client-program is check if the text in the clipboard can be de-serialized back into your object.
Ok, found what the issue was.
Custom format names get truncated to 16 characters when copying over RDC using custom format.
In the line
ido.SetData(typeof(EntryForClipboard).FullName, sw.ToString());
the format name was quite long.
When i was receiving the copied data on the host machine the formats available had my custom format, but truncated to 16 characters.
IDataObject ido = Clipboard.GetDataObject();
ido.GetFormats(); //used to see available formats.
So i just used a shorter format name:
//to copy
ido.SetData("MyFormat", sw.ToString());
...
//to paste
DataFormats.Format cdf = DataFormats.GetFormat("MyFormat");
if (ido.GetDataPresent(cdf.Name)) {
//this not works
...