How to copy array into file in phonegap? - java

I have array of images as follows:
var imageArray = new Array(10);
function onCameraPicSuccess (imgData) {
imageArray.push("data:image/jpeg;base64," + imgData);
}
I am copying captured images into this array.
Now how to copy this array into file? I am using phonegap.
I want to copy into particular folder like myPhotos in my local place.
Any help?
Is it possible to do it in javascript?
Or should i call JAVA applet from javascript to write into file?

You can use the FileWriter API to write a string version of your data to the disk.
Quick Example
function win(writer) {
writer.onwrite = function(evt) {
console.log("write success");
};
writer.write(JSON.stringify(imageArray));
};
var fail = function(evt) {
console.log(error.code);
};
entry.createWriter(win, fail);
For the whole context, see the Full Example under the FileWriter API here.
You can use the FileReader API to read data back. Remember to call JSON.parse to turn it back to a JavaScript object.

Related

FileOutputStream in dart flutter

what's the equivalent fileoutputstream of java in dart?
Java code
file = new FileOutputStream(logFile, true);
byte[] input = "String".getBytes();
file.write(input);
java file output
String
Ive tried this in dart
Dart code
var file = File(logFile!.path).openWrite();
List input = "String".codeUnits;
file.write(input);
[String]
and every time I open the file again to append "String2" and "String3" to it, the output will be
[String][String2][String3]
as oppose to java's output
StringString3String3
to sum it up, is there a way to fix/workaround this?
why each array bytes written in dart will be a new array instead of append into an existing one?
You can achieve that by using File.writeAsString() and using FileMode.append.
Picking up your example, this would be:
var file = File(logFile!.path);
file.writeAsString("String", mode: FileMode.append);
did you try writeAsString() ?
import 'dart:io';
void main() async {
final filename = 'file.txt';
var file = await File(filename).writeAsString('some content');
// Do something with the file.
}

Best way to present data from a big excel file on a website

I have a big excel file and I want to show the data on my website. I have made a matlab and a Java program(script) that can extract the information I want from the excel file. How do I get the data to the website?
Should I have the matlab or java script running on a server and then make a javascript that in some way connects to the server? How would i do this?
Or should a make a javascript that directly reads the excel file?
I am a beginner in web development so I dont really know where to start...
I happened to do something like this while I had to analyze the grades I gave. What I did was export the Excel sheet as a CSV, and then put that in a website where I used JavaScript to first convert it to a JSON. This is the function I used to perform the conversion:
function csvJSON(csv){
var lines=csv.split("\n");
var result = [];
var headers=lines[0].split(",");
for(var i=1;i<lines.length;i++){
var obj = {};
var currentline=lines[i].split(",");
for(var j=0;j<headers.length;j++){
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
//return result; //JavaScript object
return JSON.stringify(result); //JSON
}
And then it was simple. to use. Let's say I put in a textarea the exported CSV, for instance:
Name,Grade1,Grade2
Bobby,87,12
Rakesh,9,3
//...
Then I called csvJSON() with this data to get:
[{"Name":"Bobby","Grade1":87,"Grade2":12},{"Name":"Rakesh","Grade1":9,"Grade2":3},/*...*/]
Which is especially easy to use. For instance:
var csv = ""; // get it from somewhere
var json = JSON.parse(csvJSON(csv));
for (int i = 0; i < json.length; i++)
{
var obj = json[i];
var name = obj.Name, Grade1 = obj.Grade1, Grade2 = obj.Grade2;
//Do something
}

Add comment to an ARFF file

this is my first question in this forum....
I'm making adata-mining application in java with the WEKA API.
I make first a pre-processing stage and when I save the ARFF file i would like to add a couple of lines (as comments) specifing the preprocessing task that i have done to the file...
the problem is that i don't know how to add comments to an ARFF file from the java WEKA API.
To save the file i use the class ArffSaver like this...
try {
ArffSaver saver = new ArffSaver();
saver.setInstances(dataPost);
saver.setFile(arffFile);
saver.writeBatch();
return true;
} catch (IOException ex) {
Logger.getLogger(Preprocesamiento.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
I would be really greatfull if someone could give some idea...
thanks!
You should AVOID writting comments on an .arff file, even more when writting it from Java. These files are very "parser-sensitive". The Weka API to create these files is restrictive for this particular reason.
Even though, you can always add your comments manually with the % symbol. This said, I wouldn't recommend you writting anything more than instances, attributes and values into an .arff file. ;-)
I don't see a reason to not write comments into the header of an ARFF file. The specification clearly says:
Lines that begin with a % are comments.
So while it is technically valid, it can be difficult if you want to use the ArffSaver#setFile method. This method does a lot of (convenient, but somewhat arbitrary and unspecified) work internally, until it finally calls
setDestination(new FileOutputStream(m_outputFile));
If this is not required, the easiest option is to write directly to an OutputStream, which then can simply be set as the destination for the ArffSaver. This can be wrapped in a small helper method, for example, like this:
static void writeArff(
Instances instances,
List<String> commentLines,
OutputStream outputStream) throws IOException
{
ArffSaver saver = new ArffSaver();
saver.setInstances(instances);
if (commentLines != null && !commentLines.isEmpty())
{
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(outputStream));
for (String commentLine : commentLines)
{
bw.write("% " + commentLine + "\n");
}
bw.write("\n");
bw.flush();
}
saver.setDestination(outputStream);
saver.writeBatch();
}
When calling it like this
List<String> comments = Arrays.asList("A comment", "Another one");
writeArff(instances, comments, outputStream);
then the given comments will be inserted at the top of the ARFF file.

How do i verify string content using Mockito in Java

I am new to using Mockito test framework. I need to unit test one method which return the the string content. Also the same contents will be stored in one .js file (i.e. "8.js").
How do I verify the the string contents returned from the method is as expected as i want.
Please find the below code for generating the .js file:
public String generateJavaScriptContents(Project project)
{
try
{
// Creating projectId.js file
FileUtils.mkdir(outputDir);
fileOutputStream = new FileOutputStream(outputDir + project.getId() + ".js");
streamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
StringTemplateGroup templateGroup =
new StringTemplateGroup("viTemplates", "/var/vi-xml/template/", DefaultTemplateLexer.class);
stringTemplate = templateGroup.getInstanceOf("StandardJSTemplate");
stringTemplate.setAttribute("projectIdVal", project.getId());
stringTemplate.setAttribute("widthVal", project.getDimension().getWidth());
stringTemplate.setAttribute("heightVal", project.getDimension().getHeight());
stringTemplate.setAttribute("playerVersionVal", project.getPlayerType().getId());
stringTemplate.setAttribute("finalTagPath", finalPathBuilder.toString());
streamWriter.append(stringTemplate.toString());
return stringTemplate.toString();
}
catch (Exception e)
{
logger.error("Exception occurred while generating Standard Tag Type Content", e);
return "";
}
}
The output of above method writes the .js file and the contents of that file are looks something below:
var projectid = 8; var playerwidth = 300; var playerheight =
250; var player_version = 1; .....
I have written the testMethod() using mockito to test this, however i am able to write the .js file successfully using the test method, but how do I verify its contents?
Can anyone help me to sort out this problem?
As #ƁukaszBachman mentions, you can read the contents from the js file. There are a couple of things to consider when using this approach:
The test will be slow, as you will have to wait for the js content to be written to the disk, read the content back from the disk and assert the content.
The test could theoretically be flaky because the entire js content may not be written to the disk by the time the code reads from the file. (On that note, you should probably consider calling flush() and close() on your OutputStreamWriter, if you aren't already.)
Another approach is to mock your OutputStreamWriter and inject it into the method. This would allow you to write test code similar to the following:
OutputStreamWriter mockStreamWriter = mock(OutputStreamWriter.class);
generateJavaScriptContents(mockStreamWriter, project);
verify(mockStreamWriter).append("var projectid = 8;\nvar playerwidth = 300;...");
http://mockito.googlecode.com/svn/branches/1.5/javadoc/org/mockito/Mockito.html#verify%28T%29
If you persist this *.js file on file system then simply create util method which will read it's contents and then use some sort of assertEquals to compare it with your fixed data.
Here is code for reading file contents into String.

Convert Byte Array from Action Script to Image in Java and save it

I am a .NET Developer, but the question I am having is not related to .NET
Please keep this in mind even if my question sounds very trivial.
This is my question:
We have an swf in the browser, which communicates with a java extension
Its done using Smartfox Server(Used for MMO apllications)
From the swf we are grabbing a portion of the screen as "Byte Array" in action script(3).
And in Java, we are calling a function that converts the ByteArray to Image and then saves it.
Our Java developer is encountering the error
java.lang.illegalArgumentException
when the java function executes.
So basically, what I would like to know is this:
How to accept the object type Byte Array from ActionScript in Java?
Whats Java object type that is mapped to Byte Array in ActionScript?
The conversion part is easy, I dare say.
Update:
The code in the ActionScript Section
public function savePhoto(uName:String, ba:ByteArray, descr:String):void{
var obj:Object = {};
obj.arr = ba;
obj.desc = descr;
sfsConnectobj.photoSectionSave(obj,"save");
}
public function photoSectionSave(targetObject:Object,type:String) {
sfs.sendXtMessage("trialjava", "save", targetObject);
}
The first function calls the SmartFox Extension in Java.
The extension name is "trialjava.js"
The Java Code that accepts the function is
public void handleRequest(String cmd, ActionscriptObject ao, User u, int fromRoom)
{
try {
ActionscriptObject arr = ao.getObj("arr");
String dirName="C:\\";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos;
oos = new ObjectOutputStream(bos);
oos.writeObject(ao.getObj("arr"));
oos.flush();
oos.close();
bos.close();
byte [] data = bos.toByteArray();
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(data));
ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Array reading not succesful. Error is: "+e);
}
}
Seems like there was a small mismatch in retrieving the objects by java.
Now the error is different.
Array reading not succesful. Error is:
java.io.NotSerializableException:
it.goto
andplay.smartfoxserver.lib.ActionscriptObject
Regards,
naveenj
flash.utils.ByteArray is mapped to Java's byte[] type.
I am not sure if this is an issue, but according to Flash security model, if SWF is loading media from any host/domain other that the one it was loaded, screen capture would result in error.
Can you check the byte array you received? What is its size? And try to print its starting few values.
Byte array is not received directly. It comes inside an AS object. The real question here is how to get this byte array inside the ActionScript object to a Java byte array object.
I am the aforesaid Java developer and I am doing this.

Categories

Resources